问:
Empty string is returned when using parse_str()
This is my string that I need to work with parse_str:

```<code>type%3Dbasic%26WhatPropType%3DSingle%2BFamily%2BResidential%26WhatDistrict%255B0%255D%3DHaiku%26WhatStartPrice%3D90000%26WhatEndPrice%3D30000000%26WhatStartBed%3D%26WhatStartBath%3D0%26DaysAgo%3D%26WhatStartIntArea%3D%26WhatSortDirection1%3DDESC%26start%3D0%26WhatNumber%3D10
</code>```

How can i get this to work?

答:
as the same as our friends say decode the string

```<code>parse_str(urldecode('type%3Dbasic%26WhatPropType%3DSingle%2BFamily%2BResidential%26WhatDistrict%255B0%255D%3DHaiku%26WhatStartPrice%3D90000%26WhatEndPrice%3D30000000%26WhatStartBed%3D%26WhatStartBath%3D0%26DaysAgo%3D%26WhatStartIntArea%3D%26WhatSortDirection1%3DDESC%26start%3D0%26WhatNumber%3D10'), $array);
</code>```

and get value like this

```<code>$array['type']  //out put "basic"
</code>```

Body:
This is my string that I need to work with parse_str:

type%3Dbasic%26WhatPropType%3DSingle%2BFamily%2BResidential%26WhatDistrict%255B0%255D%3DHaiku%26WhatStartPrice%3D90000%26WhatEndPrice%3D30000000%26WhatStartBed%3D%26WhatStartBath%3D0%26DaysAgo%3D%26WhatStartIntArea%3D%26WhatSortDirection1%3DDESC%26start%3D0%26WhatNumber%3D10

How can i get this to work?

Body:
as the same as our friends say decode the string

parse_str(urldecode('type%3Dbasic%26WhatPropType%3DSingle%2BFamily%2BResidential%26WhatDistrict%255B0%255D%3DHaiku%26WhatStartPrice%3D90000%26WhatEndPrice%3D30000000%26WhatStartBed%3D%26WhatStartBath%3D0%26DaysAgo%3D%26WhatStartIntArea%3D%26WhatSortDirection1%3DDESC%26start%3D0%26WhatNumber%3D10'), $array);

and get value like this

$array['type']  //out put "basic"


来源: stackexchange

问:
Please let me know why I can not install RedMine connector
If you install from Eclipse, it will continue to fail.
I am using jdk1.8.0 and Eclipse Neon.3.
Please let me know why I can not install RedMine connector

Cannot complete the install because one or more required items could not be found.
  Software being installed: Mylyn Connector: Redmine 0.4.0.201602071631 (net.sf.redmine_mylyn.feature.feature.group 0.4.0.201602071631)
  Missing requirement: Mylyn Connector: Redmine 0.4.0.201602071631 (net.sf.redmine_mylyn.feature.feature.group 0.4.0.201602071631) requires 'org.eclipse.equinox.log 1.2.0' but it could not be found
```

答:
I solved this problem.
The solution to this problem is
Kepler in org.eclipse.equinox.log bundle was uninstalled error.

```<code>To fix this, go to Help> install software> add>
Update url: http://download.eclipse.org/eclipse/updates/4.3 >
Equinox Target Components - Equinox Target Components
</code>```

I hope it helps someone else.

ContentLicense: CC BY-SA 3.0

Body:
I solved this problem.
The solution to this problem is
Kepler in org.eclipse.equinox.log bundle was uninstalled error.

To fix this, go to Help> install software> add>
Update url: http://download.eclipse.org/eclipse/updates/4.3 >
Equinox Target Components - Equinox Target Components

I hope it helps someone else.


问:
scipy.optimize.minimize with powell method violating maximum function evaluation
I am optimizing a function using scipy.optimize.minimize with Powell algorithm. There is an option called maxfev to set maximum function evaluations. However it doesn't seem to work always. Algorithm crosses the function evaluation limit. The code is as follows:

```<code>def func_eval(x):
    import math as math
    funcval=0
    dimension=len(x)
    tmp=0
    tmp2=0
    for i in range(dimension):
        tmp +=x[i]

    for i in range(dimension):
        tmp2=(tmp-x[i])*x[i]
        funcval += dimension*(math.pow(x[i],2)+0.4*tmp2)

    return funcval

from scipy.optimize import minimize
x=[-11.04021,-92.72567,28.60728,68.65449,66.41443,-25.59824,73.97660,-69.85293,1.10955,17.56914]
res=minimize(func_eval,x,method='Powell',options={'maxfev':220})
print(res.fun)
print(res.nfev)
</code>```

The output of second option i.e. number of func evaluations is 298 instead of 220. What is possibly going wrong with my code, or is it some issue with algorithm itself ?

答:
The function needs to be evaluated multiple times per iteration; once for each dimension. For some reason (I guess performance or other implementation detail) the evaluation count is only checked once per iteration. That is why the maximum can be exceeded.

How much the evaluation count overshoots the maximum depends on the dimensionality of x, perhaps also on the function and the data.

Body:
I am optimizing a function using scipy.optimize.minimize with Powell algorithm. There is an option called maxfev to set maximum function evaluations. However it doesn't seem to work always. Algorithm crosses the function evaluation limit. The code is as follows:

def func_eval(x):
    import math as math
    funcval=0
    dimension=len(x)
    tmp=0
    tmp2=0
    for i in range(dimension):
        tmp +=x[i]

    for i in range(dimension):
        tmp2=(tmp-x[i])*x[i]
        funcval += dimension*(math.pow(x[i],2)+0.4*tmp2)

    return funcval

from scipy.optimize import minimize
x=[-11.04021,-92.72567,28.60728,68.65449,66.41443,-25.59824,73.97660,-69.85293,1.10955,17.56914]
res=minimize(func_eval,x,method='Powell',options={'maxfev':220})
print(res.fun)
print(res.nfev)

The output of second option i.e. number of func evaluations is 298 instead of 220. What is possibly going wrong with my code, or is it some issue with algorithm itself ?

ContentLicense: CC BY-SA 4.0


问:
Access apps with AppleScript
Is there anyway to programmatically get a list of iOS apps from iTunes?

AppleScript does not seem able to do this.

The only way I can think of is looking in the 'iTunes Media/Mobile Applications' folder. But this way a lose all metadata.

Any suggestions to get list of iOS apps including the metadata?

Thanks

答:
I now actually went with the solution to scan the 'Mobile Applications' folder.

In order to get the metadata I had to do the following:

the *.ipa are simply archives

unzip/extract the 'iTunesMetadata.plist' inside

parse the plist

voila you got all metadata

This whole process is actually pretty straightforward in python as your already have both zipfile and plistlib.

One thing to lookout for though is that plistlib in python can not handle the new binary plist files. So you first have to convert them to their corresponding xml format. (only some *.ipa seem to be in binary form).

This can be done quite easily with the following line of code:

```<code>os.system("/usr/bin/plutil -convert xml1 %s" % file_name )
</code>```

Now the only thing I still have to figure out is how to get the currently installed apps on the device...

ContentLicense: CC BY-SA 2.5

Title: Access apps with AppleScript

Body:
I now actually went with the solution to scan the 'Mobile Applications' folder.

In order to get the metadata I had to do the following:

the *.ipa are simply archives

unzip/extract the 'iTunesMetadata.plist' inside

parse the plist

voila you got all metadata

This whole process is actually pretty straightforward in python as your already have both zipfile and plistlib.

One thing to lookout for though is that plistlib in python can not handle the new binary plist files. So you first have to convert them to their corresponding xml format. (only some *.ipa seem to be in binary form).

This can be done quite easily with the following line of code:

os.system("/usr/bin/plutil -convert xml1 %s" % file_name )

Now the only thing I still have to figure out is how to get the currently installed apps on the device...


问:
How can I initialize an array's argument to its default value?
Here is my code:

```<code>function myfunc( $arg1, $arg2 = 'sth', $arg3 = 'sth else' ){
    // do stuff
}
</code>```

Now I want to set a new value for arg3 and keep the default defined value for arg2. How can I do that?

Something like this:

```<code>myfunc( true, <keep everything defined as default>, $arg3 = 'new value' );
</code>```

The expected result is sth in this fiddle.

答:
A possible alternative would not have your function take 3 parameters, but only one, an array:

```<code>function my_function(array $value = array()) {
    // if set, use $value['key1']
    // if set, use $value['key2']
    // ...
}
</code>```

And call that function like this:

```<code>my_function(array(
    'key1' => 'google',
    'key2' => 'yahoo'
));
</code>```

This would allow you to:

accept any number of parameters

all of which could be optional

Hope it will helpful.

Body:
Here is my code:

function myfunc( $arg1, $arg2 = 'sth', $arg3 = 'sth else' ){
    // do stuff
}

Now I want to set a new value for arg3 and keep the default defined value for arg2. How can I do that?

Something like this:

myfunc( true, <keep everything defined as default>, $arg3 = 'new value' );

The expected result is sth in this fiddle.

Body:
A possible alternative would not have your function take 3 parameters, but only one, an array:

function my_function(array $value = array()) {
    // if set, use $value['key1']
    // if set, use $value['key2']
    // ...
}

And call that function like this:

my_function(array(
    'key1' => 'google',
    'key2' => 'yahoo'
));

This would allow you to:

accept any number of parameters

all of which could be optional

Hope it will helpful.


问:
jQuery serializeArray using $(this)
I'm using jQuery's serializeArray to serialize form data, in two different ways.

The "Save All Rooms" button serializes all the form data (this is working fine), and the "Check Availability" button serializes data only from the specific form the button is click for (this isn't working).

Can anyone advise where I'm going wrong? Any help much appreciated!

JSFiddle: https://jsfiddle.net/kuohhm2q/

"Check Availability" function which isn't working:

```<code>// Serialize Individual Form Data
el.find(".check_availability" ).click(function() {

   var formData = JSON.stringify( $(this).parent('div :input').serializeArray() );
   alert(formData);

});
</code>```

答:
I changed

```<code> JSON.stringify( $(this).parent('div :input').serializeArray() );
</code>```

to this

```<code>JSON.stringify($(this).parent('div').find("input, select").serializeArray() );
</code>```

Here is the updated fiddle

Title: jQuery serializeArray using $(this)

Body:
I'm using jQuery's serializeArray to serialize form data, in two different ways.

The "Save All Rooms" button serializes all the form data (this is working fine), and the "Check Availability" button serializes data only from the specific form the button is click for (this isn't working).

Can anyone advise where I'm going wrong? Any help much appreciated!

JSFiddle: https://jsfiddle.net/kuohhm2q/

"Check Availability" function which isn't working:

// Serialize Individual Form Data
el.find(".check_availability" ).click(function() {

   var formData = JSON.stringify( $(this).parent('div :input').serializeArray() );
   alert(formData);

});

Body:
I changed

 JSON.stringify( $(this).parent('div :input').serializeArray() );

to this

JSON.stringify($(this).parent('div').find("input, select").serializeArray() );

Here is the updated fiddle


问:
Tensorflow Object Detection API, tutorial with differing results
I followed the steps suggested into installation section, and I executed the suggested example. The surprise was the different values obtained If we compare the solution showed into the presentation page. I would like to explore if this behavior is correct or is an error of my implementation.

I'm using tensorflow 1.2.1
I followed these instructions, and I tested the installation using the suggested tests:

I'm using MacOs SO, and I using these lib version into my environment: pillow 4.2.0, protobuf 3.3.0, matplotlib 2.0.2, lxml 3.8.0.

This is the result after the execution:
result 1

result 2

But this result is quite different that the examples showed into the presentation, the accuracy is different:

答:
I think you are using ssd_mobilenet_v1_coco_11_06_2017 model for testing the results. Try using other models:

```<code>MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'

