问:
Multiple File Associations in VSCode for Mixed PHP and JS Syntax Highlighting
I have a file, source.php, that contains Javascript after the closing PHP tag.  Is there a way to make Visual Studio Code do syntax highlighting/completion on the Javascript code.  It currently only highlights the PHP code.

It'd be great if settings.json supported something like the following:

```<code>"files.associations": {
    "source.php": ["javascript", "php"]
}
</code>```

答:
This extension could help.
One Dark Theme

It is based in this Git Repo : https://github.com/atom/one-dark-syntax

Body:
I have a file, source.php, that contains Javascript after the closing PHP tag.  Is there a way to make Visual Studio Code do syntax highlighting/completion on the Javascript code.  It currently only highlights the PHP code.

It'd be great if settings.json supported something like the following:

"files.associations": {
    "source.php": ["javascript", "php"]
}


来源: stackexchange

问:
Add content based on what div is above
I'm working on a customization, and can't change the HTML. Unfortunately it's terrible.

It has the following format:

```<code><div>Thursday 28-02-2015</div>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
//And so on
</code>```

And I need to extract the content from the div, and add it as an :after to each table cell. So a bit of jQuery comes in handy.

```<code>var a = $("div").text();
$("td").append("<span>" + a + "</span>");
</code>```

The trouble is, the HTML repeats itself. So how can I make the jQuery choose the right div? The right div is the first div above the table.

Sample HTML

Thursday 28-02-2015

Some content

Some content

Some content

Friday 29-02-2015

Some content

Some content

Some content

Saturday 30-02-2015

Some content

Some content

Some content

```
</div>
</div>
</p>

<p>Expected Output</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Thursday 28-02-2015</div>
<table><tr><td>Some content<span>Thursday 28-02-2015</span></td></tr></table>
<table><tr><td>Some content<span>Thursday 28-02-2015</span></td></tr></table>
<table><tr><td>Some content<span>Thursday 28-02-2015</span></td></tr></table>
<div>Friday 29-02-2015</div>
<table><tr><td>Some content<span>Friday 29-02-2015</span></td></tr></table>
<table><tr><td>Some content<span>Friday 29-02-2015</span></td></tr></table>
<table><tr><td>Some content<span>Friday 29-02-2015</span></td></tr></table>
<div>Saturday 30-02-2015</div>
<table><tr><td>Some content<span>Saturday 30-02-2015</span></td></tr></table>
<table><tr><td>Some content<span>Saturday 30-02-2015</span></td></tr></table>
<table><tr><td>Some content<span>Saturday 30-02-2015</span></td></tr></table></code>```

答:
Edit: Realized I overcomplicated this. You can simply loop through each div with an .each() function and grab its contents to add into the tables after it.

You can use .next(), repeated as necessary, to get the next however many tables.