MODEL_NAME = 'ssd_inception_v2_coco_11_06_2017'

MODEL_NAME = 'rfcn_resnet101_coco_11_06_2017'

MODEL_NAME = 'faster_rcnn_resnet101_coco_11_06_2017'

MODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017'
</code>```

faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017 will give you the same result as shown in tutorial.

Body:
I think you are using ssd_mobilenet_v1_coco_11_06_2017 model for testing the results. Try using other models:

MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'

MODEL_NAME = 'ssd_inception_v2_coco_11_06_2017'

MODEL_NAME = 'rfcn_resnet101_coco_11_06_2017'

MODEL_NAME = 'faster_rcnn_resnet101_coco_11_06_2017'

MODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017'

faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017 will give you the same result as shown in tutorial.


问:
Spring Boot: Prevent decoding for @RequestParam
I have a Spring-Boot (1.5.3) application running on a Tomcat 8.5.
Within it, i have a RestController with a single parameter.

This parameter is decoded automatically - which is fine for all other controllers within my application, but for this one, i need the raw request data, since they will be used within another request. Please note that i wold like to only disable the auto-decoding for this Controller/request and keep the normal behaviour everywhere else.

```<code>@RestController
@RequestMapping("/rest/test")
public class TestController {

  @RequestMapping("/test")
  public ResponseEntity<String> test(@RequestParam final String test){
    return ResponseEntity.ok("Requested: " + test);
  }
}
</code>```

Now, if i send access it with

```<code>curl localhost/rest/test/test?test=%C3%B6%20%C3%A4
</code>```

I receive the output:

```<code>Requested: ö ä
</code>```

I would like to have

```<code>Requested: %C3%B6%20%C3%A4
</code>```

Any Ideas?

答:
I ended up ensuring, that the received data was did not contain invalid characters.</p>

```<code>private static final String VALID_URL_CHARACTER_PATTERN = "^[A-Za-z0-9-._~:/?#\\[\\]@!$&'()*+,;=`.]+$";

private static final String ensureEncoding(final Object obj) {
    if (obj == null) {
        return null;
    }
    String val = obj.toString();
    if (!val.matches(VALID_URL_CHARACTER_PATTERN)) {
        try {
            val = URLEncoder.encode(val, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("Unexpected encoding Problem on value: " + val, e);

        }
    }
    return val;
}
</code>```

Body:
I have a Spring-Boot (1.5.3) application running on a Tomcat 8.5.
Within it, i have a RestController with a single parameter.

This parameter is decoded automatically - which is fine for all other controllers within my application, but for this one, i need the raw request data, since they will be used within another request. Please note that i wold like to only disable the auto-decoding for this Controller/request and keep the normal behaviour everywhere else.

@RestController
@RequestMapping("/rest/test")
public class TestController {

  @RequestMapping("/test")
  public ResponseEntity<String> test(@RequestParam final String test){
    return ResponseEntity.ok("Requested: " + test);
  }
}

Now, if i send access it with

curl localhost/rest/test/test?test=%C3%B6%20%C3%A4

I receive the output:

Requested: ö ä

I would like to have

Requested: %C3%B6%20%C3%A4

Any Ideas?

Body:
I ended up ensuring, that the received data was did not contain invalid characters.

private static final String VALID_URL_CHARACTER_PATTERN = "^[A-Za-z0-9-._~:/?#\\[\\]@!$&'()*+,;=`.]+$";

private static final String ensureEncoding(final Object obj) {
    if (obj == null) {
        return null;
    }
    String val = obj.toString();
    if (!val.matches(VALID_URL_CHARACTER_PATTERN)) {
        try {
            val = URLEncoder.encode(val, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("Unexpected encoding Problem on value: " + val, e);

        }
    }
    return val;
}


问:
Inserting addresses into sets, the size of the sets is smaller than expected
I am getting a size of 1. Shouldn't it be 4? I am inserting the addresses of integers into the sets.</p>

```<code>void func(set<int*>& s1, set<int*>& s2, int a)
{
    s1.insert(&a);
    s2.insert(&a);
}

int main()
{
    set<int*> s1, s2;

    int a = 1, b = 2, c = 3, d = 4;
    func(s1, s2, a);
    func(s1, s2, b);
    func(s1, s2, c);
    func(s1, s2, d);

    cout<<"  s1.size = "<<s1.size()<<"  s2.size = "<<s2.size()<<endl;
}
</code>```

答:
&a inside func is the address of the local parameter a, not the address of the original variable (a, b, c or d), which:

Can take various kind of values between different calls of func;

Becomes an invalid pointer once you reach the end of the scope in which a is declared (the end of func here).

In your case, since you do nothing but calling func 4 times in a row, the address of this parameter happens to not change, which is why you get a size of 1 (you insert the same pointer 4 times).

This behavior is implementation defined (thanks @Rakete1111) since sets will need to compare invalid pointers.

Accessing the pointed element through s1 or s2 (e.g. **s1.begin()) is undefined behavior though.

Body:
I am getting a size of 1. Shouldn't it be 4? I am inserting the addresses of integers into the sets.

void func(set<int*>& s1, set<int*>& s2, int a)
{
    s1.insert(&a);
    s2.insert(&a);
}

int main()
{
    set<int*> s1, s2;

    int a = 1, b = 2, c = 3, d = 4;
    func(s1, s2, a);
    func(s1, s2, b);
    func(s1, s2, c);
    func(s1, s2, d);

    cout<<"  s1.size = "<<s1.size()<<"  s2.size = "<<s2.size()<<endl;
}


问:
How can I define the parameters of a query using string values?
The query below should have only returned the numbers 0 through 8. However, the result are 0 thru 87. and 88 thru 99 are not shown. The next numbers shown are 100 thru 799. 800 thru 999 are not shown. So I see a pattern here, and it is that if the first number is within the range specified it is returned.

```<code> public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory >= "+zero+" AND inventory <= "+user);
    return mDb.rawQuery(query, null);
</code>```

How can I keep the expected results withing the query parameters?

Thanks for all your efforts.

EDIT

For anyone that are looking for an answer as I was. Here is the final working statement.
Thanks to @FAT I was able to learn more about the sql query process from the links that where provided. Googling is an art it seems. I changed my code to meet my needs as follows.

```<code> public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory != '' AND (cast(inventory as real)) >= " + zero + " AND (cast(inventory as real)) <= " + user);
    return mDb.rawQuery(query, null);
}
</code>```

The "cast" was the key to getting the string to be used to compare the two numbers. I also learned that you can exclude all null items. By adding "!= '', only the items that had an entry where returned in accordance with the statement. This even works for decimal numbers such as 5.5 or .5 etc.

答:
You can't compare String value using >= or <=. Try using int value instead of string. For this case your column inventory should be int type.

Try this:

```<code>public Cursor getList(int user) {
    int zero = 0;
    String query = ("SELECT * FROM flavors WHERE inventory >= " + zero + " AND inventory <= " + user);
    return mDb.rawQuery(query, null);
}
</code>```

Body:
The query below should have only returned the numbers 0 through 8. However, the result are 0 thru 87. and 88 thru 99 are not shown. The next numbers shown are 100 thru 799. 800 thru 999 are not shown. So I see a pattern here, and it is that if the first number is within the range specified it is returned.

 public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory >= "+zero+" AND inventory <= "+user);
    return mDb.rawQuery(query, null);

How can I keep the expected results withing the query parameters?

Thanks for all your efforts.

EDIT

For anyone that are looking for an answer as I was. Here is the final working statement.
Thanks to @FAT I was able to learn more about the sql query process from the links that where provided. Googling is an art it seems. I changed my code to meet my needs as follows.

 public Cursor getList(String user) {
    String zero = "0";
    String query = ("SELECT * FROM flavors WHERE inventory != '' AND (cast(inventory as real)) >= " + zero + " AND (cast(inventory as real)) <= " + user);
    return mDb.rawQuery(query, null);
}

The "cast" was the key to getting the string to be used to compare the two numbers. I also learned that you can exclude all null items. By adding "!= '', only the items that had an entry where returned in accordance with the statement. This even works for decimal numbers such as 5.5 or .5 etc.

Body:
You can't compare String value using >= or <=. Try using int value instead of string. For this case your column inventory should be int type.

Try this:

public Cursor getList(int user) {
    int zero = 0;
    String query = ("SELECT * FROM flavors WHERE inventory >= " + zero + " AND inventory <= " + user);
    return mDb.rawQuery(query, null);
}


问:
Xcode 8 Table View Cells to Different Views
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

```<code>import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}
</code>```

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!

答:
Just now i done demo project with your requirements its working perfectly.

Step1: Prepare your story board as shown in below image.

step2: Give storyboard identifiers as dogID,catID,birdID,fishID to the respective viewController as shown in below image.

step3: Declare an array with the above identifiers just below your arched array.

```<code>var storyboardIds = ["dogID","catID","birdID","fishID"]
</code>```

step4: Modify your didSelectRowAt method as shown in below code snippet.

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row

    if let vc = storyboard?.instantiateViewController(withIdentifier: storyboardIds[myIndex]) {

        self.navigationController?.pushViewController(vc, animated: true)
    }
}
</code>```

Body:
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!

Body:
Just now i done demo project with your requirements its working perfectly.

Step1: Prepare your story board as shown in below image.

step2: Give storyboard identifiers as dogID,catID,birdID,fishID to the respective viewController as shown in below image.

step3: Declare an array with the above identifiers just below your arched array.

var storyboardIds = ["dogID","catID","birdID","fishID"]

step4: Modify your didSelectRowAt method as shown in below code snippet.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row

    if let vc = storyboard?.instantiateViewController(withIdentifier: storyboardIds[myIndex]) {

        self.navigationController?.pushViewController(vc, animated: true)
    }
}


问:
AESON: Parse dynamic structure
I have a JSON structure like this

```<code>{
  "tag1": 1,
  "tag2": 7,
  ...
}
</code>```

And I have a type like this

```<code>data TagResult { name :: String, numberOfDevicesTagged :: Int } deriving (Show, Eq)
newtype TagResultList = TagResultList { tags :: [TagResult] }
</code>```

The tag names are of course fully dynamic and I don't know them at compile time.
I'd like to create an instance FromJSON to parse the JSON data but I just cannot make it compile.

How can I define parseJSON to make this happen?

答:
You can use the fact that Object is an HasMap and extract the key at runtime. You can then write the FromJSON instance as follows - </p>

```<code>{-# LANGUAGE OverloadedStrings #-}
module Main where

import Data.Aeson
import qualified Data.Text as T
import qualified Data.HashMap.Lazy as HashMap

data TagResult = TagResult { name :: String
                           , numberOfDevicesTagged :: Int
                           } deriving (Show, Eq)

newtype TagResultList = TagResultList { tags :: [TagResult] } deriving Show

instance ToJSON TagResult where

  toJSON (TagResult tag ntag) =
    object [ T.pack tag .= ntag ]

instance ToJSON TagResultList where

  toJSON (TagResultList tags) =
    object [ "tagresults" .= toJSON tags ]

instance FromJSON TagResult where

  parseJSON (Object v) =
    let (k, _) = head (HashMap.toList v)
    in TagResult (T.unpack k) <$> v .: k

  parseJSON _ = fail "Invalid JSON type"

instance FromJSON TagResultList where

  parseJSON (Object v) =
    TagResultList <$> v .: "tagresults"

main :: IO ()
main = do

  let tag1 = TagResult "tag1" 1
      tag2 = TagResult "tag2" 7
      taglist = TagResultList [tag1, tag2]

  let encoded = encode taglist
      decoded = decode encoded :: Maybe TagResultList

  print decoded
</code>```

<p>The above program should print the tag result list. </p>

```<code>Just (TagResultList {tags = [TagResult {name = "tag1", numberOfDevicesTagged = 1},TagResult {name = "tag2", numberOfDevicesTagged = 7}]})
</code>```

Title: AESON: Parse dynamic structure

Body:
I have a JSON structure like this

{
  "tag1": 1,
  "tag2": 7,
  ...
}

And I have a type like this

data TagResult { name :: String, numberOfDevicesTagged :: Int } deriving (Show, Eq)
newtype TagResultList = TagResultList { tags :: [TagResult] }

The tag names are of course fully dynamic and I don't know them at compile time.
I'd like to create an instance FromJSON to parse the JSON data but I just cannot make it compile.

How can I define parseJSON to make this happen?

Body:
You can use the fact that Object is an HasMap and extract the key at runtime. You can then write the FromJSON instance as follows -

{-# LANGUAGE OverloadedStrings #-}
module Main where

import Data.Aeson
import qualified Data.Text as T
import qualified Data.HashMap.Lazy as HashMap

data TagResult = TagResult { name :: String
                           , numberOfDevicesTagged :: Int
                           } deriving (Show, Eq)

newtype TagResultList = TagResultList { tags :: [TagResult] } deriving Show

instance ToJSON TagResult where

  toJSON (TagResult tag ntag) =
    object [ T.pack tag .= ntag ]

instance ToJSON TagResultList where

  toJSON (TagResultList tags) =
    object [ "tagresults" .= toJSON tags ]

instance FromJSON TagResult where

  parseJSON (Object v) =
    let (k, _) = head (HashMap.toList v)
    in TagResult (T.unpack k) <$> v .: k

  parseJSON _ = fail "Invalid JSON type"

instance FromJSON TagResultList where

  parseJSON (Object v) =
    TagResultList <$> v .: "tagresults"

main :: IO ()
main = do

  let tag1 = TagResult "tag1" 1
      tag2 = TagResult "tag2" 7
      taglist = TagResultList [tag1, tag2]

  let encoded = encode taglist
      decoded = decode encoded :: Maybe TagResultList

  print decoded

The above program should print the tag result list.

Just (TagResultList {tags = [TagResult {name = "tag1", numberOfDevicesTagged = 1},TagResult {name = "tag2", numberOfDevicesTagged = 7}]})


问:
Change Package directory in Julia
I want to change the Package directory in Julia. The default is

```<code>"~/.julia/v0.4"
</code>```

I want to move it to /opt/julia/v0.4/. Ideally I want to move the packages that are already installed in ~/.julia/v0.4 to the new location. But if that is not possible I can reinstall them.

What do I have to do?

答:
Julia only way:

```<code>julia> ENV["JULIA_PKGDIR"] = "E:\\Julia-0.6.0\\portable"
"E:\\Julia-0.6.0\\portable"

julia> ENV["JULIA_PKGDIR"]
"E:\\Julia-0.6.0\\portable"

julia> Pkg.init()
INFO: Initializing package repository E:\Julia-0.6.0\portable\v0.6
INFO: Cloning METADATA from https://github.com/JuliaLang/METADATA.jl
</code>```

However, the cache dir is still pointing to the old folder, so I checked why that is and figured it out:

```<code>julia> Base.LOAD_CACHE_PATH
1-element Array{String,1}:
 "C:\\Users\\kung\\.julia\\lib\\v0.6"

julia> Pkg.__init__()
2-element Array{String,1}:
 "E:\\Julia-0.6.0\\portable\\lib\\v0.6"
 "C:\\Users\\kung\\.julia\\lib\\v0.6"

julia> pop!(Base.LOAD_CACHE_PATH)
"C:\\Users\\kung\\.julia\\lib\\v0.6"

julia> Base.LOAD_CACHE_PATH
1-element Array{String,1}:
 "E:\\Julia-0.6.0\\portable\\lib\\v0.6"
</code>```

As simple function:

```<code>function set_julia_dir(dir::String)
    ENV["JULIA_PKGDIR"] = dir
    Pkg.init()
    Pkg.__init__()
    pop!(Base.LOAD_CACHE_PATH)
end

set_julia_dir("E:\\Julia-0.6.0\\portable")
</code>```

Title: Change Package directory in Julia

Body:
I want to change the Package directory in Julia. The default is

"~/.julia/v0.4"

I want to move it to /opt/julia/v0.4/. Ideally I want to move the packages that are already installed in ~/.julia/v0.4 to the new location. But if that is not possible I can reinstall them.

What do I have to do?

Body:
Julia only way:

julia> ENV["JULIA_PKGDIR"] = "E:\\Julia-0.6.0\\portable"
"E:\\Julia-0.6.0\\portable"

julia> ENV["JULIA_PKGDIR"]
"E:\\Julia-0.6.0\\portable"

julia> Pkg.init()
INFO: Initializing package repository E:\Julia-0.6.0\portable\v0.6
INFO: Cloning METADATA from https://github.com/JuliaLang/METADATA.jl

However, the cache dir is still pointing to the old folder, so I checked why that is and figured it out:

julia> Base.LOAD_CACHE_PATH
1-element Array{String,1}:
 "C:\\Users\\kung\\.julia\\lib\\v0.6"

julia> Pkg.__init__()
2-element Array{String,1}:
 "E:\\Julia-0.6.0\\portable\\lib\\v0.6"
 "C:\\Users\\kung\\.julia\\lib\\v0.6"

julia> pop!(Base.LOAD_CACHE_PATH)
"C:\\Users\\kung\\.julia\\lib\\v0.6"

julia> Base.LOAD_CACHE_PATH
1-element Array{String,1}:
 "E:\\Julia-0.6.0\\portable\\lib\\v0.6"

As simple function:

function set_julia_dir(dir::String)
    ENV["JULIA_PKGDIR"] = dir
    Pkg.init()
    Pkg.__init__()
    pop!(Base.LOAD_CACHE_PATH)
end

set_julia_dir("E:\\Julia-0.6.0\\portable")


问:
Is there any plugin to replace the Gendarme rules plugin
Hi all am trying to upgrade sonarqube from 4.5.6 to 5.6.6

Current plugins:

Sonarqube v4.5.6

sonar C# plugin v2.1

sonar C# stylecop plugin  v2.1

sonar dotnet fxcop plugin v2.1

sonar dotnet gendarme plugin v2.1

sonar dotnet ndeps plugin v2.1

sonar dotnet plugin v2.1

sonar dotnet powertool plugin v2.1

sonar resharper plugin v2.0

Latest plugins:

Sonarqube v5.6.6

sonar resharper plugin v2.0 (same from v4.5.6)

sonar fxcop  plugin v1.0 (replacement for the sonar dotnet fxcop plugin v2.1)

I need the replacement plugins for the above current list plugins other than the lastest plugins.

答:
The old dotnet plugin was a kind of enabling plugin for .NET analysis. It is no longer needed. Just install the latest version of SonarC#, which calculates the basic metrics and provides a number of rules, and it will replace the "sonar C# plugin v2.1" as well as the "sonar dotnet plugin v2.1".

The NDeps, Gendarme, and StyleCop plugins are abandoned.

I've never heard of the "sonar dotnet powertool plugin" and Google doesn't seem to know about it either.


问:
Best way to do real time data analytics
I'm currently am interested in performing real time data analytics using real time aircraft performance data for predictive analysis. What tools and technologies could be used to implement such a system on research level?

答:
For real time data analytics if i would be in your place i would have choose the following technologies

1) Kafka for real time Data Ingestion.

2) Spark Streaming for Streaming Processing

3) Spark ML for using machine learning algorithms (Prediction)

4) Apache Zeppelin for Visualization.

5) Data Storage you can use Hive or HDFS as per your needs

6) Ganglia for performance monitoring

Hope this Helps!!!...

Title: Best way to do real time data analytics


问:
Extracting new items from an RSS feed
I'm writing an application which takes data input from a series of arbitrary RSS feeds. The feeds are polled asynchronously in the background and a method is called every time a new item is added to the feed.

My problem is identifying the new items in the feed. What's the best way to do it? I have come up with a few ideas, but they're all flawed.

Suggestion: Every time you poll, keep
  all items newer than the pubDate of
  the last item in the last poll
  Problem: pubDate is not a required
  field.

Suggestion: Keep a hash of the content
  for every item you return, and do not
  return content with the same hash
  Problem: Rapidly grows out of control
  in terms of memory usage

答:
You can use PubDate for those RSS feed where it is provided.
When PubDate is not provided and if duplicate items are exactly equal, ie.. when you can not find any single field to distinguish them,  calculate the md5 checksum and store that for comparison. Use the link  http://sharpertutorials.com/calculate-md5-checksum-file/.  This way you will avoid storing the entire content files and their comparison. Practically you can purge the the checksum data often based upon frequency of new content to avoid the memory problem. If possible maintain multiple hash for the different sources. If you post the actual numbers we may have more realistic solution.</p>

Title: Extracting new items from an RSS feed


问:
Send push notifications to Android
I am currently developing Java web services that run on WebLogic on a server. These web services are called by a mobile application, which is developed by another team. There is a requirement that I need to send push notifications to the mobile application. My current development does not require me to do any mobile development since I am only doing server side development. I don't have experience in mobile development either. How do go about developing push notifications to both Android devices?

Thanks.

答:
Send push notifications to Android

```<code> private void pushNotification(String handlename) {
        StringEntity entity = null;
        JSONObject jsonObject = new JSONObject();
        String referesedtoken = FirebaseInstanceId.getInstance().getToken();
        try {
            jsonObject.put("to", clientToken);
            jsonObject.put("priority", "high");
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(referesedtoken);
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("body", handlename);
            jsonObject1.put("commonContact", commonContact);
            jsonObject1.put("profileType", profileType);
            jsonObject1.put("notification-type", "chat");
            jsonObject1.put("target", handlename);
            jsonObject1.put("email", authPreferences.getEmailAddress());
            jsonObject1.put("UniqueId", authPreferences.getUserUid());
            jsonObject1.put("profilePicUrl", authPreferences.getMyProfilePicImageUrl());
            jsonObject1.put("title", profileBeenClasss.getFirstname() + " " + profileBeenClasss.getLastname() + " has sent message to you");
            jsonObject.put("registrationIDs", jsonArray);
            jsonObject.put("notification", jsonObject1);
            entity = new StringEntity(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
        client.setTimeout(80000);
        client.addHeader("Authorization", "key=AIzaSyCxKiM-LlNHfUOZ3QiiZfSGTo3vTAZdAAI");
        client.post(this, "https://fcm.googleapis.com/fcm/send", entity, "application/json", new TextHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String res) {
                        System.out.println("Send Notification sucessfully" + res.toString());
                   }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
                        System.out.println("notification fail", res.toString());
                    }

                }
        );

    }