$(function(){
  $('div').each(function(){
    var a = $(this).text();
    $(this).next().find('td')
    .add($(this).next().next().find('td'))
    .add($(this).next().next().next().find('td'))
    .after('' + a + '');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Thursday 28-02-2015</div>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<div>Friday 29-02-2015</div>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<div>Saturday 30-02-2015</div>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table></code>```

ContentLicense: CC BY-SA 3.0

Title: Add content based on what div is above

Body:
I'm working on a customization, and can't change the HTML. Unfortunately it's terrible.

It has the following format:

Thursday 28-02-2015

Some content

Some content

Some content

//And so on

And I need to extract the content from the div, and add it as an :after to each table cell. So a bit of jQuery comes in handy.

var a = $("div").text();
$("td").append("" + a + "");

The trouble is, the HTML repeats itself. So how can I make the jQuery choose the right div? The right div is the first div above the table.

Sample HTML

Thursday 28-02-2015

Some content

Some content

Some content

Friday 29-02-2015

Some content

Some content

Some content

Saturday 30-02-2015

Some content

Some content

Some content

Expected Output

Thursday 28-02-2015

Some contentThursday 28-02-2015

Some contentThursday 28-02-2015

Some contentThursday 28-02-2015

Friday 29-02-2015

Some contentFriday 29-02-2015

Some contentFriday 29-02-2015

Some contentFriday 29-02-2015

Saturday 30-02-2015

Some contentSaturday 30-02-2015

Some contentSaturday 30-02-2015

Some contentSaturday 30-02-2015

Body:
Edit: Realized I overcomplicated this. You can simply loop through each div with an .each() function and grab its contents to add into the tables after it.

You can use .next(), repeated as necessary, to get the next however many tables.

$(function(){
  $('div').each(function(){
    var a = $(this).text();
    $(this).next().find('td')
    .add($(this).next().next().find('td'))
    .add($(this).next().next().next().find('td'))
    .after('<span>' + a + '</span>');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Thursday 28-02-2015</div>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<div>Friday 29-02-2015</div>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<div>Saturday 30-02-2015</div>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>
<table><tr><td>Some content</td></tr></table>


问:
Verify with absolute certainty that a picture is visible to a user
I need to verify a picture within an img tag is actually being displayed. The images are dynamically created and then sent to the user's browser with javascript. I do wait for the picture loaded event but this isn't enough.

I need to test with certainty if an image is actually being displayed. If I put the image inside a canvas can I use the canvas getImageData(left, top, width, height) method to verify what pixels have been loaded onto the end user's browser?

答:
Unless I'm mistaken, there is absolutely no way to "prove" with complete certainty what is being rendered on a client's machine, since they could be running any number of scripts client-side that might change or alter what they're actually seeing. You can't "prove" that an unknown user isn't running the Chuck Norris Picture Replacement plugin on Chrome, for example (yes, that's a real thing). They could literally be seeing anything.

And here, I intend to use the word "prove" in the strict sense, not necessarily in the legal sense. To prove something legally in a civil case, you need only a preponderance of the evidence (i.e., anything that would make it more than 50% likely that it's true). So if you can show that it's more likely than not that they saw the picture (as it's unlikely they're using the Chuck Norris Picture Replacement plugin, for example), then you have "proven" that they saw the image as far as you would need to for legal purposes. (I happen to be a lawyer in addition to a web developer, if that generates any additional confidence in the answer I provided).


问:
Firebase: Authenticated user with full permissions gets PERMISSION DENIED on root
Set rules in Firebase console:

```<code>{
  "rules": {
    ".read": true,
    ".write": true
  }
}
</code>```

Run in Chrome console:

```<code>> firebase.database().ref().set('foo');
</code>```

Database tab of Firebase Console now reflects foo.

Set rules in Firebase console:

```<code>{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
</code>```

Run in Chrome console:

```<code>> firebase.auth().signInAnonymously()
< A {W: 1, sa: undefined, u: null, oa: null, fb: nul…}
> firebase.database().ref().set('bar');
Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied
</code>```

Firebase is set up to allow anonymous and Google users, both of which get PERMISSION DENIED when I attempt to read or write.

EDIT

I've added an example project here:

https://github.com/formido/react-firebaseui-web-stackoverflow-question

If I set my rules to:

```<code>{
  "rules": {
    ".read": "auth != null",
    "44358340": { ".write": true }
  }
}
</code>```

...and log in, the console will print Timestamp written.

If I set my rules to:

```<code>{
  "rules": {
    ".read": "auth != null",
    "44358340": { ".write": "auth != null" }
  }
}
</code>```

...and log in, the console will print PERMISSION DENIED.

The most relevant part of the code I'm aware of is:

```<code>  componentDidMount() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        const ref = firebase.database().ref("/44358340");
        if (user) {
          const timestamp = firebase.database.ServerValue.TIMESTAMP;
          ref.set(timestamp).then((error) => {
            if (error) {
              console.error(error);
            }
            else {
              console.log('Timestamp written');
            }
          });
        }
      }
      this.setState({loading: false, user});
    });
  }
</code>```

It's hosted on an Amazon server. I thought maybe I had to set the AUTH_DOMAIN to the AWS host, but that didn't make a difference.

答:
It was a bug. See discussion starting here.

Fix here and it was deployed in Firebase 4.1.2.

Body:
Set rules in Firebase console:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Run in Chrome console:

> firebase.database().ref().set('foo');

Database tab of Firebase Console now reflects foo.

Set rules in Firebase console:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Run in Chrome console:

> firebase.auth().signInAnonymously()
 firebase.database().ref().set('bar');
Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied

Firebase is set up to allow anonymous and Google users, both of which get PERMISSION DENIED when I attempt to read or write.

EDIT

I've added an example project here:

https://github.com/formido/react-firebaseui-web-stackoverflow-question

If I set my rules to:

{
  "rules": {
    ".read": "auth != null",
    "44358340": { ".write": true }
  }
}

...and log in, the console will print Timestamp written.

If I set my rules to:

{
  "rules": {
    ".read": "auth != null",
    "44358340": { ".write": "auth != null" }
  }
}

...and log in, the console will print PERMISSION DENIED.

The most relevant part of the code I'm aware of is:

  componentDidMount() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        const ref = firebase.database().ref("/44358340");
        if (user) {
          const timestamp = firebase.database.ServerValue.TIMESTAMP;
          ref.set(timestamp).then((error) => {
            if (error) {
              console.error(error);
            }
            else {
              console.log('Timestamp written');
            }
          });
        }
      }
      this.setState({loading: false, user});
    });
  }

It's hosted on an Amazon server. I thought maybe I had to set the AUTH_DOMAIN to the AWS host, but that didn't make a difference.


问:
Sort DRF serializer output of nested Serializer field by child's field
I have two serializers, in which one refers to the other with a many=True relationship.

```<code>class AttributeInParentSerializer(ModelSerializer):
    masterdata_type = CharField(max_length=256, source='masterdata_type_id')

    class Meta:
        model = Attribute
        fields = ('uuid', 'masterdata_type')

class ArticleInArticleSetSerializer(ModelSerializer):
    attributes = AttributeInParentSerializer(many=True)

    class Meta:
        model = Article
        fields = ('uuid', 'attributes')
</code>```

The ordering of the attributes in the Article are not always the same, but I want to output them in the same order, so in this case ordering on the field masterdata_type. How can I accomplish this? Note that I do not want to change any client of the serializer if possible, and surely not any model.

答:
You can't set the ordering on ArticleInArticleSetSerializer but you can set the ordering of attributes on AttributeInParentSerializer. This is because you can only set the ordering when you are consuming a serializer rather than when you're defining one.

You could perhaps set it in the __init__ method when the queryset or data is passed in, but then you're making assumptions on what is being passed in. I'd probably end up specifying it in the consumers of ArticleInArticleSetSerializer to avoid any future problems with passing in a list to the serializer.

Body:
I have two serializers, in which one refers to the other with a many=True relationship.

class AttributeInParentSerializer(ModelSerializer):
    masterdata_type = CharField(max_length=256, source='masterdata_type_id')

    class Meta:
        model = Attribute
        fields = ('uuid', 'masterdata_type')

class ArticleInArticleSetSerializer(ModelSerializer):
    attributes = AttributeInParentSerializer(many=True)

    class Meta:
        model = Article
        fields = ('uuid', 'attributes')

The ordering of the attributes in the Article are not always the same, but I want to output them in the same order, so in this case ordering on the field masterdata_type. How can I accomplish this? Note that I do not want to change any client of the serializer if possible, and surely not any model.


问:
Calls to BluetoothLEDevice.FromIdAsync doesn't work after the windows 10 creators update
I wrote a code to connect to my bluetoothLE device. It was working fine before the windows 10 creators build update. After the update, when the program reaches the line of code bellow:

```<code>bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(bleDevice.Id);
</code>```

It stays on that line forever. I've seen some workarounds for this problems but just for UWP projects. Any idea in how could I solve this problem?

答:
After reading this thread I found out a solution. While Microsoft doesn't fix the broken API, the easiest way to make the code work is add an AppID on windows registry. Here the steps to solve the problem:

Open regedit (type regedit.exe on search bar);

On Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppId add a new key (right click "new>key") with the name of your executable for your client process (for example, "YourClient.exe");

Right click on the right of the regedit window, then "new">"string value". After that, edit the "Name" property to be "AppID". Then, change the "Data" value to your program Id;

Add a new key on registry, similarly with the step 2, but with the Id of your executable;

Right click on the right of the regedit window, then "new">"DWORD value". Change the "Name" property to "AuthenticationLevel". Then change the "Data" value to 1.

Body:
I wrote a code to connect to my bluetoothLE device. It was working fine before the windows 10 creators build update. After the update, when the program reaches the line of code bellow:

bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(bleDevice.Id);

It stays on that line forever. I've seen some workarounds for this problems but just for UWP projects. Any idea in how could I solve this problem?


问:
MYSQL DBDump Error message
I need to get a DBDUMP, i am using MySQL.
I get the following error when i try to get a DB Dump. Any clue what it did wrong.</p>

```<code>C:\Program Files\MySQL\MySQL Server 5.1\bin>mysqldump -u root -p xxx myDB
e >  dump.sql
Enter password: ***
mysqldump: Got error: 1049: Unknown database 'xxx' when selecting the database
</code>```

答: If you use localhost with basic user=root,password=<blank> just copy this mysqldump -d -u root -l dbname

Title: MYSQL DBDump Error message

Body:
I need to get a DBDUMP, i am using MySQL.
I get the following error when i try to get a DB Dump. Any clue what it did wrong.

C:\Program Files\MySQL\MySQL Server 5.1\bin>mysqldump -u root -p xxx myDB
e >  dump.sql
Enter password: ***
mysqldump: Got error: 1049: Unknown database 'xxx' when selecting the database


问:
Java JTextfields
Just a quick question,
How do i ensure my JtextField only accepts numeric values?
I want it to to diplsy an error message if the user entered anything else
thank you</p>

答:
You can use a JFormattedTextField.  Construct it using a NumberFormatter and it will only accept numbers.

The JFormattedTextField has a bunch of configurable options that let you decide how bad input is handled.  I recommend looking at the documentation.

ContentLicense: CC BY-SA 2.5

Title: Java JTextfields


问:
Trying to replace the evaluate function. Having an issue with 1 particular case
I am having a heck of a time trying to figure this out. I'm trying to replace this evaluate function.

```<code><cfoutput>
 #evaluate('#qry#.#editVal#')#
</cfoutput>
</code>```

But I just can't seem to work it out. Both qry and editVal are in the variables scope and when using evaluate it returns a value for instane the value of

```<code>#qryVitals.PULSE#
</code>```

I just can't seem to get the notation right to interpret it. Any help would be greatly appreciated.

答:
#evaluate('#qry#.#editVal#')# is equivalent to #VARIABLES[qry][editVal]#.

As noted by @Leigh, if VARIABLES[qry] is of type query, you have to specify the row number as well, e.g. #VARIABLES[qry][editVal][1]#.

Body:
I am having a heck of a time trying to figure this out. I'm trying to replace this evaluate function.

<cfoutput>
 #evaluate('#qry#.#editVal#')#
</cfoutput>

But I just can't seem to work it out. Both qry and editVal are in the variables scope and when using evaluate it returns a value for instane the value of

#qryVitals.PULSE#

I just can't seem to get the notation right to interpret it. Any help would be greatly appreciated.


问:
How to log or notify when a column is truncated using a LEFT()
As part of our OLAP modeling workflow, we are often truncating fields as upstream data sources have no restrictions or defined data types. A field which should be a 10 character string can sometimes be 50 or 100 characters long if it is a free form user input. I've been told this can cause problems with downstream processes which involve uploads to external sources.

I've been asked to find a way to identify instances in which one ore more of these fields is truncated.

How we handle these fields now is something like this:

```<code>SELECT
    LEFT(FreeResponseField, 10) AS Comment
INTO
    dbo.ModeledTable
FROM
    dbo.SourceTable
</code>```

Essentially if the field is greater than 10 characters, who cares, we only take the first 10.

If dbo.SourceTable.FreeResponseField has a length greater than 10, now we want to know somehow (be it a warning/error message or insertion into a log table). We have a lot of tables with a lot of fields, so the above example is a simplification. Identifying just the field in which this occurs and/or the tuple in the table would be helpful to see where these issues are occurring.

Is something like this possible? You can't just compare data types of the source table with the target table as the source table sets everything to essentially VARCHAR(MAX). The naive approach is to check the length every single value of every tuple against the defined length of the target table.

答:
The original specifications weren't descriptive, but I've figured out a solution and thought I'd share in case anyone stumbles across this for some reason.

Imagine we have a SourceTable which are pulling in to our model. We have defined zip codes as being of length 5 and addresses of being length 25. Say we have the following two records:

```<code>CustomerID | ZipCode | Address
         1 |   90210 | 123 Fake Street
         2 |  902106 | 546 Fake Street
</code>```

Based on our model definitions, there is an error with ZipCode for the record where CustomerID equals 2. We would like to identify both ZipCode as being the problem field and the record where CustomerID equals 2. The following query with a CROSS APPLY does that:

```<code>WITH CTE AS (
    SELECT
        CustomerID,
        ZipCodeFlag = IIF(LEN(ZipCode) > 5, 1, 0),
        AddressFlag = IIF(Len(Address) > 25, 1, 0),
        ZipCode,
        Address
    FROM
        SourceTable
)
SELECT
    CustomerID,
    TruncatedField,
    RawValue
FROM
    CTE
CROSS APPLY (
    VALUES ('ZipCode', ZipCodeFlag, ZipCode),
           ('Address', AddressFlag, Address)
) CA(TruncatedField, TruncatedFlag, RawValue)
WHERE
    TruncatedFlag = 1
ORDER BY
    CustomerID
</code>```

With the following output:

```<code>CustomerID | TruncatedField | RawValue
         2 |        ZipCode |   902106
</code>```

Body:
As part of our OLAP modeling workflow, we are often truncating fields as upstream data sources have no restrictions or defined data types. A field which should be a 10 character string can sometimes be 50 or 100 characters long if it is a free form user input. I've been told this can cause problems with downstream processes which involve uploads to external sources.

I've been asked to find a way to identify instances in which one ore more of these fields is truncated.

How we handle these fields now is something like this:

SELECT
    LEFT(FreeResponseField, 10) AS Comment
INTO
    dbo.ModeledTable
FROM
    dbo.SourceTable

Essentially if the field is greater than 10 characters, who cares, we only take the first 10.

If dbo.SourceTable.FreeResponseField has a length greater than 10, now we want to know somehow (be it a warning/error message or insertion into a log table). We have a lot of tables with a lot of fields, so the above example is a simplification. Identifying just the field in which this occurs and/or the tuple in the table would be helpful to see where these issues are occurring.

Is something like this possible? You can't just compare data types of the source table with the target table as the source table sets everything to essentially VARCHAR(MAX). The naive approach is to check the length every single value of every tuple against the defined length of the target table.

Body:
The original specifications weren't descriptive, but I've figured out a solution and thought I'd share in case anyone stumbles across this for some reason.

Imagine we have a SourceTable which are pulling in to our model. We have defined zip codes as being of length 5 and addresses of being length 25. Say we have the following two records:

CustomerID | ZipCode | Address
         1 |   90210 | 123 Fake Street
         2 |  902106 | 546 Fake Street

Based on our model definitions, there is an error with ZipCode for the record where CustomerID equals 2. We would like to identify both ZipCode as being the problem field and the record where CustomerID equals 2. The following query with a CROSS APPLY does that:

WITH CTE AS (
    SELECT
        CustomerID,
        ZipCodeFlag = IIF(LEN(ZipCode) > 5, 1, 0),
        AddressFlag = IIF(Len(Address) > 25, 1, 0),
        ZipCode,
        Address
    FROM
        SourceTable
)
SELECT
    CustomerID,
    TruncatedField,
    RawValue
FROM
    CTE
CROSS APPLY (
    VALUES ('ZipCode', ZipCodeFlag, ZipCode),
           ('Address', AddressFlag, Address)
) CA(TruncatedField, TruncatedFlag, RawValue)
WHERE
    TruncatedFlag = 1
ORDER BY
    CustomerID

With the following output:

CustomerID | TruncatedField | RawValue
         2 |        ZipCode |   902106


问:
How to check if there is an item in an array that exists in another array?
I have the following React code that I want to use to disable a button:

```<code>todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)
</code>```

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.

答:
You can use include in combination with some for succinctness

var arr1=[1,2,3,4,5,6,7];

var arr2=[8,9,10];

var arr3=[2,1,3,4,5,6,7];

if(arr1.some((x)=> arr2.includes(x))){
console.log('true');
//do something
}else{
console.log(false);
//do something
};

if(arr1.some((x)=> arr3.includes(x))){
console.log('true');
//do something
}else{
console.log(false);
//do something
};

// something even shorter would be
arr1.some((x)=> arr2.includes(x))?console.log(true):console.log(false)```