</code>```

Title: Send push notifications to Android

Body:
Send push notifications to Android

 private void pushNotification(String handlename) {
        StringEntity entity = null;
        JSONObject jsonObject = new JSONObject();
        String referesedtoken = FirebaseInstanceId.getInstance().getToken();
        try {
            jsonObject.put("to", clientToken);
            jsonObject.put("priority", "high");
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(referesedtoken);
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("body", handlename);
            jsonObject1.put("commonContact", commonContact);
            jsonObject1.put("profileType", profileType);
            jsonObject1.put("notification-type", "chat");
            jsonObject1.put("target", handlename);
            jsonObject1.put("email", authPreferences.getEmailAddress());
            jsonObject1.put("UniqueId", authPreferences.getUserUid());
            jsonObject1.put("profilePicUrl", authPreferences.getMyProfilePicImageUrl());
            jsonObject1.put("title", profileBeenClasss.getFirstname() + " " + profileBeenClasss.getLastname() + " has sent message to you");
            jsonObject.put("registrationIDs", jsonArray);
            jsonObject.put("notification", jsonObject1);
            entity = new StringEntity(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
        client.setTimeout(80000);
        client.addHeader("Authorization", "key=AIzaSyCxKiM-LlNHfUOZ3QiiZfSGTo3vTAZdAAI");
        client.post(this, "https://fcm.googleapis.com/fcm/send", entity, "application/json", new TextHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String res) {
                        System.out.println("Send Notification sucessfully" + res.toString());
                   }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
                        System.out.println("notification fail", res.toString());
                    }

                }
        );

    }


问:
Display datetime as day for xtick
I have the following sample codes:

```<code>import pandas as pd
import matplotlib.pyplot as plt
dates = ['01/02/2007 00:02:00','01/02/2007 00:04:00','02/02/2007
00:02:00','02/02/2007 00:04:00']
x = pd.to_datetime(dates, format='%d/%m/%Y %H:%M:%S')
y = [0.32,0.33,0.32,0.34]
plt.plot(x,y)
</code>```

I would like to have the xtick to be just 'Thu' for 01/02/2007 and 'Fri' for 02/02/2007. What is the best possible way to do that?

答:
The key idea is to get the dayofweek from the DateTime object, like: x.dayofweek. This returns the numeric dayofweek. We can easily get the corresponding name np.array(['Mon','Tue','Wed','Thu','Fri','Sat', 'Sun'])[x.dayofweek]

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
dates = ['01/02/2007 00:02:00','01/02/2007 00:04:00','02/02/2007 00:02:00','02/02/2007 00:04:00']
x = pd.to_datetime(dates, format='%d/%m/%Y %H:%M:%S')
x_d = np.array(['Mon','Tue','Wed','Thu','Fri','Sat', 'Sun'])[x.dayofweek]
y = [0.32,0.33,0.32,0.34]
ser = pd.Series(y, index=x_d)
ser.plot()
</code>```

Title: Display datetime as day for xtick

Body:
I have the following sample codes:

import pandas as pd
import matplotlib.pyplot as plt
dates = ['01/02/2007 00:02:00','01/02/2007 00:04:00','02/02/2007
00:02:00','02/02/2007 00:04:00']
x = pd.to_datetime(dates, format='%d/%m/%Y %H:%M:%S')
y = [0.32,0.33,0.32,0.34]
plt.plot(x,y)

I would like to have the xtick to be just 'Thu' for 01/02/2007 and 'Fri' for 02/02/2007. What is the best possible way to do that?

Body:
The key idea is to get the dayofweek from the DateTime object, like: x.dayofweek. This returns the numeric dayofweek. We can easily get the corresponding name np.array(['Mon','Tue','Wed','Thu','Fri','Sat', 'Sun'])[x.dayofweek]

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
dates = ['01/02/2007 00:02:00','01/02/2007 00:04:00','02/02/2007 00:02:00','02/02/2007 00:04:00']
x = pd.to_datetime(dates, format='%d/%m/%Y %H:%M:%S')
x_d = np.array(['Mon','Tue','Wed','Thu','Fri','Sat', 'Sun'])[x.dayofweek]
y = [0.32,0.33,0.32,0.34]
ser = pd.Series(y, index=x_d)
ser.plot()


答:
The parameter a is passed by value, that means what you're inserting is the address of the local parameter copied from the arguments. a will be constructed  everytime when func is called, their addresses might be same or different; nothing is guaranteed.

And it's worth noting that the parameter a will be destroyed when get out of the function, then the pointers inserted will become dangled.

You should make it pass-by-reference, then the addresses of the arguments (i.e. the variable a, b, c, d in main()) will be inserted. These addresses are different, and won't become dangled inside the body of main().

```<code>void func(set<int*>& s1, set<int*>& s2, int& a)
{
    s1.insert(&a);
    s2.insert(&a);
}
</code>```

LIVE

Title: Inserting addresses into sets, the size of the sets is smaller than expected

Body:
The parameter a is passed by value, that means what you're inserting is the address of the local parameter copied from the arguments. a will be constructed  everytime when func is called, their addresses might be same or different; nothing is guaranteed.

And it's worth noting that the parameter a will be destroyed when get out of the function, then the pointers inserted will become dangled.

You should make it pass-by-reference, then the addresses of the arguments (i.e. the variable a, b, c, d in main()) will be inserted. These addresses are different, and won't become dangled inside the body of main().

void func(set<int*>& s1, set<int*>& s2, int& a)
{
    s1.insert(&a);
    s2.insert(&a);
}

LIVE


问:
How to display YouTube like black title box?
I want to view black title box instead of regular title box like  and I think there is readymade HTML tag for this as far I know because i have seen it somewhere else but couldn't remember at all! Please help me if you know the tag for this.

Above share button you can see a black box titled Share. I want to view that!

答:
w3schools has one as @Ihaz mentioned. Link

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  bottom: 150%;
  left: 50%;
  margin-left: -60px;
}

.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: black transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body style="text-align:center;">
  <h2>Top Tooltip w/ Bottom Arrow</h2>

  <div class="tooltip">Hover over me
    <span class="tooltiptext">Tooltip text</span>
  </div>
</body></code>```

A creative one if needed;

.wrapper {
  text-transform: uppercase;
  background: #ececec;
  color: #555;
  cursor: help;
  font-family: "Gill Sans", Impact, sans-serif;
  font-size: 20px;
  margin: 100px 75px 10px 75px;
  padding: 15px 20px;
  position: relative;
  text-align: center;
  width: 200px;
  -webkit-transform: translateZ(0);
  /* webkit flicker fix */
  -webkit-font-smoothing: antialiased;
  /* webkit text rendering fix */
}

.wrapper .tooltip {
  background: #e84747;
  bottom: 100%;
  color: #fff;
  display: block;
  left: -20px;
  margin-bottom: 15px;
  opacity: 0;
  padding: 20px;
  pointer-events: none;
  position: absolute;
  width: 100%;
  -webkit-transform: translateY(10px);
  -moz-transform: translateY(10px);
  -ms-transform: translateY(10px);
  -o-transform: translateY(10px);
  transform: translateY(10px);
  -webkit-transition: all .25s ease-out;
  -moz-transition: all .25s ease-out;
  -ms-transition: all .25s ease-out;
  -o-transition: all .25s ease-out;
  transition: all .25s ease-out;
  -webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  -moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  -ms-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  -o-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}

/* This bridges the gap so you can mouse into the tooltip without it disappearing */

.wrapper .tooltip:before {
  bottom: -20px;
  content: " ";
  display: block;
  height: 20px;
  left: 0;
  position: absolute;
  width: 100%;
}

.wrapper .tooltip:after {
  border-left: solid transparent 10px;
  border-right: solid transparent 10px;
  border-top: solid #e84747 10px;
  bottom: -10px;
  content: " ";
  height: 0;
  left: 50%;
  margin-left: -13px;
  position: absolute;
  width: 0;
}

.wrapper:hover .tooltip {
  opacity: 1;
  pointer-events: auto;
  -webkit-transform: translateY(0px);
  -moz-transform: translateY(0px);
  -ms-transform: translateY(0px);
  -o-transform: translateY(0px);
  transform: translateY(0px);
}

/* IE can just show/hide with no transition */

.lte8 .wrapper .tooltip {
  display: none;
}

.lte8 .wrapper:hover .tooltip {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  Subscribe
  <div class="tooltip">Subscribe to Channel</div>
</div>
</div></code>```

Body:
w3schools has one as @Ihaz mentioned. Link

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  bottom: 150%;
  left: 50%;
  margin-left: -60px;
}

.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: black transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}

<body style="text-align:center;">
  <h2>Top Tooltip w/ Bottom Arrow</h2>

  <div class="tooltip">Hover over me
    <span class="tooltiptext">Tooltip text</span>
  </div>
</body>

A creative one if needed;

.wrapper {
  text-transform: uppercase;
  background: #ececec;
  color: #555;
  cursor: help;
  font-family: "Gill Sans", Impact, sans-serif;
  font-size: 20px;
  margin: 100px 75px 10px 75px;
  padding: 15px 20px;
  position: relative;
  text-align: center;
  width: 200px;
  -webkit-transform: translateZ(0);
  /* webkit flicker fix */
  -webkit-font-smoothing: antialiased;
  /* webkit text rendering fix */
}

.wrapper .tooltip {
  background: #e84747;
  bottom: 100%;
  color: #fff;
  display: block;
  left: -20px;
  margin-bottom: 15px;
  opacity: 0;
  padding: 20px;
  pointer-events: none;
  position: absolute;
  width: 100%;
  -webkit-transform: translateY(10px);
  -moz-transform: translateY(10px);
  -ms-transform: translateY(10px);
  -o-transform: translateY(10px);
  transform: translateY(10px);
  -webkit-transition: all .25s ease-out;
  -moz-transition: all .25s ease-out;
  -ms-transition: all .25s ease-out;
  -o-transition: all .25s ease-out;
  transition: all .25s ease-out;
  -webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  -moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  -ms-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  -o-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
  box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}

/* This bridges the gap so you can mouse into the tooltip without it disappearing */

.wrapper .tooltip:before {
  bottom: -20px;
  content: " ";
  display: block;
  height: 20px;
  left: 0;
  position: absolute;
  width: 100%;
}

.wrapper .tooltip:after {
  border-left: solid transparent 10px;
  border-right: solid transparent 10px;
  border-top: solid #e84747 10px;
  bottom: -10px;
  content: " ";
  height: 0;
  left: 50%;
  margin-left: -13px;
  position: absolute;
  width: 0;
}

.wrapper:hover .tooltip {
  opacity: 1;
  pointer-events: auto;
  -webkit-transform: translateY(0px);
  -moz-transform: translateY(0px);
  -ms-transform: translateY(0px);
  -o-transform: translateY(0px);
  transform: translateY(0px);
}

/* IE can just show/hide with no transition */

.lte8 .wrapper .tooltip {
  display: none;
}

.lte8 .wrapper:hover .tooltip {
  display: block;
}

<div class="wrapper">
  Subscribe
  <div class="tooltip">Subscribe to Channel</div>
</div>
</div>


问:
How can I make my TextView font as shown in image
I am trying to style my text of STUDENT LOGIN which is shown in the image.
But I don't know how can use a different custom font to make my STUDENT LOGIN to look like as shown in the image.

I want Style in that way. How Can I make my S and L shown in image

答:
you can use simple HTML tags in your strings. You can do the following:

```<code>textView.setText(Html.fromHtml("<b>S</b>tudent <b>L</b>ogin"));
</code>```

This way S and L will become bold, while all other chars will be regular.

Body:
you can use simple HTML tags in your strings. You can do the following:

textView.setText(Html.fromHtml("<b>S</b>tudent <b>L</b>ogin"));

This way S and L will become bold, while all other chars will be regular.


问:
How can i Get All days of Next and Previous dates
I want to get all days of next and Prev dates.
I have Three buttons there are PrevDate, TodayDate, NextDate.
When i am clicking 1st time on prevDate button it should show previous date and clicking 2nd time it show day before day similarly it should show all prev dates when i am clicking.. samething in Nextdate also it show next day of date. 2nd time clicking it show day after day of date..
This is my HTML Code:

```<code><body ng-app="app" ng-controller="myCtrl">
 <div class="col-sm-10" >
   <button style="font-size:14px" ng-click="prevBtn()">Previous day</button>
   <button style="font-size:14px" ng-click="todayBtn()" > Today </button>
   <button style="font-size:14px" ng-click="nextBtn()" >Next day</button>
   {{date}}
 </div>
</body>
</code>```

app.js Code :

```<code>var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
   var today = new Date();

       $scope.prevBtn = function(){
           var yesterday = new Date(today);
           yesterday.setDate(today.getDate() - 1);
           var dd = yesterday.getDate();
           var mm = yesterday.getMonth()+1;
           var yyyy = yesterday.getFullYear();
           yesterday = dd+'-'+mm+'-'+yyyy;
           console.log(yesterday);
           $scope.date = yesterday;
       }
});
</code>```

This code showing prev date only..
I want to get all days of Prev dates....
Please Help me... Thanks...

答:
keep a reference for current date

```<code>var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  var today = new Date();

  var curDay = new Date(today);
  $scope.prevBtn = function() {

    curDay.setDate(curDay.getDate() - 1);
    var dd = curDay.getDate();
    var mm = curDay.getMonth() + 1;
    var yyyy = curDay.getFullYear();
    var yesterday = dd + '-' + mm + '-' + yyyy;
    console.log(yesterday);
    $scope.date = yesterday;
  }
});
</code>```

the following snippet may help you for your sample app

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  var today = new Date();

  var curDay = new Date(today);
  $scope.prevBtn = function() {

    curDay.setDate(curDay.getDate() - 1);
    showDate();

  }

  $scope.todayBtn = function() {
    curDay = new Date(today);
    showDate();
  };

  $scope.nextBtn = function() {
    curDay.setDate(curDay.getDate() + 1);
    showDate();
  };

  function showDate() {
    var dd = curDay.getDate();
    var mm = curDay.getMonth() + 1;
    var yyyy = curDay.getFullYear();
    var dateStr = dd + '-' + mm + '-' + yyyy;
    console.log(dateStr);
    $scope.date = dateStr;
  };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
  <div class="col-sm-10">
    <button style="font-size:14px" ng-click="prevBtn()">Previous day</button>
    <button style="font-size:14px" ng-click="todayBtn()"> Today </button>
    <button style="font-size:14px" ng-click="nextBtn()">Next day</button> {{date}}
  </div>
</body></code>```

Body:
I want to get all days of next and Prev dates.
I have Three buttons there are PrevDate, TodayDate, NextDate.
When i am clicking 1st time on prevDate button it should show previous date and clicking 2nd time it show day before day similarly it should show all prev dates when i am clicking.. samething in Nextdate also it show next day of date. 2nd time clicking it show day after day of date..
This is my HTML Code:

   <button style="font-size:14px" ng-click="prevBtn()">Previous day</button>
   <button style="font-size:14px" ng-click="todayBtn()" > Today </button>
   <button style="font-size:14px" ng-click="nextBtn()" >Next day</button>
   {{date}}

app.js Code :

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
   var today = new Date();

       $scope.prevBtn = function(){
           var yesterday = new Date(today);
           yesterday.setDate(today.getDate() - 1);
           var dd = yesterday.getDate();
           var mm = yesterday.getMonth()+1;
           var yyyy = yesterday.getFullYear();
           yesterday = dd+'-'+mm+'-'+yyyy;
           console.log(yesterday);
           $scope.date = yesterday;
       }
});

This code showing prev date only..
I want to get all days of Prev dates....
Please Help me... Thanks...

Body:
keep a reference for current date

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  var today = new Date();

  var curDay = new Date(today);
  $scope.prevBtn = function() {

    curDay.setDate(curDay.getDate() - 1);
    var dd = curDay.getDate();
    var mm = curDay.getMonth() + 1;
    var yyyy = curDay.getFullYear();
    var yesterday = dd + '-' + mm + '-' + yyyy;
    console.log(yesterday);
    $scope.date = yesterday;
  }
});

the following snippet may help you for your sample app

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  var today = new Date();

  var curDay = new Date(today);
  $scope.prevBtn = function() {

    curDay.setDate(curDay.getDate() - 1);
    showDate();

  }

  $scope.todayBtn = function() {
    curDay = new Date(today);
    showDate();
  };

  $scope.nextBtn = function() {
    curDay.setDate(curDay.getDate() + 1);
    showDate();
  };

  function showDate() {
    var dd = curDay.getDate();
    var mm = curDay.getMonth() + 1;
    var yyyy = curDay.getFullYear();
    var dateStr = dd + '-' + mm + '-' + yyyy;
    console.log(dateStr);
    $scope.date = dateStr;
  };

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
  <div class="col-sm-10">
    <button style="font-size:14px" ng-click="prevBtn()">Previous day</button>
    <button style="font-size:14px" ng-click="todayBtn()">&nbsp;Today&nbsp;</button>
    <button style="font-size:14px" ng-click="nextBtn()">Next day</button> {{date}}
  </div>
</body>


问:
Array equation explanation
I would appreciate if someone could explain why the output of this code:

```<code>*a, b = [1, 2, 3, 4]
a[b-2] + b
</code>```

is 7. Could anyone please break it down line by line so I understand what's going on here? How does this become 7?

Title: Array equation explanation

Body:
I would appreciate if someone could explain why the output of this code:

*a, b = [1, 2, 3, 4]
a[b-2] + b

is 7. Could anyone please break it down line by line so I understand what's going on here? How does this become 7?

Body:
*a, b = [1, 2, 3, 4]

a
 => [1, 2, 3]

b
 => 4

a[b-2] // b-2 = 2 find value at index of 2 in a, like a[2] is 3
 => 3

a[b-2]+b
 => 7


问:
Message: 'chromedriver' executable needs to be in PATH
So, I am using OS X  El Capitan with  Eclipse (Neo) and Python.  I am wrote some Python with Selenium scripts.

These scripts were working fine.

Then I upgraded from OSX Sierra to El Capitan

Note: this is about the only major change
  that I did to my setup.

When I tried to run the same scripts, now, I get the

Message: chromedriver executable needs to be in PATH

As far I can tell chromedriver IS on my PATH.

Now, I can only make my scripts work if I hard copy the path to my chrome driver, which is not the most elegant way to do things, as we all know.

Has anyone else has/had this issue?  Thoughts on any configuration with my Eclipse + Python.

My Eclipse and Python project screen shot

my PYTHONPATH screen shot

答:
First of all verify your driver path , if you open a command prompt and type in chromedriver  and hit Enter. If you get message "Starting ChromeDriver 2.15.322448 .." your path is correctly set up.

In python, alternate solution is you can use

driver = webdriver.Chrome("path_to_driver/chromedriver.exe")

 Hope this should work !


问:
What Ruby technique does Rails use to make my controller methods render views?
Just curious if anybody knows what Ruby technique is used to accomplish the following in the Rails framework.

If I don't write, say, an index method on a Rails controller, Rails will still render the index view file if the URL matches that route. That makes sense, because my controller inherits from a parent class, which must have its own index method.

However, if I do define an index method, and only tell it to set an instance variable, it still renders the appropriate view. For example:

```<code>def index
  @weasels = Weasel.all

  # If I omit this line, Rails renders the index anyway.
  # If this behavior is defined in the parent class's index method,
  # it seems that by overriding the method, my index wouldn't do it.
  # I'm not explicitly calling super to get the method from
  # ActionController::Base, but maybe Rails is doing something like that?
  render :index