Body:
I have the following React code that I want to use to disable a button:

todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.


问:
Python logging configuration file
I seem to be having some issues while attempting to implement logging into my python project.

I'm simply attempting to mimic the following configuration:

Python Logging to Multiple Destinations

However instead of doing this inside of code, I'd like to have it in a configuration file.

Below is my config file:

```<code>[loggers]
keys=root

[logger_root]
handlers=screen,file

[formatters]
keys=simple,complex

[formatter_simple]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[formatter_complex]
format=%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s

[handlers]
keys=file,screen

[handler_file]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=complex
level=DEBUG
args=('logs/testSuite.log',)

[handler_screen]
class=StreamHandler
formatter=simple
level=INFO
args=(sys.stdout,)
</code>```

The problem is that my screen output looks like:

      2010-12-14 11:39:04,066 - root - WARNING - 3

      2010-12-14 11:39:04,066 - root - ERROR - 4

      2010-12-14 11:39:04,066 - root - CRITICAL - 5

My file is output, but looks the same as above (although with the extra information included).  However the debug and info levels are not output to either.

I am on Python 2.7

Here is my simple example showing failure:

```<code>import os
import sys
import logging
import logging.config

sys.path.append(os.path.realpath("shared/"))
sys.path.append(os.path.realpath("tests/"))

class Main(object):

  @staticmethod
  def main():
    logging.config.fileConfig("logging.conf")
    logging.debug("1")
    logging.info("2")
    logging.warn("3")
    logging.error("4")
    logging.critical("5")

if __name__ == "__main__":
  Main.main()
</code>```

答:
Adding the following line to the root logger took care of my problem:  </p>

```<code>level=NOTSET
</code>```

Title: Python logging configuration file

Body:
I seem to be having some issues while attempting to implement logging into my python project.

I'm simply attempting to mimic the following configuration:

Python Logging to Multiple Destinations

However instead of doing this inside of code, I'd like to have it in a configuration file.

Below is my config file:

[loggers]
keys=root

[logger_root]
handlers=screen,file

[formatters]
keys=simple,complex

[formatter_simple]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[formatter_complex]
format=%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s

[handlers]
keys=file,screen

[handler_file]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=complex
level=DEBUG
args=('logs/testSuite.log',)

[handler_screen]
class=StreamHandler
formatter=simple
level=INFO
args=(sys.stdout,)

The problem is that my screen output looks like:

      2010-12-14 11:39:04,066 - root - WARNING - 3

      2010-12-14 11:39:04,066 - root - ERROR - 4

      2010-12-14 11:39:04,066 - root - CRITICAL - 5

My file is output, but looks the same as above (although with the extra information included).  However the debug and info levels are not output to either.

I am on Python 2.7

Here is my simple example showing failure:

import os
import sys
import logging
import logging.config

sys.path.append(os.path.realpath("shared/"))
sys.path.append(os.path.realpath("tests/"))

class Main(object):

  @staticmethod
  def main():
    logging.config.fileConfig("logging.conf")
    logging.debug("1")
    logging.info("2")
    logging.warn("3")
    logging.error("4")
    logging.critical("5")

if __name__ == "__main__":
  Main.main()

Body:
Adding the following line to the root logger took care of my problem:

level=NOTSET


问:
PHP look through every root directory for keyword
So I tried for some days to get this done. But I still don't have a single clue how i could build this code so it works. Maybe someone has an idea.

Goal: Automaticely iterate through the root-directory and any of it's subdirectories. If there's a directory, which matches the keyword it should be stored into an array.

I am only looking for directories, that's why there's a regex to exclude every object with a dot in it's name. Not perfect yet, but that's not a problem.

I ll post the first version of my code. Now it's just scanning the directory your handling to the function when calling it. Because all my other attempts are trash and this one at least works

```<code>searchformigration('/');

/* Check for related folders, that could be used for a migration */
function searchformigration($dir)
{
    $scanned_elements = scandir($dir);

    for($c = 0; $c <= (count($scanned_elements) - 1); $c++)
    {
        /* Anything but files containing a dot (hidden files, files) */
        if(preg_match('/^[^.]+$/', $scanned_elements[$c]))
        {
            /* Checking for the keyword "Project" */
            if($scanned_elements[$c] == '*Project*')
            {
                echo $scanned_elements[$c];
                echo '</br>';
            }
            else
            {
                continue;
            }
        }
        else
        {
            continue;
        }
    }
}
</code>```

答:
I would get all directories recursively and then grep for Project:

```<code>function searchformigration($dir) {
    $results = glob($dir, GLOB_ONLYDIR);

    foreach($results as $subdir) {
        $results = array_merge($results, searchformigration($subdir));
    }
    return $results;
}

$results = preg_grep('/Project/', searchformigration('/'));
</code>```

You can also do this on Linux:

```<code>exec("find / -type d -name 'Project'", $results);
</code>```

Body:
So I tried for some days to get this done. But I still don't have a single clue how i could build this code so it works. Maybe someone has an idea.

Goal: Automaticely iterate through the root-directory and any of it's subdirectories. If there's a directory, which matches the keyword it should be stored into an array.

I am only looking for directories, that's why there's a regex to exclude every object with a dot in it's name. Not perfect yet, but that's not a problem.

I ll post the first version of my code. Now it's just scanning the directory your handling to the function when calling it. Because all my other attempts are trash and this one at least works

searchformigration('/');

/* Check for related folders, that could be used for a migration */
function searchformigration($dir)
{
    $scanned_elements = scandir($dir);

    for($c = 0; $c <= (count($scanned_elements) - 1); $c++)
    {
        /* Anything but files containing a dot (hidden files, files) */
        if(preg_match('/^[^.]+$/', $scanned_elements[$c]))
        {
            /* Checking for the keyword "Project" */
            if($scanned_elements[$c] == '*Project*')
            {
                echo $scanned_elements[$c];
                echo '
';
            }
            else
            {
                continue;
            }
        }
        else
        {
            continue;
        }
    }
}

Body:
I would get all directories recursively and then grep for Project:

function searchformigration($dir) {
    $results = glob($dir, GLOB_ONLYDIR);

    foreach($results as $subdir) {
        $results = array_merge($results, searchformigration($subdir));
    }
    return $results;
}

$results = preg_grep('/Project/', searchformigration('/'));

You can also do this on Linux:

exec("find / -type d -name 'Project'", $results);


问:
Inserting images using jQuery .html
I have a counter that counts in dollars. Each number, as well as the dollar sign and comma, are all displayed on the page using images. I use display: flex; in my container div and flex: 1 1 auto; on the divs that hold the images. I use this CSS so that it all shrinks as more numbers are added.

Here is a jsfiddle to see the issue.
https://jsfiddle.net/0mvy8hqo/

Here is the CSS I am using