end
</code>```

In pure Ruby, I would expect to have to call super to get that behavior.

I assume that Rails uses some kind of metaprogramming technique to guarantee that my controller methods will call super. If so, can anyone explain it? Can you point to the source code that does this?

Update

As Mladen Jablanović has pointed out, my initial mental model was wrong; the controller method doesn't normally render the view; instead, both the controller method and the view rendering are called by some framework code. This is apparent because I can make a controller method with any name - for example, search - and the search view will get rendered. So clearly I'm not overriding a parent method in that case, and some framework code is parsing the controller method name and looking for the matching view.

Still, the framework must be able to detect whether or not the controller method has already called render. So that's another small mystery to me.

答:
On the controller, there is a method called render_for_text. This takes a string and sets the result as the response body. Even if you don't render as text, rendering a view file simply reads the file's contents, evaluates it, and passes it to the render_for_text method. The method then stores sets an instance variable called @performed_render to true, which tells rails that the controller has already rendered a view.

There is then a method called performed? that indicates whether or not the render action has been called. It does this by checking if @performed_render or @performed_redirect is true.

With the above information, the very first line of the render method should make sense now, and hopefully answer your question:

raise DoubleRenderError, "Can only render or redirect once per action" if performed?

Body:
Just curious if anybody knows what Ruby technique is used to accomplish the following in the Rails framework.

If I don't write, say, an index method on a Rails controller, Rails will still render the index view file if the URL matches that route. That makes sense, because my controller inherits from a parent class, which must have its own index method.

However, if I do define an index method, and only tell it to set an instance variable, it still renders the appropriate view. For example:

def index
  @weasels = Weasel.all

  # If I omit this line, Rails renders the index anyway.
  # If this behavior is defined in the parent class's index method,
  # it seems that by overriding the method, my index wouldn't do it.
  # I'm not explicitly calling super to get the method from
  # ActionController::Base, but maybe Rails is doing something like that?
  render :index
end

In pure Ruby, I would expect to have to call super to get that behavior.

I assume that Rails uses some kind of metaprogramming technique to guarantee that my controller methods will call super. If so, can anyone explain it? Can you point to the source code that does this?

Update

As Mladen Jablanović has pointed out, my initial mental model was wrong; the controller method doesn't normally render the view; instead, both the controller method and the view rendering are called by some framework code. This is apparent because I can make a controller method with any name - for example, search - and the search view will get rendered. So clearly I'm not overriding a parent method in that case, and some framework code is parsing the controller method name and looking for the matching view.

Still, the framework must be able to detect whether or not the controller method has already called render. So that's another small mystery to me.


问:
Warning: include(../includes/db.php): failed to open stream:
This is the problem I am facing now Can you please suggest me to get rid of this problem. Before I have not get this problem It was working nicely now I don't know what happened the path is correct only. Anyone please solve it...

Warning: include(../includes/db.php): failed to open stream: No such
  file or directory in
  C:\xampp\htdocs\portfolio\admin\includes\admin_header.php on line 3
  Warning: include(): Failed opening '../includes/db.php' for inclusion
  (include_path='C:\xampp\php\PEAR') in
  C:\xampp\htdocs\portfolio\admin\includes\admin_header.php on line 3
  Warning: include(functions.php): failed to open stream: No such file
  or directory in
  C:\xampp\htdocs\portfolio\admin\includes\admin_header.php on line 4
  Warning: include(): Failed opening 'functions.php' for inclusion
  (include_path='C:\xampp\php\PEAR') in
  C:\xampp\htdocs\portfolio\admin\includes\admin_header.php on line 4

答:
Try removing relative paths ("../")
e.g. change include(../includes/db.php) to include(includes/db.php)


问:
'An item with the same key has already been added.' -- Which key?
The following code:

```<code>var rnd = new Random();
Enumerable.Range(1,20).Select(x => rnd.Next(10)).ToDictionary(x => x, x => "");
</code>```

will inevitably fail with the following exception:

System.ArgumentException: 'An item with the same key has already been added.'

Is there any way to use the Visual Studio IDE while debugging, to find out the attempted key? Is the key stored somewhere in the exception details -- some internal / private field perhaps; which can be read using the exception details window?

I can't change the source of ToDictionary to include the key in the thrown exception.

Note: I am aware that I can rewrite this in a debuggable fashion, using a For Each loop instead of LINQ. But I am asking about the general case -- when this exception is thrown, and the source code is not under my control, is there some way to access the key?

Using VS 2017 Community Edition.

答:
I don't believe it's feasible to get that information from the exception with the current desktop .NET framework. (Although you can do it in the debugger, if you're willing to jump through some hoops.)

The good news is that in .NET Core, you do get to see the key, as you can see by following the source code:

Dictionary.Add

Dictionary.TryInsert

ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException

SR.Argument_AddingDuplicateWithKey

So on .NET Core you end up with an exception like this:

```<code>System.ArgumentException: An item with the same key has already been added. Key: x
</code>```

I don't believe you can programmatically determine the key at this point, but at least you can tell for debugging purposes, assuming the string representation of your key is sufficiently detailed.

I'd hope that at some point this might make it into the desktop version of .NET.

Body:
The following code:

var rnd = new Random();
Enumerable.Range(1,20).Select(x => rnd.Next(10)).ToDictionary(x => x, x => "");

will inevitably fail with the following exception:

System.ArgumentException: 'An item with the same key has already been added.'

Is there any way to use the Visual Studio IDE while debugging, to find out the attempted key? Is the key stored somewhere in the exception details -- some internal / private field perhaps; which can be read using the exception details window?

I can't change the source of ToDictionary to include the key in the thrown exception.

Note: I am aware that I can rewrite this in a debuggable fashion, using a For Each loop instead of LINQ. But I am asking about the general case -- when this exception is thrown, and the source code is not under my control, is there some way to access the key?

Using VS 2017 Community Edition.

Body:
I don't believe it's feasible to get that information from the exception with the current desktop .NET framework. (Although you can do it in the debugger, if you're willing to jump through some hoops.)

The good news is that in .NET Core, you do get to see the key, as you can see by following the source code:

Dictionary.Add

Dictionary.TryInsert

ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException

SR.Argument_AddingDuplicateWithKey

So on .NET Core you end up with an exception like this:

System.ArgumentException: An item with the same key has already been added. Key: x

I don't believe you can programmatically determine the key at this point, but at least you can tell for debugging purposes, assuming the string representation of your key is sufficiently detailed.

I'd hope that at some point this might make it into the desktop version of .NET.


答:
One possible solution is to change the X-axis format:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = ['01/02/2007 00:02:00','01/02/2007 00:04:00','02/02/2007 00:02:00','02/02/2007 00:04:00']
x = pd.to_datetime(dates, format='%d/%m/%Y %H:%M:%S')
y = [0.32,0.33,0.32,0.34]

fig, ax = plt.subplots()

ax.plot(x,y)

yearsFmt = mdates.DateFormatter('%a')
ax.xaxis.set_major_formatter(yearsFmt)
plt.show()
</code>```

Title: Display datetime as day for xtick

Body:
One possible solution is to change the X-axis format:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = ['01/02/2007 00:02:00','01/02/2007 00:04:00','02/02/2007 00:02:00','02/02/2007 00:04:00']
x = pd.to_datetime(dates, format='%d/%m/%Y %H:%M:%S')
y = [0.32,0.33,0.32,0.34]

fig, ax = plt.subplots()

ax.plot(x,y)

yearsFmt = mdates.DateFormatter('%a')
ax.xaxis.set_major_formatter(yearsFmt)
plt.show()


问:
Database design - defining a basic many-to-one relationship
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

```<code>PrimaryCustomerID  RelationshipID  SecondaryCustomerID
</code>```

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?

答:
Nothing wrong with No 3.

If you need to prevent reverse-relationship duplicates, you can use

```<code>ALTER TABLE CustomerRelationship
ADD CONSTRAINT chk_id CHECK (PrimaryCustomerId < SecondaryCustomerId);
</code>```

Body:
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

PrimaryCustomerID  RelationshipID  SecondaryCustomerID

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?

Body:
Nothing wrong with No 3.

If you need to prevent reverse-relationship duplicates, you can use

ALTER TABLE CustomerRelationship
ADD CONSTRAINT chk_id CHECK (PrimaryCustomerId < SecondaryCustomerId);


问:
PHP date function is returning wrong month and date
I have been working in PHP Development for 5 years but never seen this type of error before.

I have a date which is the last day of the month and I am going to change its format with using below code :

```<code>$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;
</code>```

It outputs :

2017-04-31 00:00:00 : 01-05-2017 ###

I am working on PHP version 5.6.25.
Is there anyone can help me in this??

答: April only has 30 days, so it's actually correcting the date your using.  The 31st would really be the 1st of May.</p>

Body:
I have been working in PHP Development for 5 years but never seen this type of error before.

I have a date which is the last day of the month and I am going to change its format with using below code :

$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;

It outputs :

2017-04-31 00:00:00 : 01-05-2017 ###

I am working on PHP version 5.6.25.
Is there anyone can help me in this??


答: The 31th April don't exist. Because of that PHP going to the day after the 30th April</p>

Title: PHP date function is returning wrong month and date


问:
Unable to Deserialize Attributes
I have the following element in some XML which I need to deserialize:

```<code><settlementLineItem number="1">
    <amountPaid>38250.89</amountPaid>
    <originalAmount>42501.00</originalAmount>
    <adjustmentAndDiscount>
        <amount>850.02</amount>
        <adjustmentReason>
            <messageReason>XG 2.000 % Distribution Allow.</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200527269</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <adjustmentAndDiscount>
        <amount>2125.05</amount>
        <adjustmentReason>
            <messageReason>XI 5.000 % Incentive Discount</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200528098</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <adjustmentAndDiscount>
        <amount>1062.53</amount>
        <adjustmentReason>
            <messageReason>XF 2.500 % Advertising Allow.</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200529157</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <adjustmentAndDiscount>
        <amount>212.51</amount>
        <adjustmentReason>
            <messageReason>XO 0.500 % Training & Dev. Cost</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200529467</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <invoice creationDateTime="2017-06-28">
        <uniqueCreatorIdentification>4912115908</uniqueCreatorIdentification>
        <contentOwner>
            <gln>6001000000001</gln>
        </contentOwner>
        <invoiceType>CREDIT_NOTE </invoiceType>
    </invoice>
    <settlementEntity entityType="SITE">
        <partyIdentification>
            <gln>6001007031336</gln>
        </partyIdentification>
    </settlementEntity>
</settlementLineItem>
</code>```

I am using this class to represent that particular element:

```<code>[XmlRoot(ElementName = "settlementLineItem")]
public class SettlementLineItem
{
    [XmlAttribute(AttributeName = "number")]
    public string Number { get; set; }

    // Standard data
    [XmlElement(ElementName = "amountPaid")]
    public string AmountPaid { get; set; }
    [XmlElement(ElementName = "originalAmount")]
    public string OriginalAmount { get; set; }
    [XmlElement(ElementName = "invoice")]
    public Invoice Invoice { get; set; }
    [XmlElement(ElementName = "settlementEntity")]
    public SettlementEntity SettlementEntity { get; set; }
    [XmlElement(ElementName = "adjustmentAndDiscount")]
    public List<AdjustmentAndDiscount> AdjustmentAndDiscount { get; set; }

    // Exetension data
    [XmlElement(ElementName = "documentType")]
    public string DocumentType { get; set; }
    [XmlElement(ElementName = "documentNumber")]
    public string DocumentNumber { get; set; }
    [XmlElement(ElementName = "itemText")]
    public string ItemText { get; set; }
}
</code>```

The code which performs the deserialization:

```<code>private Message DeserializeXml(string xml)
{
    var serializer = new XmlSerializer(typeof(Message));
    using (var reader = new StringReader(xml))
    {
        return (Message)serializer.Deserialize(reader);
    }
}
</code>```

All the elements apper to deserialize without any problems, but the Number attribute is always null.

I am seeing this issue for all attributes in the document which I am trying to deserialize.

Does anyone know why this might be happening?

Note that I have not included the entire xml message (it is huge, and of type Message), but this should be enough information, as the deserialization itself is successful (just not when it comes to attributes).

Thanks!

Edit

Code for Invoice, SettlementEntity, AdjustmentAndDiscount

```<code>[XmlRoot(ElementName = "invoice")]
public class Invoice
{
    [XmlElement(ElementName = "uniqueCreatorIdentification")]
    public string UniqueCreatorIdentification { get; set; }
    [XmlElement(ElementName = "contentOwner")]
    public ContentOwner ContentOwner { get; set; }
    [XmlElement(ElementName = "invoiceType")]
    public string InvoiceType { get; set; }
}

[XmlRoot(ElementName = "settlementEntity")]
public class SettlementEntity
{
    [XmlElement(ElementName = "partyIdentification")]
    public PartyIdentification PartyIdentification { get; set; }
}

[XmlRoot(ElementName = "adjustmentAndDiscount")]
public class AdjustmentAndDiscount
{
    [XmlElement(ElementName = "adjustmentReason")]
    public AdjustmentReason AdjustmentReason { get; set; }

    // LineItem data
    [XmlElement(ElementName = "amount")]
    public string Amount { get; set; }
    [XmlElement(ElementName = "alternateAdjustmentReference")]
    public AlternateAdjustmentReference AlternateAdjustmentReference { get; set; }

    // Summary data
    [XmlElement(ElementName = "amountTotal")]
    public string AmountTotal { get; set; }
    [XmlElement(ElementName = "amountNet")]
    public string AmountNet { get; set; }
    [XmlElement(ElementName = "amountVAT")]
    public string AmountVAT { get; set; }
}
</code>```

答:
I have created an xml file inside the application named as "XMLFile1.xml" and copied your xml string to the "XMLFile1.xml" file.

CODE

```<code>using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace DeserializeXMLConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlString = File.ReadAllText(@"D:\My Apps\Console Applications\DeserializeXMLConsoleApp\DeserializeXMLConsoleApp\XMLFile1.xml");
            var serializer = new XmlSerializer(typeof(SettlementLineItem));
            using (var reader = new StringReader(xmlString))
            {
                var finalResult =  (SettlementLineItem)serializer.Deserialize(reader);
            }
            Console.Read();
        }
    }

    [XmlRoot(ElementName = "adjustmentReason")]
    public class AdjustmentReason
    {
        [XmlElement(ElementName = "messageReason")]
        public string MessageReason { get; set; }
        [XmlElement(ElementName = "sourceCode")]
        public string SourceCode { get; set; }
    }

    [XmlRoot(ElementName = "alternateAdjustmentReference")]
    public class AlternateAdjustmentReference
    {
        [XmlElement(ElementName = "alternateAdjustmentReferenceType")]
        public string AlternateAdjustmentReferenceType { get; set; }
        [XmlElement(ElementName = "identification")]
        public string Identification { get; set; }
    }

    [XmlRoot(ElementName = "adjustmentAndDiscount")]
    public class AdjustmentAndDiscount
    {
        [XmlElement(ElementName = "amount")]
        public string Amount { get; set; }
        [XmlElement(ElementName = "adjustmentReason")]
        public AdjustmentReason AdjustmentReason { get; set; }
        [XmlElement(ElementName = "alternateAdjustmentReference")]
        public AlternateAdjustmentReference AlternateAdjustmentReference { get; set; }
    }

    [XmlRoot(ElementName = "contentOwner")]
    public class ContentOwner
    {
        [XmlElement(ElementName = "gln")]
        public string Gln { get; set; }
    }

    [XmlRoot(ElementName = "invoice")]
    public class Invoice
    {
        [XmlElement(ElementName = "uniqueCreatorIdentification")]
        public string UniqueCreatorIdentification { get; set; }
        [XmlElement(ElementName = "contentOwner")]
        public ContentOwner ContentOwner { get; set; }
        [XmlElement(ElementName = "invoiceType")]
        public string InvoiceType { get; set; }
        [XmlAttribute(AttributeName = "creationDateTime")]
        public string CreationDateTime { get; set; }
    }

    [XmlRoot(ElementName = "partyIdentification")]
    public class PartyIdentification
    {
        [XmlElement(ElementName = "gln")]
        public string Gln { get; set; }
    }

    [XmlRoot(ElementName = "settlementEntity")]
    public class SettlementEntity
    {
        [XmlElement(ElementName = "partyIdentification")]
        public PartyIdentification PartyIdentification { get; set; }
        [XmlAttribute(AttributeName = "entityType")]
        public string EntityType { get; set; }
    }

    [XmlRoot(ElementName = "settlementLineItem")]
    public class SettlementLineItem
    {
        [XmlElement(ElementName = "amountPaid")]
        public string AmountPaid { get; set; }
        [XmlElement(ElementName = "originalAmount")]
        public string OriginalAmount { get; set; }
        [XmlElement(ElementName = "adjustmentAndDiscount")]
        public List<AdjustmentAndDiscount> AdjustmentAndDiscount { get; set; }
        [XmlElement(ElementName = "invoice")]
        public Invoice Invoice { get; set; }
        [XmlElement(ElementName = "settlementEntity")]
        public SettlementEntity SettlementEntity { get; set; }
        [XmlAttribute(AttributeName = "number")]
        public string Number { get; set; }
    }
}
</code>```

OUTPUT > See the Number attribute value

Please check and revert me back if it solves your problem or not.

Title: Unable to Deserialize Attributes

Body:
I have the following element in some XML which I need to deserialize:

<settlementLineItem number="1">
    <amountPaid>38250.89</amountPaid>
    <originalAmount>42501.00</originalAmount>
    <adjustmentAndDiscount>
        <amount>850.02</amount>
        <adjustmentReason>
            <messageReason>XG 2.000 % Distribution Allow.</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200527269</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <adjustmentAndDiscount>
        <amount>2125.05</amount>
        <adjustmentReason>
            <messageReason>XI 5.000 % Incentive Discount</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200528098</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <adjustmentAndDiscount>
        <amount>1062.53</amount>
        <adjustmentReason>
            <messageReason>XF 2.500 % Advertising Allow.</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200529157</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <adjustmentAndDiscount>
        <amount>212.51</amount>
        <adjustmentReason>
            <messageReason>XO 0.500 % Training & Dev. Cost</messageReason>
            <sourceCode>TNT</sourceCode>
        </adjustmentReason>
        <alternateAdjustmentReference>
            <alternateAdjustmentReferenceType>DOC_NO</alternateAdjustmentReferenceType>
            <identification>2200529467</identification>
        </alternateAdjustmentReference>
    </adjustmentAndDiscount>
    <invoice creationDateTime="2017-06-28">
        <uniqueCreatorIdentification>4912115908</uniqueCreatorIdentification>
        <contentOwner>
            <gln>6001000000001</gln>
        </contentOwner>
        <invoiceType>CREDIT_NOTE </invoiceType>
    </invoice>
    <settlementEntity entityType="SITE">
        <partyIdentification>
            <gln>6001007031336</gln>
        </partyIdentification>
    </settlementEntity>