```<code>.i15-counter .i15-counter-inner { display: flex; }
.i15-counter .i15-counter-inner .i15-counter-number { flex: 1 1 auto; max-width: 110px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-dollar { flex: 1 1 auto; max-width: 76px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-comma { flex: 1 1 auto; max-width: 40px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-first {
  padding: 20px 0px 20px 20px;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-bottom-left-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-bottomleft: 5px;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.i15-counter .i15-counter-inner .i15-counter-last {
  padding: 20px 20px 20px 0px;
  -webkit-border-top-right-radius: 5px;
  -webkit-border-bottom-right-radius: 5px;
  -moz-border-radius-topright: 5px;
  -moz-border-radius-bottomright: 5px;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}
</code>```

I also use jQuery to update the counter every second based on some math I have set up in my code. This all works just fine. My only issue is that if the amount of images displayed on the page is enough that the images shrink then when I have my javascript replace the images with new images as the counter increases, the images start out at full size and then shrink to fit the container. So rather than it just looking like the number is changing, you have this expand/shrink effect that I would like to get rid of. This happens for about a minute then it stops. I am guessing the stopping has something to do with the browser's cache, but I am not sure.

Here is the Javascript I am using.

```<code>function number_format (number, decimals, dec_point, thousands_sep) {
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function updateCounters(id) {
  var current = parseInt(jQuery('.i15-counter-'+id+'-current').val());
  var next = parseInt(jQuery('.i15-counter-'+id+'-next').val());
  var rate = parseInt(jQuery('.i15-counter-'+id+'-rate').val());
  var image_url = jQuery('.i15-counter-'+id+'-image-url').val();

  var new_current = current + rate;

  if(new_current <= next) {
    var new_current_formatted = number_format(new_current, 0);
    var new_current_formatted_adddollar = '$' + new_current_formatted;
    var new_current_split = new_current_formatted_adddollar.split("");
    //console.log(new_current_formatted);
    var numbercount = 1;
    var numbertotal = new_current_split.length;
    var counter_html = "";

    jQuery.each( new_current_split, function( i, val ) {
      var number_ends = "";
      if(numbercount == 1) {
        number_ends += " i15-counter-first";
      }

      if(numbercount == numbertotal) {
        number_ends += " i15-counter-last";
      }

      var anumber_class = "i15-counter-number";
      if(val == "$") { val = "dollar"; anumber_class = "i15-counter-dollar"; }
      if(val == ",") { val = "comma"; anumber_class = "i15-counter-comma"; }

      counter_html += '<div class="' + anumber_class + number_ends + '"><img src="' + image_url + 'counter_' + val + '.png" /></div>';
      numbercount++;
    });

    jQuery('.i15-counter-container-'+id).html(counter_html);
    jQuery('.i15-counter-'+id+'-current').val(new_current);
  }
}

jQuery(document).ready( function($) {

  window.setInterval(function(){
    jQuery(".i15-counter").each(function() {
      updateCounters(jQuery(this).data('id'));
    });
  }, 1000);

})
</code>```

答:
Like @ZPiDER mentioned you have to preload the assets

I have attached the fiddle with preload functionality

```<code>var images = new Array();
        function preload() {
            for (i = 0; i < preload.arguments.length; i++) {
                images[i] = new Image()
                images[i].src = preload.arguments[i]
            }
        }
</code>```

https://jsfiddle.net/0mvy8hqo/1/

Title: Inserting images using jQuery .html

Body:
I have a counter that counts in dollars. Each number, as well as the dollar sign and comma, are all displayed on the page using images. I use display: flex; in my container div and flex: 1 1 auto; on the divs that hold the images. I use this CSS so that it all shrinks as more numbers are added.

Here is a jsfiddle to see the issue.
https://jsfiddle.net/0mvy8hqo/

Here is the CSS I am using

.i15-counter .i15-counter-inner { display: flex; }
.i15-counter .i15-counter-inner .i15-counter-number { flex: 1 1 auto; max-width: 110px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-dollar { flex: 1 1 auto; max-width: 76px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-comma { flex: 1 1 auto; max-width: 40px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-first {
  padding: 20px 0px 20px 20px;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-bottom-left-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-bottomleft: 5px;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.i15-counter .i15-counter-inner .i15-counter-last {
  padding: 20px 20px 20px 0px;
  -webkit-border-top-right-radius: 5px;
  -webkit-border-bottom-right-radius: 5px;
  -moz-border-radius-topright: 5px;
  -moz-border-radius-bottomright: 5px;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

I also use jQuery to update the counter every second based on some math I have set up in my code. This all works just fine. My only issue is that if the amount of images displayed on the page is enough that the images shrink then when I have my javascript replace the images with new images as the counter increases, the images start out at full size and then shrink to fit the container. So rather than it just looking like the number is changing, you have this expand/shrink effect that I would like to get rid of. This happens for about a minute then it stops. I am guessing the stopping has something to do with the browser's cache, but I am not sure.

Here is the Javascript I am using.

function number_format (number, decimals, dec_point, thousands_sep) {
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function updateCounters(id) {
  var current = parseInt(jQuery('.i15-counter-'+id+'-current').val());
  var next = parseInt(jQuery('.i15-counter-'+id+'-next').val());
  var rate = parseInt(jQuery('.i15-counter-'+id+'-rate').val());
  var image_url = jQuery('.i15-counter-'+id+'-image-url').val();

  var new_current = current + rate;

  if(new_current <= next) {
    var new_current_formatted = number_format(new_current, 0);
    var new_current_formatted_adddollar = '$' + new_current_formatted;
    var new_current_split = new_current_formatted_adddollar.split("");
    //console.log(new_current_formatted);
    var numbercount = 1;
    var numbertotal = new_current_split.length;
    var counter_html = "";

    jQuery.each( new_current_split, function( i, val ) {
      var number_ends = "";
      if(numbercount == 1) {
        number_ends += " i15-counter-first";
      }

      if(numbercount == numbertotal) {
        number_ends += " i15-counter-last";
      }

      var anumber_class = "i15-counter-number";
      if(val == "$") { val = "dollar"; anumber_class = "i15-counter-dollar"; }
      if(val == ",") { val = "comma"; anumber_class = "i15-counter-comma"; }

      counter_html += '

';
      numbercount++;
    });

    jQuery('.i15-counter-container-'+id).html(counter_html);
    jQuery('.i15-counter-'+id+'-current').val(new_current);
  }
}

jQuery(document).ready( function($) {

  window.setInterval(function(){
    jQuery(".i15-counter").each(function() {
      updateCounters(jQuery(this).data('id'));
    });
  }, 1000);

})

Body:
Like @ZPiDER mentioned you have to preload the assets

I have attached the fiddle with preload functionality

var images = new Array();
        function preload() {
            for (i = 0; i < preload.arguments.length; i++) {
                images[i] = new Image()
                images[i].src = preload.arguments[i]
            }
        }

https://jsfiddle.net/0mvy8hqo/1/


问:
How to convert hashmap from android to dictionary in Python?

Below is the code which is sent as Android response to Python

```<code>{key1=value1,key2=value2}
</code>```

答:
```<code>for kv in '{key1=value1,key2=value2}'[1:-1].split(','):
    key, value = kv.split('=')
    my_dict[key] = value
</code>```

Body:
Below is the code which is sent as Android response to Python

{key1=value1,key2=value2}


问:
DateTime from SQL database with value null
I want to get datetime from SQL database and store it in a DateTime property.
At the moment it has value null.
I keep getting conversion error.
Programming in C# with MVVM.

```<code>private void LoadFunctie()
    {
        _myModel = new ObservableCollection<myModel>();
        DataTable DT = new DataTable();
        DT =
        clsDAC.ExecuteDataTable(Properties.Resources.S_myStoredProcedure);
        foreach (DataRow DR in DT.Rows)
        {
            var x = new clsOrderOverzichtM()
            {
                SomeID = (int)DR[0],//works
                SomeString = DR[1].ToString(),//works
                SomeDate = (DateTime)DR[2]//ERROR

            };
            _myModel.Add(x);
        }
    }
</code>```

My Property

```<code>    private DateTime? _SomeDate;
    public DateTime? SomeDate
    {
        get { return _SomeDate; }
        set
        {
            _SomeDate = value;
            RaisePropertyChanged();
        }
    }
</code>```

What could be my problem?

答:
If the column allows null values then you have to check for DBNull when you read from it. The easiest way to do this on a DataRow is with IsNull. The line of code would then be:

```<code>SomeDate = DR.IsNull(2) ? null : (DateTime?)DR[2]
</code>```

The assignment type you are using should then also be nullable or have an acceptable default value.

Body:
I want to get datetime from SQL database and store it in a DateTime property.
At the moment it has value null.
I keep getting conversion error.
Programming in C# with MVVM.

private void LoadFunctie()
    {
        _myModel = new ObservableCollection<myModel>();
        DataTable DT = new DataTable();
        DT =
        clsDAC.ExecuteDataTable(Properties.Resources.S_myStoredProcedure);
        foreach (DataRow DR in DT.Rows)
        {
            var x = new clsOrderOverzichtM()
            {
                SomeID = (int)DR[0],//works
                SomeString = DR[1].ToString(),//works
                SomeDate = (DateTime)DR[2]//ERROR

            };
            _myModel.Add(x);
        }
    }

My Property

    private DateTime? _SomeDate;
    public DateTime? SomeDate
    {
        get { return _SomeDate; }
        set
        {
            _SomeDate = value;
            RaisePropertyChanged();
        }
    }

What could be my problem?

Body:
If the column allows null values then you have to check for DBNull when you read from it. The easiest way to do this on a DataRow is with IsNull. The line of code would then be:

SomeDate = DR.IsNull(2) ? null : (DateTime?)DR[2]

The assignment type you are using should then also be nullable or have an acceptable default value.


问:
Google Checkout Account Username
I'm looking for a method that returns me the Google Checkout User Account of the owner of the telephone...

I explain: when I buy an application over the market, in the phone is stored somewhere the Google Account that I use to purchase the app (that maybe can be different from the main google main account?). I need a method, if exists, that gives me this account (only the username, I don't need the password!).

Thanx in advance

答: I don't think you can retrieve that information, since I would consider it to be private data.</p>

Title: Google Checkout Account Username


问:
Windows Command Line - Select Server Based upon Ping Latency
Ok basic premise here is that there are two servers with the same files.

I'm using Windows command line scripts and opening a network share to either of those hosts. I'd like to make the script "smart" so it works out the latency between the two servers and picks the lowest latency host to connect to.

I want to do something like (i know this code doesn't work, it's an example of my concept):

```<code>PING 192.168.0.1
SET HOST1=%ERRORLEVEL%
PING 192.168.0.2
SET HOST2=%ERRORLEVEL%
IF HOST1 GTR HOST2 GOTO HOST2CONNECT
:HOST1CONNECT
NET USE X: \\HOST1 (etc)
:HOST2CONNECT
NET USE X: \\HOST2 (etc)
</code>```

Does that make any sense? I just can't seem to visualise a way of comparing the data from the two PING tests and i know that ERRORLEVEL in this situation is just a 1 or 0 based upon whether the ping is successful or not, so it's garbage as they'll both succeed. But i'm hoping you get the concept and can see what i'm missing.

Thanks in advance.

答:
<pre class="lang-dos prettyprint-override"><code>@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Initialize variables
    set "selected="
    set "min=99999999"
    set serverList= "bing.com" "duckduckgo.com" "google.es" "google.com"

    echo - Testing -----------------------------

    rem Enumerate the hosts to check
    for %%a in ( %serverList% ) do (

        rem Ping the host and retrieve the average roundtrip
        for /f "tokens=6 delims== " %%r in ('
            ping -n 1 "%%~a" ^| findstr /r /c:"^  .*ms$"
        ') do for /f "delims=ms" %%t in ("%%r") do (
            echo "%%~a" : %%t ms

            rem Determine if the current host has a lower rtt
            rem if %%t geq min or min is already 0, then we have
            rem a division by 0, else a lower rtt has been found
            set /a "1/(min/(%%t+1))" && (
                set "selected=%%~a"
                set "min=%%t"
            )
            rem Of course this can be done with delayed expansion,
            rem just a question of personal preferences
        )
    ) 2>nul

    echo(
    echo - Selected ----------------------------
    echo %selected% : %min%
</code>```

Body:
Ok basic premise here is that there are two servers with the same files.

I'm using Windows command line scripts and opening a network share to either of those hosts. I'd like to make the script "smart" so it works out the latency between the two servers and picks the lowest latency host to connect to.

I want to do something like (i know this code doesn't work, it's an example of my concept):

PING 192.168.0.1
SET HOST1=%ERRORLEVEL%
PING 192.168.0.2
SET HOST2=%ERRORLEVEL%
IF HOST1 GTR HOST2 GOTO HOST2CONNECT
:HOST1CONNECT
NET USE X: \\HOST1 (etc)
:HOST2CONNECT
NET USE X: \\HOST2 (etc)

Does that make any sense? I just can't seem to visualise a way of comparing the data from the two PING tests and i know that ERRORLEVEL in this situation is just a 1 or 0 based upon whether the ping is successful or not, so it's garbage as they'll both succeed. But i'm hoping you get the concept and can see what i'm missing.

Thanks in advance.


问:
How to match url to controller action
I'm having difficulty getting my my controller action, as this is currently matching the default route (I'm using a typical default route configuration)

```<code>routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
</code>```

Why doesn't my url get routed to this controller action?

My typescript

```<code>let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let update = new CollectionUpdate();
    update.collectionID = Number(this.collectionID);
    update.collectionName = "new name";

    let url = "/api/Collections/RenameCollection/";

    let json = JSON.stringify(update);
    debugger;
    return this.http
        .patch(url, json, { headers: headers })
        .map(res => res.json())
        .subscribe(
        result => {
            this.onRename(result as CollectionUpdate)
        });
</code>```

My controller action

```<code>[HttpPatch]
    public Task<CollectionUpdate> RenameCollection([FromBody]CollectionUpdate update)
    {
        return Task.FromResult<CollectionUpdate>(new CollectionUpdate());
    }
</code>```

答:
Changing it to a put operation worked.  I guess I'll just roll with that.</p>

```<code>        [HttpPut("[action]")]
    public Task<CollectionUpdate> RenameCollection([FromBody]CollectionUpdate update)
</code>```

Title: How to match url to controller action

Body:
I'm having difficulty getting my my controller action, as this is currently matching the default route (I'm using a typical default route configuration)

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");

Why doesn't my url get routed to this controller action?

My typescript

let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let update = new CollectionUpdate();
    update.collectionID = Number(this.collectionID);
    update.collectionName = "new name";

    let url = "/api/Collections/RenameCollection/";

    let json = JSON.stringify(update);
    debugger;
    return this.http
        .patch(url, json, { headers: headers })
        .map(res => res.json())
        .subscribe(
        result => {
            this.onRename(result as CollectionUpdate)
        });

My controller action

[HttpPatch]
    public Task<CollectionUpdate> RenameCollection([FromBody]CollectionUpdate update)
    {
        return Task.FromResult<CollectionUpdate>(new CollectionUpdate());
    }

Body:
Changing it to a put operation worked.  I guess I'll just roll with that.

        [HttpPut("[action]")]
    public Task<CollectionUpdate> RenameCollection([FromBody]CollectionUpdate update)


问:
Dynamic HTML controls through jQuery?
I have the following section of javascript/jQuery trying to create a grid overlay on a picture:

```<code>var $tbl = $('<table></table>');
for (var y = 1; y <= $rows; y++) {
    var $tr = $('<tr></tr>');
    for (var x = 1; x <= $cols; x++) {
        var $td = $('<td><input class = "chkDamage" type="checkbox" /></td>'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $tr.append($td);

    }
    $tbl.append($tr);
}
</code>```

What I would like to do is to dynamically have a class name or id associated with each of the td elements so that I'm able to grab which squares are checked for later usage.  Is something like that possible?

答:
You can do something like below.

I have attached a click handler to all checkbox. So when the user clicks a checkbox, I am finding the closest tr and check add a css class called changed.

jQuery closest will traverse up in the parent order hierarchy and returns a dom node based on the selector which is passed.

```<code>$(document).ready(function() {
   $(document).on("click", "input[type=checkbox]", function() {
      // Add condition to see if checked or not and add class or do something
      $(this).closest("tr").addClass("changed");
   }
})
</code>```

Title: Dynamic HTML controls through jQuery?

Body:
I have the following section of javascript/jQuery trying to create a grid overlay on a picture:

var $tbl = $('

');
for (var y = 1; y <= $rows; y++) {
    var $tr = $('

');
    for (var x = 1; x <= $cols; x++) {
        var $td = $('<input class = "chkDamage" type="checkbox" />	'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $tr.append($td);

    }
    $tbl.append($tr);
}

What I would like to do is to dynamically have a class name or id associated with each of the td elements so that I'm able to grab which squares are checked for later usage.  Is something like that possible?

Body:
You can do something like below.

I have attached a click handler to all checkbox. So when the user clicks a checkbox, I am finding the closest tr and check add a css class called changed.

jQuery closest will traverse up in the parent order hierarchy and returns a dom node based on the selector which is passed.

$(document).ready(function() {
   $(document).on("click", "input[type=checkbox]", function() {
      // Add condition to see if checked or not and add class or do something
      $(this).closest("tr").addClass("changed");
   }
})


问:
Escaping single and double quotes in a string in ruby?
How can I escape single and double quotes in a string?

I want to escape single and double quotes together. I know how to pass them separately but don't know how to pass both of them.

e.g: str = "ruby 'on rails" " = ruby 'on rails"

答:
One caveat:

Using %Q[] and %q[] for string comparisons is not intuitively safe.

For example, if you load something meant to signify something empty, like "" or '', you need to use the actual escape sequences. For example, let's say qvar equals "" instead of any empty string.

This will evaluate to false

if qvar == "%Q[]"

As will this,

if qvar == %Q[]

While this will evaluate to true

if qvar == "\"\""

I ran into this issue when sending command-line vars from a different stack to my ruby script. Only Gabriel Augusto's answer worked for me.


问:
Pass sql column values to an array usnig Javascript
I am working with an ASP.net webform and have a SQL select statement that generates a table with a single column. All values of that column would need to be added to an array using javascript, to replace manual entry. Here is a working array example:

```<code>  <script type="text/javascript">

    var addressPoints = [

        [35.393617, -119.038301],
        [33.485073, -86.785173],
        [35.218721, -80.849652],
        [38.678598, -90.373175],
        [37.786996, -90.414874],
        [44.946816, -124.016506]

     </script>
      <script type="text/javascript">
        var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            minZoom: 1,
            maxZoom: 12

        }),
            latlng = L.latLng(35.824322, -98.763128);

        var map = L.map('map', { center: latlng, zoom: 3.8, layers: [tiles] });

        var markers = L.markerClusterGroup();

        for (var i = 0; i < addressPoints.length; i++) {
            var a = addressPoints[i];
            var title = a[2];
            var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
            marker.bindPopup(title);
            markers.addLayer(marker);
        }

        map.addLayer(markers);

    </script>
</code>```

The Coordinates column has been formatted exactly as the Manual entry data you saw in the example above. The below example does not work:

```<code><script type="text/javascript">

        var addressPoints = [
//    Values from a column  "Coordinates" go here//
//    [35.393617, -119.038301],
//    [33.485073, -86.785173],
//    [35.218721, -80.849652],
//    [38.678598, -90.373175],
//    [37.786996, -90.414874],
//    [44.946816, -124.016506]
        ];

</script>
</code>```

If you have any idea how to plug in the Coordinates column into an array using Javascript,  I will really appreciate your help!

答:
It looks like you have already displayed the Coordinates value in the DOM element "Coordinates" - so try this:</p>

```<code><script type="text/javascript">

    var addressPoints = [
        document.getElementById("Coordinates").value;
    ];

</script>
</code>```

Body:
I am working with an ASP.net webform and have a SQL select statement that generates a table with a single column. All values of that column would need to be added to an array using javascript, to replace manual entry. Here is a working array example:

The Coordinates column has been formatted exactly as the Manual entry data you saw in the example above. The below example does not work:

If you have any idea how to plug in the Coordinates column into an array using Javascript,  I will really appreciate your help!

Body:
It looks like you have already displayed the Coordinates value in the DOM element "Coordinates" - so try this:

<script type="text/javascript">

    var addressPoints = [
        document.getElementById("Coordinates").value;
    ];

</script>


问:
opencv\modules\core\src\persistence.cpp:2697: error: (-27) NULL or empty buffer in function cvOpenFileStorage
I am trying to run a facedetection application and I get the following error:  </p>

```<code>Unexpected Standard exception from MEX file.
What() is:..\..\..\..\opencv\modules\core\src\persistence.cpp:2697: error: (-27)
NULL or empty buffer in function cvOpenFileStorage
</code>```

答:
If you're using  haarcascade_frontalface_default.xml, check the xml file content.

The first 3 lines should be:

```<code><?xml version="1.0"?>
<!--
    Stump-based 24x24 discrete(?) adaboost frontal face detector.
</code>```

I inadvertently downloaded the html that linked to the  haarcascade_frontalface_default.xml file instead of the xml itself and got the same error you did.

Body:
I am trying to run a facedetection application and I get the following error:

Unexpected Standard exception from MEX file.
What() is:..\..\..\..\opencv\modules\core\src\persistence.cpp:2697: error: (-27)
NULL or empty buffer in function cvOpenFileStorage

Body:
If you're using  haarcascade_frontalface_default.xml, check the xml file content.

The first 3 lines should be:

<?xml version="1.0"?>
<!--
    Stump-based 24x24 discrete(?) adaboost frontal face detector.

I inadvertently downloaded the html that linked to the  haarcascade_frontalface_default.xml file instead of the xml itself and got the same error you did.


问:
How to install Boost.Python using pip on Windows 10?
I want to install boost.python for the installation of dlib library.</p>

答: You have to compile it for the platform. I believe PIP alone cannot accomplish that feat. You'll have to navigate the arcanery of bjam and boost build. God speed.</p>


问:
How could I convert png binary data into bmp binary data in JAVA?
I got my binary data from database which is in PNG format. Now, I need to change the format to BMP and then convert it to a string by Base64.

My logic is PNG binary-->BMP binary-->BMP base64 String.

My Code is as below. The input "data" is the PNG binary, imageFormat="BMP".

```<code> public static String imageToBase64 (byte[] data, String imageFormat) throws IOException{
         BufferedImage imag=ImageIO.read(new ByteArrayInputStream(data));
         ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
         ImageIO.write(imag, imageFormat, baos);

         String base64String=Base64.encodeBytes(baos.toByteArray());

         return base64String;
     }
</code>```

However, the result always return empty. Can anyone help me to solve this problem?
Thanks

答:
You need to use the Java API to write to a new BMP file. Based on your code this is how it does what you asked.

```<code>public static String imageToBase64(byte[] data, String imageFormat) throws IOException {
    BufferedImage imag = ImageIO.read(new ByteArrayInputStream(data));
    BufferedImage bmpImg = new BufferedImage(imag.getWidth(), imag.getHeight(), BufferedImage.TYPE_INT_RGB);
    bmpImg.createGraphics().drawImage(imag, 0, 0, Color.WHITE, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bmpImg, imageFormat, baos);
    String base64String = Base64.getEncoder().encodeToString(baos.toByteArray());
    return base64String;
}
</code>```

Please note I used "bmp" (lowercase) instead of "BMP". Not sure if this matters. Enjoy.

Body:
I got my binary data from database which is in PNG format. Now, I need to change the format to BMP and then convert it to a string by Base64.

My logic is PNG binary-->BMP binary-->BMP base64 String.

My Code is as below. The input "data" is the PNG binary, imageFormat="BMP".

 public static String imageToBase64 (byte[] data, String imageFormat) throws IOException{
         BufferedImage imag=ImageIO.read(new ByteArrayInputStream(data));
         ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
         ImageIO.write(imag, imageFormat, baos);

         String base64String=Base64.encodeBytes(baos.toByteArray());

         return base64String;
     }

However, the result always return empty. Can anyone help me to solve this problem?
Thanks

Body:
You need to use the Java API to write to a new BMP file. Based on your code this is how it does what you asked.

public static String imageToBase64(byte[] data, String imageFormat) throws IOException {
    BufferedImage imag = ImageIO.read(new ByteArrayInputStream(data));
    BufferedImage bmpImg = new BufferedImage(imag.getWidth(), imag.getHeight(), BufferedImage.TYPE_INT_RGB);
    bmpImg.createGraphics().drawImage(imag, 0, 0, Color.WHITE, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bmpImg, imageFormat, baos);
    String base64String = Base64.getEncoder().encodeToString(baos.toByteArray());
    return base64String;
}

Please note I used "bmp" (lowercase) instead of "BMP". Not sure if this matters. Enjoy.


问:
trouble installing matplotlib python? WINDOWS
So I used pip to install matplotlib module through command line in windows, but when I then try to import the module in python, it says no module is found.

How do I fix this?
When I've tried to install it again, it says the module exists and can be found through my files. However python doesn't seem to be able to link to it to import it?

答:
If you're on Python 2.7, you will want to read the following document at it details how to install MySQLdb1 on the various platforms:

https://github.com/farcepest/MySQLdb1

See the INSTALL file specifically.

Note that this is kind of a legacy module. If you want something that works in Python 3, you might want to check out moist.

There is also PyMySQL, which is compatible with both Python 2.6+ and 3.3+ and it can be installed with pip:

```<code>pip install PyMySQL
</code>```

Body:
If you're on Python 2.7, you will want to read the following document at it details how to install MySQLdb1 on the various platforms:

https://github.com/farcepest/MySQLdb1

See the INSTALL file specifically.

Note that this is kind of a legacy module. If you want something that works in Python 3, you might want to check out moist.

There is also PyMySQL, which is compatible with both Python 2.6+ and 3.3+ and it can be installed with pip:

pip install PyMySQL


问:
Specflow/Selenium tests run simultaneously on same browser (and interfere)
I have some tests written in SpecFlow and Selenium. I'd like them to run sequentially for the time being. For some reason, they kick off at the same time on the same browser window and interfere with each other. I do want tests to re-use the browser window but I obviously don't want them running at the same time on the same window.

I have these classes set up for reusing the browser window:

```<code>public class SeleniumContext
{
    public ChromeDriver WebDriver { get; set; }
    public SeleniumContext()
    {
        ChromeOptions options = new ChromeOptions();
        options.SetLoggingPreference(LogType.Browser, LogLevel.All);
        options.AddArgument("no-sandbox");

        WebDriver = new ChromeDriver("./", options, TimeSpan.FromSeconds(240));
    }
}

[Binding]
public class BeforeAllTests
{
    private readonly IObjectContainer objectContainer;
    private static SeleniumContext seleniumContext;

    public BeforeAllTests(IObjectContainer container)
    {
        this.objectContainer = container;
    }

    [BeforeTestRun]
    public static void RunBeforeAllTests()
    {
        seleniumContext = new SeleniumContext();
    }

    [BeforeScenario]
    public void RunBeforeScenario()
    {
        objectContainer.RegisterInstanceAs<SeleniumContext>(seleniumContext);
    }

    [AfterTestRun]
    public static void afterRun()
    {
        seleniumContext.WebDriver.Quit();
    }
}
</code>```

An example Steps class:

```<code>[Binding]
public sealed class LogInSteps
{
    private ChromeDriver driver;

    public LogInSteps(SeleniumContext seleniumContext)
    {
        this.driver = seleniumContext.WebDriver;
    }

    //step definitions here

}
</code>```

When I click "Run All" they both fire up and run on the same window:

I do not want them to run at the same time on the same window. How can I get them to run sequentially? Using a test playlist is not an option. I'd settle as well for running on different windows but when they behave as they do the tests interfere with each other and cause them to fail. They do run successfully when run individually.

答:
The solution was to add the following to AssemblyInfo.cs:

```<code>[assembly: CollectionBehavior(DisableTestParallelization = true)]
</code>```

This tells xUnit not to run the tests in parallel.

Reference: https://xunit.github.io/docs/running-tests-in-parallel.html

Body:
I have some tests written in SpecFlow and Selenium. I'd like them to run sequentially for the time being. For some reason, they kick off at the same time on the same browser window and interfere with each other. I do want tests to re-use the browser window but I obviously don't want them running at the same time on the same window.

I have these classes set up for reusing the browser window:

public class SeleniumContext
{
    public ChromeDriver WebDriver { get; set; }
    public SeleniumContext()
    {
        ChromeOptions options = new ChromeOptions();
        options.SetLoggingPreference(LogType.Browser, LogLevel.All);
        options.AddArgument("no-sandbox");

        WebDriver = new ChromeDriver("./", options, TimeSpan.FromSeconds(240));
    }
}

[Binding]
public class BeforeAllTests
{
    private readonly IObjectContainer objectContainer;
    private static SeleniumContext seleniumContext;

    public BeforeAllTests(IObjectContainer container)
    {
        this.objectContainer = container;
    }

    [BeforeTestRun]
    public static void RunBeforeAllTests()
    {
        seleniumContext = new SeleniumContext();
    }

    [BeforeScenario]
    public void RunBeforeScenario()
    {
        objectContainer.RegisterInstanceAs<SeleniumContext>(seleniumContext);
    }

    [AfterTestRun]
    public static void afterRun()
    {
        seleniumContext.WebDriver.Quit();
    }
}

An example Steps class:

[Binding]
public sealed class LogInSteps
{
    private ChromeDriver driver;

    public LogInSteps(SeleniumContext seleniumContext)
    {
        this.driver = seleniumContext.WebDriver;
    }

    //step definitions here

}

When I click "Run All" they both fire up and run on the same window:

I do not want them to run at the same time on the same window. How can I get them to run sequentially? Using a test playlist is not an option. I'd settle as well for running on different windows but when they behave as they do the tests interfere with each other and cause them to fail. They do run successfully when run individually.

Body:
The solution was to add the following to AssemblyInfo.cs:

[assembly: CollectionBehavior(DisableTestParallelization = true)]

This tells xUnit not to run the tests in parallel.

Reference: https://xunit.github.io/docs/running-tests-in-parallel.html


问:
Using two WHERE conditions when extracting data from a Nested SELECT query
I am currently stuck with a relatively straight-forward SQL query.

Working_schedule table is

```<code>Work_ID   Work_grade   Work_shift       Work_Process    pay_grade
-----------------------------------------------------------------
1         senior       day              manual          1
2         mid          day              auto            5
3         mid          day              auto            2
4         junior       night            manual          1
</code>```

Query:

```<code>SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
  AND Work_grade = 'senior'
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')
</code>```

I have to count how many night workers, who are also seniors work companies of Spanish origin.

Currently I am able to filter for all night workers who are seniors, but I am unsure of how to check to see if they work for companies of Spanish origin.

I can also get filter for all companies of Spanish origin and (through a series of inner joins) find out the work_ids in the Working schedule table.

My question is how do I connect the two queries (or even can I)? If not, how should I resolve this problem? I have attempted this with INTERSECT, UNION and UNION ALL but nothing has worked.

The output anticipated is a number - number of work_shifts at night that are also work_grade senior.

答:
Try this:</p>

```<code>SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
AND Work_grade = 'senior'
AND Work_id in
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')
</code>```

Body:
I am currently stuck with a relatively straight-forward SQL query.

Working_schedule table is

Work_ID   Work_grade   Work_shift       Work_Process    pay_grade
-----------------------------------------------------------------
1         senior       day              manual          1
2         mid          day              auto            5
3         mid          day              auto            2
4         junior       night            manual          1

Query:

SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
  AND Work_grade = 'senior'
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')

I have to count how many night workers, who are also seniors work companies of Spanish origin.

Currently I am able to filter for all night workers who are seniors, but I am unsure of how to check to see if they work for companies of Spanish origin.

I can also get filter for all companies of Spanish origin and (through a series of inner joins) find out the work_ids in the Working schedule table.

My question is how do I connect the two queries (or even can I)? If not, how should I resolve this problem? I have attempted this with INTERSECT, UNION and UNION ALL but nothing has worked.

The output anticipated is a number - number of work_shifts at night that are also work_grade senior.

Body:
Try this:

SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
AND Work_grade = 'senior'
AND Work_id in
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')


问:
What is the significance of this entry in Annex E of the ES2015 spec?
Annex E of the ES2015 spec contains the following:

19.2.3.2: In ECMAScript 2015, the [[Prototype]] internal slot of a bound function is set to the [[GetPrototypeOf]] value of its target function. In the previous edition, [[Prototype]] was always set to %FunctionPrototype%.

What is the significance of this?

Source: http://www.ecma-international.org/ecma-262/6.0/#sec-additions-and-changes-that-introduce-incompatibilities-with-prior-editions

答:
Before ES2015 there was only a single type of function. ES2015 introduced introduced arrow functions, generator functions and methods. Generator functions and class methods do not (necessarily) have Function.prototype as their prototype. For example:

9.2.6 GeneratorFunctionCreate (kind, ParameterList, Body, Scope, Strict)

Let functionPrototype be the intrinsic object %Generator%.

Let F be FunctionAllocate(functionPrototype, Strict, "generator").

Return FunctionInitialize(F, kind, ParameterList, Body, Scope).

Bound versions of these functions should probably "preserve" the prototype of the original function.


问:
WPF DataGrid Need Vertical Scrollbar in Grid Row
My customer developing a property editor of sorts that contains multiple property sections that are presented as WPF Expanders with Datagrids contained within. We have everything laid out in a WPF Grid, currently with auto sized rows.

The problem we're trying to solve is proportional sizing of each property section when the screen height changes. When expanders are opened they should take up a proportional amount of space with vertical scrollbars kicking automatically when needed. When they are closed they should collapse and give the remaining space to the remaining sections.

In real life we have 4 expanders with content. The first one is a fixed height, the remaining three are Lists and DataGrids that need to size proportionally with the last one getting the largest portion of the remaining space. Keep in mind, users might resize the screen, or users might be running in different screen resolutions, so we need it to react accordingly.

We've tried messing with the DataGrid RowDefinition Height (fixed, proportional and auto) and MaxHeight, and also the MaxHeight of each datagrid, but I can't seem to find a combination that causes the whole area to be consumed when needed. We're researching a code based solution, but we're curious what others may suggest.

Here's a simple code sample that will give you the layout we're after. We just need it to work as described above.

Here's The Code (this would be a view model in real world)

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        datagrid1.DataContext = GetCustomerVM();
        datagrid2.DataContext = GetCustomerVM();
        datagrid3.DataContext = GetCustomerVM();
    }

    private List<Customer> GetCustomerVM()
    {
        var CustomerList = new List<Customer>();
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });

        return CustomerList;
    }
}

public class Customer
{
    public string FirstName { get; set; }
}
```

<p><strong>The XAML</strong></p>

<pre class="lang-xml prettyprint-override"><code><Window x:Class="StackOverflow_SidePanelGridScrolling.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StackOverflow_SidePanelGridScrolling"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="MainWindow" Height="500" Width="300">

    <Window.Resources>

        <DataTemplate x:Key="ExpanderHeaderTemplate">
            <DockPanel Height="30">
                <TextBlock Margin="4,0,0,0"
                               VerticalAlignment="Center"
                               DockPanel.Dock="Left"
                               FontSize="16"
                               Text="{Binding}" />

            </DockPanel>
        </DataTemplate>

        <Style TargetType="Expander">
            <Setter Property="HeaderTemplate"
                    Value="{StaticResource ExpanderHeaderTemplate}" />
        </Style>

    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Expander x:Name="expander1" Grid.Row="0" Header="Area 1">

            <DataGrid Name="datagrid1"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

        <Expander x:Name="expander2" Grid.Row="1" Header="Area 2">

            <DataGrid Name="datagrid2"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

        <Expander x:Name="expander3" Grid.Row="3" Header="Area 3">

            <DataGrid Name="datagrid2"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

    </Grid>
</Window>
</code>```

答:
As far as I'm able to understand your requirements, I think this does about what you want:

Every expander, when not expanded, takes up whatever minimal space it requires.

The top row, when expanded, is sized to its content.

Rows two, three, and four divide up the remainder of the space. When expanded, they stretch. Two gets one share of the available space, Three gets two shares, Four gets three shares. If Two and Three are open, Two gets one of four shares and Three gets the other three.

Those shares are handed out by the * Height values in the setters in the triggers. Here's the trigger for Row Four:

```<code><DataTrigger
    Binding="{Binding Children[3].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
    Value="True"
    >
    <Setter Property="Height" Value="3*" />
</DataTrigger>
</code>```

The nice thing about doing this in XAML is that it will never spring any ugly surprises on you.

So here's the XAML:

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition>
            <RowDefinition.Style>
                <Style TargetType="RowDefinition">
                    <Setter Property="Height" Value="Auto" />
                    <Style.Triggers>
                        <DataTrigger
                            Binding="{Binding Children[1].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
                            Value="True"
                            >
                            <Setter Property="Height" Value="1*" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </RowDefinition.Style>
        </RowDefinition>
        <RowDefinition>
            <RowDefinition.Style>
                <Style TargetType="RowDefinition">
                    <Setter Property="Height" Value="Auto" />
                    <Style.Triggers>
                        <DataTrigger
                            Binding="{Binding Children[2].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
                            Value="True"
                            >
                            <Setter Property="Height" Value="2*" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </RowDefinition.Style>
        </RowDefinition>
        <RowDefinition>
            <RowDefinition.Style>
                <Style TargetType="RowDefinition">
                    <Setter Property="Height" Value="Auto" />
                    <Style.Triggers>
                        <DataTrigger
                            Binding="{Binding Children[3].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
                            Value="True"
                            >
                            <Setter Property="Height" Value="3*" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </RowDefinition.Style>
        </RowDefinition>
    </Grid.RowDefinitions>
    <Expander
        Grid.Row="0"
        VerticalAlignment="Stretch"
        Header="One" Background="LightGreen">
        <StackPanel>
            <Label>Content One</Label>
            <Label>Content One</Label>
            <Label>Content One</Label>
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="1"
        VerticalAlignment="Stretch"
        Header="Two" Background="LightSkyBlue">
        <StackPanel>
            <Label>Content Two</Label>
            <Label>Content Two</Label>
            <Label>Content Two</Label>
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="2"
        VerticalAlignment="Stretch"
        Header="Three" Background="LightGoldenrodYellow">
        <StackPanel>
            <Label>Content Three</Label>
            <Label>Content Three</Label>
            <Label>Content Three</Label>
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="3"
        VerticalAlignment="Stretch"
        Header="Four" Background="Khaki">
        <StackPanel>
            <Label>Content Four</Label>
            <Label>Content Four</Label>
            <Label>Content Four</Label>
        </StackPanel>
    </Expander>
</Grid>
</code>```

These don't show scrollbars because I didn't take the time to create content that will scroll.

Body:
My customer developing a property editor of sorts that contains multiple property sections that are presented as WPF Expanders with Datagrids contained within. We have everything laid out in a WPF Grid, currently with auto sized rows.

The problem we're trying to solve is proportional sizing of each property section when the screen height changes. When expanders are opened they should take up a proportional amount of space with vertical scrollbars kicking automatically when needed. When they are closed they should collapse and give the remaining space to the remaining sections.

In real life we have 4 expanders with content. The first one is a fixed height, the remaining three are Lists and DataGrids that need to size proportionally with the last one getting the largest portion of the remaining space. Keep in mind, users might resize the screen, or users might be running in different screen resolutions, so we need it to react accordingly.

We've tried messing with the DataGrid RowDefinition Height (fixed, proportional and auto) and MaxHeight, and also the MaxHeight of each datagrid, but I can't seem to find a combination that causes the whole area to be consumed when needed. We're researching a code based solution, but we're curious what others may suggest.

Here's a simple code sample that will give you the layout we're after. We just need it to work as described above.

Here's The Code (this would be a view model in real world)

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        datagrid1.DataContext = GetCustomerVM();
        datagrid2.DataContext = GetCustomerVM();
        datagrid3.DataContext = GetCustomerVM();
    }

    private List<Customer> GetCustomerVM()
    {
        var CustomerList = new List<Customer>();
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });

        return CustomerList;
    }
}

public class Customer
{
    public string FirstName { get; set; }
}

The XAML

<Window x:Class="StackOverflow_SidePanelGridScrolling.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StackOverflow_SidePanelGridScrolling"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="MainWindow" Height="500" Width="300">

    <Window.Resources>

        <DataTemplate x:Key="ExpanderHeaderTemplate">
            <DockPanel Height="30">
                <TextBlock Margin="4,0,0,0"
                               VerticalAlignment="Center"
                               DockPanel.Dock="Left"
                               FontSize="16"
                               Text="{Binding}" />

            </DockPanel>
        </DataTemplate>

    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Expander x:Name="expander1" Grid.Row="0" Header="Area 1">

            <DataGrid Name="datagrid1"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

        <Expander x:Name="expander2" Grid.Row="1" Header="Area 2">

            <DataGrid Name="datagrid2"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

        <Expander x:Name="expander3" Grid.Row="3" Header="Area 3">

            <DataGrid Name="datagrid2"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

    </Grid>
</Window>

Body:
As far as I'm able to understand your requirements, I think this does about what you want:

Every expander, when not expanded, takes up whatever minimal space it requires.

The top row, when expanded, is sized to its content.

Rows two, three, and four divide up the remainder of the space. When expanded, they stretch. Two gets one share of the available space, Three gets two shares, Four gets three shares. If Two and Three are open, Two gets one of four shares and Three gets the other three.

Those shares are handed out by the * Height values in the setters in the triggers. Here's the trigger for Row Four:

<DataTrigger
    Binding="{Binding Children[3].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
    Value="True"
    >
    <Setter Property="Height" Value="3*" />
</DataTrigger>

The nice thing about doing this in XAML is that it will never spring any ugly surprises on you.

So here's the XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition>
            <RowDefinition.Style>
                <Style TargetType="RowDefinition">
                    <Setter Property="Height" Value="Auto" />
                    <Style.Triggers>
                        <DataTrigger
                            Binding="{Binding Children[1].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
                            Value="True"
                            >
                            <Setter Property="Height" Value="1*" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </RowDefinition.Style>
        </RowDefinition>
        <RowDefinition>
            <RowDefinition.Style>
                <Style TargetType="RowDefinition">
                    <Setter Property="Height" Value="Auto" />
                    <Style.Triggers>
                        <DataTrigger
                            Binding="{Binding Children[2].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
                            Value="True"
                            >
                            <Setter Property="Height" Value="2*" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </RowDefinition.Style>
        </RowDefinition>
        <RowDefinition>
            <RowDefinition.Style>
                <Style TargetType="RowDefinition">
                    <Setter Property="Height" Value="Auto" />
                    <Style.Triggers>
                        <DataTrigger
                            Binding="{Binding Children[3].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
                            Value="True"
                            >
                            <Setter Property="Height" Value="3*" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </RowDefinition.Style>
        </RowDefinition>
    </Grid.RowDefinitions>
    <Expander
        Grid.Row="0"
        VerticalAlignment="Stretch"
        Header="One" Background="LightGreen">
        <StackPanel>
            <Label>Content One</Label>
            <Label>Content One</Label>
            <Label>Content One</Label>
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="1"
        VerticalAlignment="Stretch"
        Header="Two" Background="LightSkyBlue">
        <StackPanel>
            <Label>Content Two</Label>
            <Label>Content Two</Label>
            <Label>Content Two</Label>
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="2"
        VerticalAlignment="Stretch"
        Header="Three" Background="LightGoldenrodYellow">
        <StackPanel>
            <Label>Content Three</Label>
            <Label>Content Three</Label>
            <Label>Content Three</Label>
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="3"
        VerticalAlignment="Stretch"
        Header="Four" Background="Khaki">
        <StackPanel>
            <Label>Content Four</Label>
            <Label>Content Four</Label>
            <Label>Content Four</Label>
        </StackPanel>
    </Expander>
</Grid>

These don't show scrollbars because I didn't take the time to create content that will scroll.


问:
Why do these two items have the same barcode?
I am trying to build an iOS app that involves scanning barcodes and I came across this weird scenario where this api and this api gave me different items for the same UPC-A barcodes.

Is it possible for two item issued in the same country to have the same UPC-A barcode or is this the APIs fault?

Here's the barcode image? It'll be great if someone can give me some general barcode guidelines. It's my first time dealing with barcodes.

答:
I don't know anything about API's, but I was a 3rd party seller on Amazon, and it looks like that shower gel was sold on Amazon, and the website http://www.upcitemdb.com that was used to pull those results pulls data from Amazon, somehow. When you enter an item for sale on Amazon, some catergories require you to use a barcode in order to place an item for sale on Amazon. If an item does not have a barcode it is conceivable that the seller invented one simply to get their listing on Amazon. In this case, it looks like they entered the same barcode that RedBull has registered to them.

I also find it fishy that the website http://www.upcitemdb.com not only pulls data from Amazon, but uses Amazon ads, and is likely owned by an Amazon affiliate who has a vested interest in directing traffic to Amazon, not in displaying correct barcode information.


问:
How to input an arbitrary number of text files in C++?
so I'm working on a coding project for a class, and I understand the basic things I want to accomplish, but one thing that nobody seems to be able to help me with is inputting an unspecified number of text files. The user is prompted to enter the text files they want to compare (overall purpose of my code), separated by spaces, thus allowing them to compare an arbitrary amount of text files (eg. 2, 3, 8, 16, etc). I know that the getline function is helpful here, as well as searching for the number of "." because files can only contain one ".", all within a for loop. After that logic I am utterly lost. Eventually, I'm going to have to open the text files and put them in sets to compare them against every other file once, and output their similarities and differences into yet another text file. Any ideas?</p>

答:
Here is the general process I would try to follow (if I interpreted the prompt correctly)

Get the line of text files using getline

Put that into a stringstream

Open the next file in the stream while there is still information in the stringstream (not at eof)

Store all of that information in a Vector of strings, each new file just appended on after it is read

compare strings in the vector