</settlementLineItem>

I am using this class to represent that particular element:

[XmlRoot(ElementName = "settlementLineItem")]
public class SettlementLineItem
{
    [XmlAttribute(AttributeName = "number")]
    public string Number { get; set; }

    // Standard data
    [XmlElement(ElementName = "amountPaid")]
    public string AmountPaid { get; set; }
    [XmlElement(ElementName = "originalAmount")]
    public string OriginalAmount { get; set; }
    [XmlElement(ElementName = "invoice")]
    public Invoice Invoice { get; set; }
    [XmlElement(ElementName = "settlementEntity")]
    public SettlementEntity SettlementEntity { get; set; }
    [XmlElement(ElementName = "adjustmentAndDiscount")]
    public List<AdjustmentAndDiscount> AdjustmentAndDiscount { get; set; }

    // Exetension data
    [XmlElement(ElementName = "documentType")]
    public string DocumentType { get; set; }
    [XmlElement(ElementName = "documentNumber")]
    public string DocumentNumber { get; set; }
    [XmlElement(ElementName = "itemText")]
    public string ItemText { get; set; }
}

The code which performs the deserialization:

private Message DeserializeXml(string xml)
{
    var serializer = new XmlSerializer(typeof(Message));
    using (var reader = new StringReader(xml))
    {
        return (Message)serializer.Deserialize(reader);
    }
}

All the elements apper to deserialize without any problems, but the Number attribute is always null.

I am seeing this issue for all attributes in the document which I am trying to deserialize.

Does anyone know why this might be happening?

Note that I have not included the entire xml message (it is huge, and of type Message), but this should be enough information, as the deserialization itself is successful (just not when it comes to attributes).

Thanks!

Edit

Code for Invoice, SettlementEntity, AdjustmentAndDiscount

[XmlRoot(ElementName = "invoice")]
public class Invoice
{
    [XmlElement(ElementName = "uniqueCreatorIdentification")]
    public string UniqueCreatorIdentification { get; set; }
    [XmlElement(ElementName = "contentOwner")]
    public ContentOwner ContentOwner { get; set; }
    [XmlElement(ElementName = "invoiceType")]
    public string InvoiceType { get; set; }
}

[XmlRoot(ElementName = "settlementEntity")]
public class SettlementEntity
{
    [XmlElement(ElementName = "partyIdentification")]
    public PartyIdentification PartyIdentification { get; set; }
}

[XmlRoot(ElementName = "adjustmentAndDiscount")]
public class AdjustmentAndDiscount
{
    [XmlElement(ElementName = "adjustmentReason")]
    public AdjustmentReason AdjustmentReason { get; set; }

    // LineItem data
    [XmlElement(ElementName = "amount")]
    public string Amount { get; set; }
    [XmlElement(ElementName = "alternateAdjustmentReference")]
    public AlternateAdjustmentReference AlternateAdjustmentReference { get; set; }

    // Summary data
    [XmlElement(ElementName = "amountTotal")]
    public string AmountTotal { get; set; }
    [XmlElement(ElementName = "amountNet")]
    public string AmountNet { get; set; }
    [XmlElement(ElementName = "amountVAT")]
    public string AmountVAT { get; set; }
}

Body:
I have created an xml file inside the application named as "XMLFile1.xml" and copied your xml string to the "XMLFile1.xml" file.

CODE

using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace DeserializeXMLConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlString = File.ReadAllText(@"D:\My Apps\Console Applications\DeserializeXMLConsoleApp\DeserializeXMLConsoleApp\XMLFile1.xml");
            var serializer = new XmlSerializer(typeof(SettlementLineItem));
            using (var reader = new StringReader(xmlString))
            {
                var finalResult =  (SettlementLineItem)serializer.Deserialize(reader);
            }
            Console.Read();
        }
    }

    [XmlRoot(ElementName = "adjustmentReason")]
    public class AdjustmentReason
    {
        [XmlElement(ElementName = "messageReason")]
        public string MessageReason { get; set; }
        [XmlElement(ElementName = "sourceCode")]
        public string SourceCode { get; set; }
    }

    [XmlRoot(ElementName = "alternateAdjustmentReference")]
    public class AlternateAdjustmentReference
    {
        [XmlElement(ElementName = "alternateAdjustmentReferenceType")]
        public string AlternateAdjustmentReferenceType { get; set; }
        [XmlElement(ElementName = "identification")]
        public string Identification { get; set; }
    }

    [XmlRoot(ElementName = "adjustmentAndDiscount")]
    public class AdjustmentAndDiscount
    {
        [XmlElement(ElementName = "amount")]
        public string Amount { get; set; }
        [XmlElement(ElementName = "adjustmentReason")]
        public AdjustmentReason AdjustmentReason { get; set; }
        [XmlElement(ElementName = "alternateAdjustmentReference")]
        public AlternateAdjustmentReference AlternateAdjustmentReference { get; set; }
    }

    [XmlRoot(ElementName = "contentOwner")]
    public class ContentOwner
    {
        [XmlElement(ElementName = "gln")]
        public string Gln { get; set; }
    }

    [XmlRoot(ElementName = "invoice")]
    public class Invoice
    {
        [XmlElement(ElementName = "uniqueCreatorIdentification")]
        public string UniqueCreatorIdentification { get; set; }
        [XmlElement(ElementName = "contentOwner")]
        public ContentOwner ContentOwner { get; set; }
        [XmlElement(ElementName = "invoiceType")]
        public string InvoiceType { get; set; }
        [XmlAttribute(AttributeName = "creationDateTime")]
        public string CreationDateTime { get; set; }
    }

    [XmlRoot(ElementName = "partyIdentification")]
    public class PartyIdentification
    {
        [XmlElement(ElementName = "gln")]
        public string Gln { get; set; }
    }

    [XmlRoot(ElementName = "settlementEntity")]
    public class SettlementEntity
    {
        [XmlElement(ElementName = "partyIdentification")]
        public PartyIdentification PartyIdentification { get; set; }
        [XmlAttribute(AttributeName = "entityType")]
        public string EntityType { get; set; }
    }

    [XmlRoot(ElementName = "settlementLineItem")]
    public class SettlementLineItem
    {
        [XmlElement(ElementName = "amountPaid")]
        public string AmountPaid { get; set; }
        [XmlElement(ElementName = "originalAmount")]
        public string OriginalAmount { get; set; }
        [XmlElement(ElementName = "adjustmentAndDiscount")]
        public List<AdjustmentAndDiscount> AdjustmentAndDiscount { get; set; }
        [XmlElement(ElementName = "invoice")]
        public Invoice Invoice { get; set; }
        [XmlElement(ElementName = "settlementEntity")]
        public SettlementEntity SettlementEntity { get; set; }
        [XmlAttribute(AttributeName = "number")]
        public string Number { get; set; }
    }
}

OUTPUT > See the Number attribute value

Please check and revert me back if it solves your problem or not.


问:
C# String Length returning the wrong amount
I have a string of 13 characters. 8C4B99823CB9C.
I am assigning it to a string.

```<code> string serialNumber = "8C4B99823CB9C";
</code>```

This string then enters a method

```<code>GenerateCode(proxy, serialNumber, product);
</code>```

Inside this method I have this line...

```<code>codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
</code>```

In the watch this is showing the length as 15.

Here is the full code

```<code>[TestMethod]
public void CanGenerateCodeNumberWithPrefixWithHEX()
{
    string serialNumber = "8C4B99823CB9C";
    Entity product = new Entity();
    product.Attributes["piv_codeseriallength"] = 8;
    product.Attributes["piv_codeprefix"] = "G";
    string result = GenerateCode(proxy, serialNumber, product);
    string expected = "G9823CB9C";
    Assert.AreEqual(expected, result, "The Code was not generated correctly");
}

public static string GenerateCode(IOrganizationService _service, string serial_no, Entity product)
{
    string codeSerial = null;
    //Serial Length
    if (product.Attributes.ContainsKey("piv_codeseriallength"))
    {
        codeSerial = serial_no;
        int codeSerialLength = product.GetAttributeValue<int>("piv_codeseriallength");
        codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
        string prefix = product.Attributes.ContainsKey("piv_codeprefix") ? product.GetAttributeValue<string>("piv_codeprefix") : "";
        codeSerial = prefix + codeSerial;
    }
    return codeSerial;
}
</code>```

This unit test fails because it thinks the string is 15 characters long and so taking the wrong section of the string

答: In debug you can watch serialNumber.ToArray() you will notice that there is char 8237 at the begining of string and 8236 at the end

Body:
I have a string of 13 characters. 8C4B99823CB9C.
I am assigning it to a string.

 string serialNumber = "8C4B99823CB9C";

This string then enters a method

GenerateCode(proxy, serialNumber, product);

Inside this method I have this line...

codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);

In the watch this is showing the length as 15.

Here is the full code

[TestMethod]
public void CanGenerateCodeNumberWithPrefixWithHEX()
{
    string serialNumber = "8C4B99823CB9C";
    Entity product = new Entity();
    product.Attributes["piv_codeseriallength"] = 8;
    product.Attributes["piv_codeprefix"] = "G";
    string result = GenerateCode(proxy, serialNumber, product);
    string expected = "G9823CB9C";
    Assert.AreEqual(expected, result, "The Code was not generated correctly");
}

public static string GenerateCode(IOrganizationService _service, string serial_no, Entity product)
{
    string codeSerial = null;
    //Serial Length
    if (product.Attributes.ContainsKey("piv_codeseriallength"))
    {
        codeSerial = serial_no;
        int codeSerialLength = product.GetAttributeValue<int>("piv_codeseriallength");
        codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
        string prefix = product.Attributes.ContainsKey("piv_codeprefix") ? product.GetAttributeValue<string>("piv_codeprefix") : "";
        codeSerial = prefix + codeSerial;
    }
    return codeSerial;
}

This unit test fails because it thinks the string is 15 characters long and so taking the wrong section of the string