问:
How do I do Entity Extraction in Lucene
I m trying to do Entity Extraction (more like matching) in Lucene. Here is a sample workflow:

Given some text (from a URL) AND a list people names, try to extract names of people from the text.

Note:

Names of people are not completely
  normalized. e.g. Some are Mr. X, Mrs.
  Y and some are just John Doe, X and Y.
  Other prefixes and suffixes to think
  about are Jr., Sr., Dr., I, II ...
  etc. (dont let me get started with non
  US names).

I am using Lucene MemoryIndex to create an in memory index of the text from each Url (stripping html tags) and am using StandardAnalyzer to query for the list of all names, one at a time (100k names, Is there any other way to do this? On an avg. this takes about 8 secs. on the average text I have).

A major problem is that to eliminate noise I m using a score of 0.01 as a base score and queries like "Mr. John Doe" have a significantly lower score as compared to "John Doe" if the text contains "John Doe" and in many cases miss the 0.01 threshold.

The other problem is that If I normalize all names and start removing all occurences of Dr. Mr. Mrs. etc. then I start missing good matches like "Dr. John Edward II" and end up with a lot of junk matches like "Mr. John Edward".

I understand that Lucene might not be the right tool for the job either, but so far it hasnt proved to be too bad. Any help appreciated.

答:
These projects could be useful for you:

http://nlp.stanford.edu/ner/index.shtml

http://cogcomp.cs.illinois.edu/page/software_view/4

Title: How do I do Entity Extraction in Lucene


来源: stackexchange

问:
Animation of imageView is starting from its center
I have a UIImageView. I have transformed its height in the animation block. The imageView have autolayout constraints. The initial height of the imageView is set to 0 so that I can achieve a transitionFlipToBottom effect. When the animation block runs, it transforms the height but it starts from the center not from the top.

Here is the code:

```<code>func Test(){
    self.imgFitness!.transform = CGAffineTransform(scaleX: 1, y: 0)
    self.imgTime!.transform = CGAffineTransform(scaleX: 0, y: 1)
    UIView.animate(withDuration: 0.6, animations: {
    self.imgFitness!.transform = CGAffineTransform(scaleX: 1, y: 1)
    }, completion: { (success) in
    UIView.animate(withDuration: 1, animations: {
    self.imgTime!.transform = CGAffineTransform(scaleX: 1, y: 1)}, completion: { (success) in

    })
}
</code>```

答:
All transforms occurs about the layer's anchor point, and default value is at the center.

E.g. when you do the rotate transform, it will rotate around the center. And when you scale, it will scale relative to the center.

Note that the anchor point is in unit space, e.g. between 0 and 1. The default value is (0.5, 0.5) or at the center.

So, try setting it to the top center of your image view before doing the animation:

```<code>self.imgFitness!.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a UIImageView. I have transformed its height in the animation block. The imageView have autolayout constraints. The initial height of the imageView is set to 0 so that I can achieve a transitionFlipToBottom effect. When the animation block runs, it transforms the height but it starts from the center not from the top.

Here is the code:

func Test(){
    self.imgFitness!.transform = CGAffineTransform(scaleX: 1, y: 0)
    self.imgTime!.transform = CGAffineTransform(scaleX: 0, y: 1)
    UIView.animate(withDuration: 0.6, animations: {
    self.imgFitness!.transform = CGAffineTransform(scaleX: 1, y: 1)
    }, completion: { (success) in
    UIView.animate(withDuration: 1, animations: {
    self.imgTime!.transform = CGAffineTransform(scaleX: 1, y: 1)}, completion: { (success) in

    })
}

Body:
All transforms occurs about the layer's anchor point, and default value is at the center.

E.g. when you do the rotate transform, it will rotate around the center. And when you scale, it will scale relative to the center.

Note that the anchor point is in unit space, e.g. between 0 and 1. The default value is (0.5, 0.5) or at the center.

So, try setting it to the top center of your image view before doing the animation:

self.imgFitness!.layer.anchorPoint = CGPoint(x: 0.5, y: 0)


问:
json_encode format for array
I can't find the answer to this anywhere online, partly because I wouldn't know how to search for this. The problem is the format of json_encode for the following array:

```<code>array(1) {
  [1441065600]=>
  array(4) {
    ["high"]=>
    float(1)
    ["low"]=>
    float(1)
    ["close"]=>
    float(1.28)
    ["open"]=>
    float(1.35)
  }
}
</code>```

The ouput in json_encode() is:

```<code>{"1441065600":{"high":1,"low":1,"close":1.28,"open":1.35}
</code>```

However I am looking to output as:

```<code>[
 [1441065600,1,1,1.28,1.35]
]
</code>```

Can anyone hint at the right approach to doing this?

Can't find my solution in http://php.net/manual/en/function.json-encode.php as I need to group by timestamp as a key.

答:
Your array format is not correct for the result you want to achieve.

You will have to loop over your array and create a new array where the key is part of the value.

For example

```<code>$result = [];
foreach ($array as $key => $value)
    $result[] = array_merge([$key], $value);

echo json_encode($result);
</code>```

Title: json_encode format for array

Body:
I can't find the answer to this anywhere online, partly because I wouldn't know how to search for this. The problem is the format of json_encode for the following array:

array(1) {
  [1441065600]=>
  array(4) {
    ["high"]=>
    float(1)
    ["low"]=>
    float(1)
    ["close"]=>
    float(1.28)
    ["open"]=>
    float(1.35)
  }
}

The ouput in json_encode() is:

{"1441065600":{"high":1,"low":1,"close":1.28,"open":1.35}

However I am looking to output as:

[
 [1441065600,1,1,1.28,1.35]
]

Can anyone hint at the right approach to doing this?

Can't find my solution in http://php.net/manual/en/function.json-encode.php as I need to group by timestamp as a key.

Body:
Your array format is not correct for the result you want to achieve.

You will have to loop over your array and create a new array where the key is part of the value.

For example

$result = [];
foreach ($array as $key => $value)
    $result[] = array_merge([$key], $value);

echo json_encode($result);


问:
jquery get first text element attribute from selected dropdown
both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.

```<code>$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname   + ' ' + value.name  +'</option>');
</code>```

what i would achieve is:

```<code>var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe
</code>```

so, in other hand, i would like get only first element of text in selected dropbox.

I can help me to understand how to reach my goal?

答:
In jQuery, you don't use the .text() method to get the value of a dropdown menu. You need to just have:

```<code>var testd = $("#dropDocente").val();
</code>```

and that will return the selected option's value from the dropdown.

Body:
both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.

$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname   + ' ' + value.name  +'</option>');

what i would achieve is:

var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe

so, in other hand, i would like get only first element of text in selected dropbox.

I can help me to understand how to reach my goal?

Body:
In jQuery, you don't use the .text() method to get the value of a dropdown menu. You need to just have:

var testd = $("#dropDocente").val();

and that will return the selected option's value from the dropdown.


问:
Ubuntu 16.04: Error return on gem install bundler
I've been getting a return,

```<code>~$ gem install bundler
ERROR:  Loading command: install (LoadError)
cannot load such file -- zlib
ERROR:  While executing gem ... (NoMethodError)
undefined method `invoke_with_build_args' for nil:NilClass
</code>```

When trying to install Jekyll via gem bundler

I've found lots of resources of others getting this error such as,

I've recompiled ruby after sudo apt-get libssl-dev as well as a few other dep/libs I could think of,

but no results. Any other ideas someone has?

Setup:
Dell 2120
Ubuntu 16.04 LTS

答:
What worked for me was following the respective issue on the official Jekyll repository in GitHub.

Performing the following steps, I got it to work:

Remove any previously installed versions:

```<code>sudo apt-get purge jekyll
sudo apt-get purge ruby
</code>```

Install ruby anew:

```<code>sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties
sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
curl -L https://get.rvm.io | bash -s stable
source ~/.rvm/scripts/rvm
echo "source ~/.rvm/scripts/rvm" >> ~/.bashrc
rvm install
rvm install 2.4.1
rvm use 2.4.1 --default
</code>```

Make sure you have, NodeJS and Python installed, if not - do so by:

```<code>sudo apt-get install node
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
</code>```

And at last,

```<code>gem install jekyll
</code>```

Result:

```<code>jekyll -v
jekyll 3.4.3
</code>```

Of course, now you could execute gem install bundler smoothly, too.

Hope this helps!

Body:
I've been getting a return,

~$ gem install bundler
ERROR:  Loading command: install (LoadError)
cannot load such file -- zlib
ERROR:  While executing gem ... (NoMethodError)
undefined method `invoke_with_build_args' for nil:NilClass

When trying to install Jekyll via gem bundler

I've found lots of resources of others getting this error such as,

I've recompiled ruby after sudo apt-get libssl-dev as well as a few other dep/libs I could think of,

but no results. Any other ideas someone has?

Setup:
Dell 2120
Ubuntu 16.04 LTS

Body:
What worked for me was following the respective issue on the official Jekyll repository in GitHub.

Performing the following steps, I got it to work:

Remove any previously installed versions:

sudo apt-get purge jekyll
sudo apt-get purge ruby

Install ruby anew:

sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties
sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
curl -L https://get.rvm.io | bash -s stable
source ~/.rvm/scripts/rvm
echo "source ~/.rvm/scripts/rvm" >> ~/.bashrc
rvm install
rvm install 2.4.1
rvm use 2.4.1 --default

Make sure you have, NodeJS and Python installed, if not - do so by:

sudo apt-get install node
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6

And at last,

gem install jekyll

Result:

jekyll -v
jekyll 3.4.3

Of course, now you could execute gem install bundler smoothly, too.

Hope this helps!


问:
How to get position of every character
How to get position (left, top) of every characters in some node? I know just one method: wrap every character in it's own tag and then we can get it's coordinate. But it's bit slowly</p>

答:
You could cache the widths of characters that you already have seen.

```<code>function findOffset(index) {
  // Set some variables early on
  var sizes          = {},
      text           = "The text you are getting an offset from.",
      lineHeight     = 16,  // You can get this dynamically if you want
      containerWidth = 500, // Same with this one
      leftOffset     = 0,
      topOffset      = 0,
      i              = 0,
      cur;

  // Loop through and count up the sizes of each character until this one
  for (; (i < text.length) && (i <= index); i++) {

    // Set the current character
    cur = text.charAt(i);

    // Check to see if we have a size
    if ( typeof size[cur] == "undefined" ) {
      // If not: Wrap it in a span (You seemed to already know how to do this)
      // then cache the result
      size[cur] = findWidthByTemporarilyWrappingInASpan(text, i);
    }

    // If it's greater than a line can hold, we'll wrap
    if ( (sizes[cur] + leftOffset) > containerWidth ) {

      // Reset the left offset
      leftOffset = 0;

      // Increment the top offset
      topOffset += lineHeight;
    }
    // Otherwise, increment from the left
    else {
      leftOffset += sizes[cur];
    }
  }

  // return an object with the coordinates
  return {
    leftOffset: leftOffset,
    topOffset : topOffset
  };
}
</code>```

Then you can even memoize each index that you go grab and start from a close by one the next time you call this function. This means you stay off the dom except for usually not too much more than ~50 (alphanumeric + punctuation, etc) times, rather than for each character.

This would certainly work for monospaced fonts, but I think there is some merit to it for other types. You'd just have to do the wrapping research for different browsers.

Also, note that this assumes left-justification, etc. It's more of an idea than an actual code solution.

ContentLicense: CC BY-SA 2.5

Title: How to get position of every character

Body:
You could cache the widths of characters that you already have seen.

function findOffset(index) {
  // Set some variables early on
  var sizes          = {},
      text           = "The text you are getting an offset from.",
      lineHeight     = 16,  // You can get this dynamically if you want
      containerWidth = 500, // Same with this one
      leftOffset     = 0,
      topOffset      = 0,
      i              = 0,
      cur;

  // Loop through and count up the sizes of each character until this one
  for (; (i < text.length) && (i <= index); i++) {

    // Set the current character
    cur = text.charAt(i);

    // Check to see if we have a size
    if ( typeof size[cur] == "undefined" ) {
      // If not: Wrap it in a span (You seemed to already know how to do this)
      // then cache the result
      size[cur] = findWidthByTemporarilyWrappingInASpan(text, i);
    }

    // If it's greater than a line can hold, we'll wrap
    if ( (sizes[cur] + leftOffset) > containerWidth ) {

      // Reset the left offset
      leftOffset = 0;

      // Increment the top offset
      topOffset += lineHeight;
    }
    // Otherwise, increment from the left
    else {
      leftOffset += sizes[cur];
    }
  }

  // return an object with the coordinates
  return {
    leftOffset: leftOffset,
    topOffset : topOffset
  };
}

Then you can even memoize each index that you go grab and start from a close by one the next time you call this function. This means you stay off the dom except for usually not too much more than ~50 (alphanumeric + punctuation, etc) times, rather than for each character.

This would certainly work for monospaced fonts, but I think there is some merit to it for other types. You'd just have to do the wrapping research for different browsers.

Also, note that this assumes left-justification, etc. It's more of an idea than an actual code solution.


问:
Why isn't the size of an empty list 0 bytes?
Today itself I ran the code given below in Python 2.7.13 and found that the list size isn't 0 when it is empty:

```<code>import sys
data = []
for k in range(n):
    a = len(data)
    b = sys.getsizeof(data)
    print('Length:{0:3d};Size in bytes:{1:4d}'.format(a,b))
    data.append(None)
</code>```

Output on my Machine:

```<code>Length: 0; Size in bytes : 72
Length: 1; Size in bytes : 104
Length: 2; Size in bytes : 104
Length: 3; Size in bytes : 104
Length: 4; Size in bytes : 104
Length: 5; Size in bytes : 136
Length: 6; Size in bytes : 136
Length: 7; Size in bytes : 136
Length: 8; Size in bytes : 136
Length: 9; Size in bytes : 200
Length: 10; Size in bytes : 200
Length: 11; Size in bytes : 200
Length: 12; Size in bytes : 200
Length: 13; Size in bytes : 200
Length: 14; Size in bytes : 200
Length: 15; Size in bytes : 200
Length: 16; Size in bytes : 200
Length: 17; Size in bytes : 272
Length: 18; Size in bytes : 272
Length: 19; Size in bytes : 272
</code>```

I want to know why is this happening?

It seems that Python is reserving memory for something.
  What is that something??

答:
Python is implemented in C, and as such will be storing data in a C struct.

Remember that all things are 'objects' - objects must have a type and an object size, even if they don't store anything.

Below are the PyObject_VAR_HEAD and PyListObject C datatypes.

#define PyObject_VAR_HEAD               \
    PyObject_HEAD                       \
    Py_ssize_t ob_size; /* Number of items in variable part */

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;
```

Remember that sys.getsizeof() will return the underlying memory usage, not something that you really need to consider or worry about from Python:

Return the size of an object in bytes.

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

Additionally, as your test shows, there is an amount of pre-allocation going on. New memory is not associated with the list on every call to append().

ContentLicense: CC BY-SA 4.0

Body:
Today itself I ran the code given below in Python 2.7.13 and found that the list size isn't 0 when it is empty:

import sys
data = []
for k in range(n):
    a = len(data)
    b = sys.getsizeof(data)
    print('Length:{0:3d};Size in bytes:{1:4d}'.format(a,b))
    data.append(None)

Output on my Machine:

Length: 0; Size in bytes : 72
Length: 1; Size in bytes : 104
Length: 2; Size in bytes : 104
Length: 3; Size in bytes : 104
Length: 4; Size in bytes : 104
Length: 5; Size in bytes : 136
Length: 6; Size in bytes : 136
Length: 7; Size in bytes : 136
Length: 8; Size in bytes : 136
Length: 9; Size in bytes : 200
Length: 10; Size in bytes : 200
Length: 11; Size in bytes : 200
Length: 12; Size in bytes : 200
Length: 13; Size in bytes : 200
Length: 14; Size in bytes : 200
Length: 15; Size in bytes : 200
Length: 16; Size in bytes : 200
Length: 17; Size in bytes : 272
Length: 18; Size in bytes : 272
Length: 19; Size in bytes : 272

I want to know why is this happening?

It seems that Python is reserving memory for something.
  What is that something??

Body:
Python is implemented in C, and as such will be storing data in a C struct.

Remember that all things are 'objects' - objects must have a type and an object size, even if they don't store anything.

Below are the PyObject_VAR_HEAD and PyListObject C datatypes.

#define PyObject_VAR_HEAD               \
    PyObject_HEAD                       \
    Py_ssize_t ob_size; /* Number of items in variable part */

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;

Remember that sys.getsizeof() will return the underlying memory usage, not something that you really need to consider or worry about from Python:

Return the size of an object in bytes.

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

Additionally, as your test shows, there is an amount of pre-allocation going on. New memory is not associated with the list on every call to append().


问:
Excel pivot condition cell
how can i set condition inside pivot sum data to refer label row ?

I need to sum data only if row label is equal to specific value.

I'm trying to use standard IF but it doesn't work.

Thanks.

答:
Use a vlookup ( within a vlookup.? Others please say if that is necc).  copy paste your row tabels in another column in another sheet/tab and look for them im ur pivot.

Vlookup(a1,sheet2(column),1,0).

Altetnatively u culd just copy paste text only the pivot table results, and use ur if statement there.

But vlookups are superior if statements. So us that is more dynamic/poweful.

Title: Excel pivot condition cell


问:
jQuery getJSON function not returning anything
I have this code:

```<code>$.getJSON('data.json', function (data) {
    console.log(data);
});
</code>```

And this is the data.json file:

```<code>{
  "Sameer": {
    "Phone": "0123456789",
  },
  "Mona": {
    "Phone": "0123456789",
  },
}
</code>```

But the console.log(data) not returning anything, Not even an error I don't know what is wrong with my code.

I tried to use $.ajax() function instead but no luck. And when I change my data.json file to something random like: data.asd I get an error that saying the file data.asd not found!

答:
Your json has problem with , as @Taki mentioned above. I stored your corrected json at below url and there is no problem with the getJSON api. I am able to output json in console.Try running below code snippet.

$.getJSON('https://api.myjson.com/bins/qnucf', function (data) {
    console.log(data);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have this code:

$.getJSON('data.json', function (data) {
    console.log(data);
});

And this is the data.json file:

{
  "Sameer": {
    "Phone": "0123456789",
  },
  "Mona": {
    "Phone": "0123456789",
  },
}

But the console.log(data) not returning anything, Not even an error I don't know what is wrong with my code.

I tried to use $.ajax() function instead but no luck. And when I change my data.json file to something random like: data.asd I get an error that saying the file data.asd not found!

Body:
Your json has problem with , as @Taki mentioned above. I stored your corrected json at below url and there is no problem with the getJSON api. I am able to output json in console.Try running below code snippet.

$.getJSON('https://api.myjson.com/bins/qnucf', function (data) {
    console.log(data);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
python wrap text and reportlab
I have a little code and I would like to wrap my long string in every 10th character and then add it into a PDF using reportlab:

This is how I try:

```<code>text = '*long_text_long_text_long_text_long_text*'
text = "\n".join(wrap(text, 10))
canvas.drawString(5,227, text)
</code>```

My pdf was created but where I want to break the lines I can only see black rectangles. You can see the attached picture:

Can you help me? Thank you!

答:
drawString draws a single line. so you will need to adjust the coordinate for each line in a loop.</p>

```<code>y = 227
for line in wrap(text, 10):
    canvas.drawString(5, y, line)
    y += 15
</code>```

Title: python wrap text and reportlab

Body:
I have a little code and I would like to wrap my long string in every 10th character and then add it into a PDF using reportlab:

This is how I try:

text = '*long_text_long_text_long_text_long_text*'
text = "\n".join(wrap(text, 10))
canvas.drawString(5,227, text)

My pdf was created but where I want to break the lines I can only see black rectangles. You can see the attached picture:

Can you help me? Thank you!

Body:
drawString draws a single line. so you will need to adjust the coordinate for each line in a loop.

y = 227
for line in wrap(text, 10):
    canvas.drawString(5, y, line)
    y += 15


问:
quirks using maven eclipse plugin with WTP
I'm using the maven eclipse plugin to generate wtp projects. It mostly works, but there are some strange quirks that I'd like to get rid of:

I must specify -Dwtpversion=2.0 each time I run mvn eclipse:eclipse. Otherwise, facet information is not generated.

The java facet level is set to version 1.4 instead of 6.0, which causes each generated project to have an error Java compiler level does not match the version of the installed Java project facet

How do I get rid of these quirks?

Below is my top-level pom.xml.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.foo</groupId>
  <artifactId>foo</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>foo</name>
  <url>http://maven.apache.org</url>
  <modules>
    <module>module1</module>
    <module>module2</module>
  </modules>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.8</version>
        <configuration>
          <wtpversion>2.0</wtpversion>
          <additionalProjectFacets>
            <jst.web>3.0</jst.web>
          </additionalProjectFacets>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

答:
You do something wrong. You can use maven-eclipse-plugin (which is discontinued or at least not developed anymore), or use m2eclipse. Not both. Use m2eclipse, but make sure, that you installed m2eclipse extras as well. For some strange reasons these are two update sites, not only one. If you install extras successfully, and use standard web or ejb artifacts, eclipse configuration will be rendered by m2eclipse extras automatically if you use project creation wizard of m2eclipse.

UPDATE:
Sorry, maven eclipse plugin is still alive. Took a look at Issue tracking system.

First

For the first sight, I have no clue. The source code tells, that it is a simple mojo parameter (that can come from configuration tag). The only thing you can consider is, that configuration is shared inside a POM (according to my experience). So if you use a plugin at the top of the POM, and you use at the bottom as well, the configuration is shared (or the same), which is probably some summary of the two (should be checked in source). So wtpversion may happen to be defined somewhere else inside your POM, or in the parent POMs. This definition can be overridden by only an environment entry. Quotes from Maven documentation:

Specifies the expressions used to
  calculate the value to be injected
  into this parameter of the Mojo at
  buildtime. The expression given by
  default-value is commonly used to
  refer to specific elements in the POM,
  such as ${project.resources}, which
  refers to the list of resources meant
  to accompany the classes in the
  resulting JAR file. Of course, the
  default value need not be an
  expression but can also be a simple
  constant like true or 1.5. And for
  parameters of type String one can mix
  expressions with literal values, e.g.
  ${project.artifactId}-${project.version}-special.
  The system property given by
  expression enables users to override
  the default value from the command
  line via -DaSystemProperty=value.
  NOTE: If neither default-value nor
  expression are specified, the
  parameter can only be configured from
  the POM. The use of '${' and '}' is
  required to delimit actual expressions
  which may be evaluated.

...

The elements in the parent POM that
  are inherited by its children are:

dependencies

developers and contributors

plugin lists

reports lists

plugin executions with matching ids

plugin configuration

Second

For the second I think you should state jst.java facet version in additionalfacets. Like this: in this POM:

```<code><additionalProjectFacets>
    <jst.java>5.0</jst.java>
    <jst.ejb>3.0</jst.ejb>
    <jpt.jpa>1.0</jpt.jpa>
</additionalProjectFacets>
</code>```

Suggestion

M2eclipse has its own problems. On the other hand there is no need to hack your POM just because of Eclipse. So until it fits Your need, You should use m2ecipse + extras instead of maven eclipse plugin.

Body:
I'm using the maven eclipse plugin to generate wtp projects. It mostly works, but there are some strange quirks that I'd like to get rid of:

I must specify -Dwtpversion=2.0 each time I run mvn eclipse:eclipse. Otherwise, facet information is not generated.

The java facet level is set to version 1.4 instead of 6.0, which causes each generated project to have an error Java compiler level does not match the version of the installed Java project facet

How do I get rid of these quirks?

Below is my top-level pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.foo</groupId>
  <artifactId>foo</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>foo</name>
  <url>http://maven.apache.org</url>
  <modules>
    <module>module1</module>
    <module>module2</module>
  </modules>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.8</version>
        <configuration>
          <wtpversion>2.0</wtpversion>
          <additionalProjectFacets>
            <jst.web>3.0</jst.web>
          </additionalProjectFacets>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Body:
You do something wrong. You can use maven-eclipse-plugin (which is discontinued or at least not developed anymore), or use m2eclipse. Not both. Use m2eclipse, but make sure, that you installed m2eclipse extras as well. For some strange reasons these are two update sites, not only one. If you install extras successfully, and use standard web or ejb artifacts, eclipse configuration will be rendered by m2eclipse extras automatically if you use project creation wizard of m2eclipse.

UPDATE:
Sorry, maven eclipse plugin is still alive. Took a look at Issue tracking system.

First

For the first sight, I have no clue. The source code tells, that it is a simple mojo parameter (that can come from configuration tag). The only thing you can consider is, that configuration is shared inside a POM (according to my experience). So if you use a plugin at the top of the POM, and you use at the bottom as well, the configuration is shared (or the same), which is probably some summary of the two (should be checked in source). So wtpversion may happen to be defined somewhere else inside your POM, or in the parent POMs. This definition can be overridden by only an environment entry. Quotes from Maven documentation:

Specifies the expressions used to
  calculate the value to be injected
  into this parameter of the Mojo at
  buildtime. The expression given by
  default-value is commonly used to
  refer to specific elements in the POM,
  such as ${project.resources}, which
  refers to the list of resources meant
  to accompany the classes in the
  resulting JAR file. Of course, the
  default value need not be an
  expression but can also be a simple
  constant like true or 1.5. And for
  parameters of type String one can mix
  expressions with literal values, e.g.
  ${project.artifactId}-${project.version}-special.
  The system property given by
  expression enables users to override
  the default value from the command
  line via -DaSystemProperty=value.
  NOTE: If neither default-value nor
  expression are specified, the
  parameter can only be configured from
  the POM. The use of '${' and '}' is
  required to delimit actual expressions
  which may be evaluated.

...

The elements in the parent POM that
  are inherited by its children are:

dependencies

developers and contributors

plugin lists

reports lists

plugin executions with matching ids

plugin configuration

Second

For the second I think you should state jst.java facet version in additionalfacets. Like this: in this POM:

<additionalProjectFacets>
    <jst.java>5.0</jst.java>
    <jst.ejb>3.0</jst.ejb>
    <jpt.jpa>1.0</jpt.jpa>
</additionalProjectFacets>

Suggestion

M2eclipse has its own problems. On the other hand there is no need to hack your POM just because of Eclipse. So until it fits Your need, You should use m2ecipse + extras instead of maven eclipse plugin.


问:
How to clear picker if It is selected in xamarin forms?
I have two picker. second picker is dependent on first picker. Both pickers are bind from Service. I am using dictionary object to bind data to picker. I am not using MVVM pattern.

First service call where dictionary object for first picker is bind.

then fill first picker from that dictionary object. At that time Second picker is empty.

On selectedIndexChange event of first picker call service to bind dictionary object of second picker.

Now Fill values to second picker from dictionary object. (If already picker has data then put Picker.Items.clear())

Now If I select some value from second picker and change value of first picker then It gives me error at Picker.Items.clear()

System.ArgumentOutOfRangeException: Index was out of range. Must be
  non-negative and less than the size of the collection.

Parameter name: index

Global Declaration :

```<code>Dictionary<string, string> DicObjActivityType;

Dictionary<string, string> DicObjSelfActivity;
</code>```

First Picker selectedIndexChange event

```<code>private async void PckrActivityType_SelectedIndexChanged(object sender, EventArgs e)
{
    if (sender as Picker == null)
        return;
    else
    {
        var objActivityType = sender as Picker;
        var Key = DicObjActivityType.FirstOrDefault(x => x.Value == objActivityType.Items[objActivityType.SelectedIndex]).Key;
        PickedActivityType = Key;
        if (Key != "0")
        {
            PckrSelfActivity.IsEnabled = true;
            await CallGetWebService_SelfActivity(Key);
            if (PckrSelfActivity.IsEnabled == true)
            {
                PckrSelfActivity.Items.Clear();
                foreach (string items in DicObjSelfActivity.Values)
                {
                    PckrSelfActivity.Items.Add(items);
                }
            }
        }
        else
        {
            PckrSelfActivity.IsEnabled = false;
        }
    }
}
</code>```

Call Service of second picker

```<code>private async Task CallGetWebService_SelfActivity(string strkey)
{
    try
    {
        var response = await GetResponseFromWebService.GetResponse<ServiceClasses.RootObject_LstListComboData>(ServiceURL.GetSelfActivity + "ActivityTypeCd=" + strkey);

        if (response.Flag == true)
        {
            DicObjSelfActivity = new Dictionary<string, string>();
            DicObjSelfActivity.Add("0", "--Select--");
            if (response.lstListComboData != null)
            {
                foreach (ServiceClasses.LstListComboData Items in response.lstListComboData)
                {
                    DicObjSelfActivity.Add(Items.Value, Items.Text);
                }
            }
        }
        else
        {
            PckrSelfActivity.IsEnabled = false;
        }
    }
    catch (Exception e)
    {
        await DisplayAlert(AppResources.LError, AppResources.LConnectionError, "OK");
    }
}
</code>```

I refer following link to solve this issue

https://forums.xamarin.com/discussion/55922/picker-clear-system-argumentoutofrangeexception

but didn't find solution.

We can't clear picker if any of the value is selected?

I don't want to use BindablePicker cutom control.

答:
Actually i do the following and it is working fine for me:</p>

```<code>//step 1: re-select index to -1
YourPicker.SelectedIndex = -1;
//step 2: clear all items
YourPicker.Items.Clear();
//refill the picker
foreach (var item in subAccountStatus)
{
    YourPicker.Items.Add(item.AccountStatus);
}
//re-selected index to first item
YourPicker.SelectedIndex = 0;
</code>```

Body:
I have two picker. second picker is dependent on first picker. Both pickers are bind from Service. I am using dictionary object to bind data to picker. I am not using MVVM pattern.

First service call where dictionary object for first picker is bind.

then fill first picker from that dictionary object. At that time Second picker is empty.

On selectedIndexChange event of first picker call service to bind dictionary object of second picker.

Now Fill values to second picker from dictionary object. (If already picker has data then put Picker.Items.clear())

Now If I select some value from second picker and change value of first picker then It gives me error at Picker.Items.clear()

System.ArgumentOutOfRangeException: Index was out of range. Must be
  non-negative and less than the size of the collection.

Parameter name: index

Global Declaration :

Dictionary<string, string> DicObjActivityType;

Dictionary<string, string> DicObjSelfActivity;

First Picker selectedIndexChange event

private async void PckrActivityType_SelectedIndexChanged(object sender, EventArgs e)
{
    if (sender as Picker == null)
        return;
    else
    {
        var objActivityType = sender as Picker;
        var Key = DicObjActivityType.FirstOrDefault(x => x.Value == objActivityType.Items[objActivityType.SelectedIndex]).Key;
        PickedActivityType = Key;
        if (Key != "0")
        {
            PckrSelfActivity.IsEnabled = true;
            await CallGetWebService_SelfActivity(Key);
            if (PckrSelfActivity.IsEnabled == true)
            {
                PckrSelfActivity.Items.Clear();
                foreach (string items in DicObjSelfActivity.Values)
                {
                    PckrSelfActivity.Items.Add(items);
                }
            }
        }
        else
        {
            PckrSelfActivity.IsEnabled = false;
        }
    }
}

Call Service of second picker

private async Task CallGetWebService_SelfActivity(string strkey)
{
    try
    {
        var response = await GetResponseFromWebService.GetResponse<ServiceClasses.RootObject_LstListComboData>(ServiceURL.GetSelfActivity + "ActivityTypeCd=" + strkey);

        if (response.Flag == true)
        {
            DicObjSelfActivity = new Dictionary<string, string>();
            DicObjSelfActivity.Add("0", "--Select--");
            if (response.lstListComboData != null)
            {
                foreach (ServiceClasses.LstListComboData Items in response.lstListComboData)
                {
                    DicObjSelfActivity.Add(Items.Value, Items.Text);
                }
            }
        }
        else
        {
            PckrSelfActivity.IsEnabled = false;
        }
    }
    catch (Exception e)
    {
        await DisplayAlert(AppResources.LError, AppResources.LConnectionError, "OK");
    }
}

I refer following link to solve this issue

https://forums.xamarin.com/discussion/55922/picker-clear-system-argumentoutofrangeexception

but didn't find solution.

We can't clear picker if any of the value is selected?

I don't want to use BindablePicker cutom control.

Body:
Actually i do the following and it is working fine for me:

//step 1: re-select index to -1
YourPicker.SelectedIndex = -1;
//step 2: clear all items
YourPicker.Items.Clear();
//refill the picker
foreach (var item in subAccountStatus)
{
    YourPicker.Items.Add(item.AccountStatus);
}
//re-selected index to first item
YourPicker.SelectedIndex = 0;


问:
Acces values inside a Future[Option[T]]
I have a class

```<code>case class SomeClass(name: String, number: Long)
</code>```

And I save it in the database. When I want to recover it from the database I get is as

Future[Option[SomeClass]]

How can I access the parameters from inside this class?

答:
Without any more context, and if you don't want to wait on the future, you can just map it:

```<code>responseFromDatabase.map(_.map(_.name))
</code>```

to have Future[Option[String]] that may contain the name.

If you really want to get the value, you can also

```<code>Await.result(responseFromDatabase).map(_.name).get
</code>```

(or getOrElse with a default Name or something).

Can you provide more context?

Title: Acces values inside a Future[Option[T]]

Body:
I have a class

case class SomeClass(name: String, number: Long)

And I save it in the database. When I want to recover it from the database I get is as

Future[Option[SomeClass]]

How can I access the parameters from inside this class?

Body:
Without any more context, and if you don't want to wait on the future, you can just map it:

responseFromDatabase.map(_.map(_.name))

to have Future[Option[String]] that may contain the name.

If you really want to get the value, you can also

Await.result(responseFromDatabase).map(_.name).get

(or getOrElse with a default Name or something).

Can you provide more context?


问:
All occurrences of temporal and spatial locality of reference in a given code snippet
I have read about spatial and temporal localities.

In a couple of words.

Temporal locality:
Programs often access the same memory locations repeatedly.

Spatial locality:
Programs also often access adjacent memory locations repeatedly.

Now I'm tying to analyse the following code to find all the occurrences of temporal and spatial locality of reference.

```<code>for (int i = 0, j = 10; i < 100; i++)
    a[i] = j++;
</code>```

I figured out only the followings.

Spatial

a[i] = j++; After referencing a[i] we are about to reference a[i+1].

The instructions to do all this are stored in next to each other in memory.

Temporal

i compared against 100.

i incremented by the one: i++.

The assignment a[i] = j++ uses i as array index.

Array base a used for indexing each a[i].

j incremented by the one in assignment a[i] = j++.

So am I correct in all of these and did I miss something else?

答:
Definitions are the other way around.

Spatial locality - locality in space, accessing nearby memory locations.

Temporal locality - locality in time, accessing the same location several times.

The use of spatial locality in designing caches is such that, when your program needs a[i], cache just doesn't fetch a[i] from memory. It fetches few entries a[i], a[i+1], a[i+2] ... as much as the size of a cacheline. By doing so, cache expect you are likely to access a[i+1] soon. And when you do so, cache does not need to fetch it from memory, its already there thanks to the use of spatial locality.

Temporal locality comes when you access i and j. Every time you need i and j, no need to fetch it from memory, as it is cached. By caching, i and j, cache thought you are gonna access it again, so saves time to fetch it from memory.

And to answer the exact point, yes you have identified places for spatial and temporal locality. Only thing that is not correct is, your statement, "The instructions to do all this are stored in next to each other in memory". There wont be separate instructions to access a[i], a[i+1]. It will be a single instruction used inside a loop, using memory address calculated each time. As I explained above, the advantage is that the cache does not need to fetch the data for the next iteration as it is likely to fetched as part of an early iteration in the loop.

Body:
I have read about spatial and temporal localities.

In a couple of words.

Temporal locality:
Programs often access the same memory locations repeatedly.

Spatial locality:
Programs also often access adjacent memory locations repeatedly.

Now I'm tying to analyse the following code to find all the occurrences of temporal and spatial locality of reference.

for (int i = 0, j = 10; i < 100; i++)
    a[i] = j++;

I figured out only the followings.

Spatial

a[i] = j++; After referencing a[i] we are about to reference a[i+1].

The instructions to do all this are stored in next to each other in memory.

Temporal

i compared against 100.

i incremented by the one: i++.

The assignment a[i] = j++ uses i as array index.

Array base a used for indexing each a[i].

j incremented by the one in assignment a[i] = j++.

So am I correct in all of these and did I miss something else?


问:
Check for changes to a SQL Server database?
is there a way to get database checksum using system SQL Server functions?

Or other way to quickly figure out if there are any changes in database?

I do not want to use any specific database analysis software for this.

I look for any changes in database (schema/object changes, data changes).

I use SQL Server 2008.

答:
One approach to record/log schema changes is to use DDL triggers as of SQL Server 2005.

You can set them up on a database to fire on specific types of schema changes (e.g. CREATE_PROCEDURE, ALTER_PROCEDURE) and then maintain whatever log you want to.


问:
XQuery Nested Query
I can't figure out how to execute this query:

Using XQuery,
For each rep number, output:

A. firstname, lastname of the rep.

B. customer name for each customer associated with the rep.

C.total amount of money (excluding tax) billed for all customers associated with the rep.

Premiere Database schema:

-A Customer structure has attributes CustomerNumber, RepNum (assigned rep), etc.

-A Rep structure has attributes RepNum, etc.

-An Orders structure has attributes CustomerNumber, OrderNum, etc.

-An OrderLine structure has attributes OrderNum, NumOrdered, QuotedPrice(per -item), etc.

*Multiple order lines can have the same order number.

Sample desired output:

Q4 Output:

```<code><results>
  <rep repnum="20" firstname="Valerie" lastname="Kaiser">
    <customer name="Al's Appliance and Sport"/>
    <customer name="Kline's"/>
    <customer name="All Season"/>
    <Revenue total="$736.45"/>
  </rep>
  <rep repnum="35" firstname="Richard" lastname="Hull">
    <customer name="Brookings Direct"/>
    <customer name="The Everything Shop"/>
    <customer name="Lee's Sport and Appliance"/>
    <customer name="Deerfield's Four Seasons"/>
    <Revenue total="$2,509.80"/>
  </rep>
  <rep repnum="65" firstname="Juan" lastname="Perez">
    <customer name="Ferguson's"/>
    <customer name="Bargains Galore"/>
    <customer name="Johnson's Department Store"/>
    <Revenue total="$5,664.89"/>
  </rep>
</results>
</code>```

The output I'm getting:

```<code><results>
  <rep>
    <rep repnum="20" firstname="Valerie" lastname="Kaiser"/>
    <customer name="Al's Appliance and Sport"/>
    <customer name="Kline's"/>
    <customer name="All Season"/>
    <Revenue total="0"/>
  </rep>
  <rep>
    <rep repnum="35" firstname="Richard" lastname="Hull"/>
    <customer name="Brookings Direct"/>
    <customer name="The Everything Shop"/>
    <customer name="Lee's Sport and Appliance"/>
    <customer name="Deerfield's Four Seasons"/>
    <Revenue total="0"/>
  </rep>
  <rep>
    <rep repnum="65" firstname="Juan" lastname="Perez"/>
    <customer name="Ferguson's"/>
    <customer name="Bargains Galore"/>
    <customer name="Johnson's Department Store"/>
    <Revenue total="0"/>
  </rep>
</results>
</code>```

Revenue per rep is 0!

My code:

```<code><results>
  {
    for $r in doc("../premiere/Rep.xml")//Rep
    let $c := doc("../premiere/Customer.xml")//Customer[RepNum = $r/RepNum]

    return
      <rep>
        <rep repnum = "{$r/RepNum}" firstname="{$r/FirstName}" lastname="{$r/LastName}"/>

        {for $customer in $c
        return
           <customer name= "{ $customer/CustomerName}"/>}

        <Revenue total=  "{sum(
             for $customer in $c
             let $o := doc("../premiere/Orders.xml")//Orders[CustomerNumber = $customer/CustomerNumber]
             let $customerAmount := sum(
                 for $order in $o
                 let $l := doc("../premiere/OrderLine.xml")//OrderLine[OrderNum = $order/OrderNum]
                 let $orderAmount := format-number(sum(
                     for $lineItem in $l
                     let $LineAmount := (data($lineItem/NumOrdered) * data($lineItem/QuotedPrice))
                     return
                       $LineAmount
                 ), '$,000.00')
                 return
                   $orderAmount
             )
             return
               $customerAmount
         )}"
         />
      </rep>

  }
</results>
</code>```

Thanks in advance!

答:
First, as @joewiz pointed out, you format the partial sums into strings before you sum them up, which should definitely raise an error if executed. Since it does not, I would suspect that the outer sum never adds up any values.

You did not provide any example data, but I found this SQL file for a Premiere data set that seems to match yours. One important difference is that CUSTOMER has an attribute CUSTOMER_NUM, not CUSTOMER_NUMBER like in your description. If the element is also called CustomerNum instead of CustomerNumber in your data set, then let $o := doc("../premiere/Orders.xml")//Orders[CustomerNumber = $customer/CustomerNumber] will silently be evaluated to the empty sequence and the sum is 0.

Here is a version of your query that works for me and produces the exact output you wanted when evaluated on the values from the SQL file:

```<code><results>{
  for $r in doc("../premiere/Rep.xml")//Rep
  let $c := doc("../premiere/Customer.xml")//Customer[RepNum = $r/RepNum]
  return <rep>{
      <rep repnum = "{$r/RepNum}" firstname="{$r/FirstName}" lastname="{$r/LastName}"/>,

      for $customer in $c
      return <customer name="{$customer/CustomerName}"/>,

      let $total :=
        sum(
          for $customer in $c
          for $order in doc("../premiere/Orders.xml")//Orders[CustomerNum = $customer/CustomerNumber]
          for $lineItem in doc("../premiere/OrderLine.xml")//OrderLine[OrderNum = $order/OrderNum]
          return $lineItem/NumOrdered * $lineItem/QuotedPrice
        )
      return <Revenue total="{format-number($total, '$,000.00')}"/>
  }</rep>
}</results>
</code>```

I have simplified it by merging the two sums into one and inlining a few variables, and I moved the number formatting out to the correct spot.

Title: XQuery Nested Query

Body:
I can't figure out how to execute this query:

Using XQuery,
For each rep number, output:

A. firstname, lastname of the rep.

B. customer name for each customer associated with the rep.

C.total amount of money (excluding tax) billed for all customers associated with the rep.

Premiere Database schema:

-A Customer structure has attributes CustomerNumber, RepNum (assigned rep), etc.

-A Rep structure has attributes RepNum, etc.

-An Orders structure has attributes CustomerNumber, OrderNum, etc.

-An OrderLine structure has attributes OrderNum, NumOrdered, QuotedPrice(per -item), etc.

*Multiple order lines can have the same order number.

Sample desired output:

Q4 Output:

<results>
  <rep repnum="20" firstname="Valerie" lastname="Kaiser">
    <customer name="Al's Appliance and Sport"/>
    <customer name="Kline's"/>
    <customer name="All Season"/>
    <Revenue total="$736.45"/>
  </rep>
  <rep repnum="35" firstname="Richard" lastname="Hull">
    <customer name="Brookings Direct"/>
    <customer name="The Everything Shop"/>
    <customer name="Lee's Sport and Appliance"/>
    <customer name="Deerfield's Four Seasons"/>
    <Revenue total="$2,509.80"/>
  </rep>
  <rep repnum="65" firstname="Juan" lastname="Perez">
    <customer name="Ferguson's"/>
    <customer name="Bargains Galore"/>
    <customer name="Johnson's Department Store"/>
    <Revenue total="$5,664.89"/>
  </rep>
</results>

The output I'm getting:

<results>
  <rep>
    <rep repnum="20" firstname="Valerie" lastname="Kaiser"/>
    <customer name="Al's Appliance and Sport"/>
    <customer name="Kline's"/>
    <customer name="All Season"/>
    <Revenue total="0"/>
  </rep>
  <rep>
    <rep repnum="35" firstname="Richard" lastname="Hull"/>
    <customer name="Brookings Direct"/>
    <customer name="The Everything Shop"/>
    <customer name="Lee's Sport and Appliance"/>
    <customer name="Deerfield's Four Seasons"/>
    <Revenue total="0"/>
  </rep>
  <rep>
    <rep repnum="65" firstname="Juan" lastname="Perez"/>
    <customer name="Ferguson's"/>
    <customer name="Bargains Galore"/>
    <customer name="Johnson's Department Store"/>
    <Revenue total="0"/>
  </rep>
</results>

Revenue per rep is 0!

My code:

<results>
  {
    for $r in doc("../premiere/Rep.xml")//Rep
    let $c := doc("../premiere/Customer.xml")//Customer[RepNum = $r/RepNum]

    return
      <rep>
        <rep repnum = "{$r/RepNum}" firstname="{$r/FirstName}" lastname="{$r/LastName}"/>

        {for $customer in $c
        return
           <customer name= "{ $customer/CustomerName}"/>}

        <Revenue total=  "{sum(
             for $customer in $c
             let $o := doc("../premiere/Orders.xml")//Orders[CustomerNumber = $customer/CustomerNumber]
             let $customerAmount := sum(
                 for $order in $o
                 let $l := doc("../premiere/OrderLine.xml")//OrderLine[OrderNum = $order/OrderNum]
                 let $orderAmount := format-number(sum(
                     for $lineItem in $l
                     let $LineAmount := (data($lineItem/NumOrdered) * data($lineItem/QuotedPrice))
                     return
                       $LineAmount
                 ), '$,000.00')
                 return
                   $orderAmount
             )
             return
               $customerAmount
         )}"
         />
      </rep>

  }
</results>

Thanks in advance!

Body:
First, as @joewiz pointed out, you format the partial sums into strings before you sum them up, which should definitely raise an error if executed. Since it does not, I would suspect that the outer sum never adds up any values.

You did not provide any example data, but I found this SQL file for a Premiere data set that seems to match yours. One important difference is that CUSTOMER has an attribute CUSTOMER_NUM, not CUSTOMER_NUMBER like in your description. If the element is also called CustomerNum instead of CustomerNumber in your data set, then let $o := doc("../premiere/Orders.xml")//Orders[CustomerNumber = $customer/CustomerNumber] will silently be evaluated to the empty sequence and the sum is 0.

Here is a version of your query that works for me and produces the exact output you wanted when evaluated on the values from the SQL file:

<results>{
  for $r in doc("../premiere/Rep.xml")//Rep
  let $c := doc("../premiere/Customer.xml")//Customer[RepNum = $r/RepNum]
  return <rep>{
      <rep repnum = "{$r/RepNum}" firstname="{$r/FirstName}" lastname="{$r/LastName}"/>,

      for $customer in $c
      return <customer name="{$customer/CustomerName}"/>,

      let $total :=
        sum(
          for $customer in $c
          for $order in doc("../premiere/Orders.xml")//Orders[CustomerNum = $customer/CustomerNumber]
          for $lineItem in doc("../premiere/OrderLine.xml")//OrderLine[OrderNum = $order/OrderNum]
          return $lineItem/NumOrdered * $lineItem/QuotedPrice
        )
      return <Revenue total="{format-number($total, '$,000.00')}"/>
  }</rep>
}</results>

I have simplified it by merging the two sums into one and inlining a few variables, and I moved the number formatting out to the correct spot.


问:
Python adding text to a line
```<code>a = open('testlines.csv', 'r')
b = a.readlines()
a.close()

for c in range(0,1):
    d = '<' + b[c] + '>'
    d = b[c].replace(',', '><')
    e = re.findall(r'<(.*?)>', d, re.DOTALL)
    print(d)
    print(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])
</code>```

d does not print right, the < or > at the beginning of the line and the end of the line doesn't show up.  If I reverse the two line to create/modify d then it doesn't replace the commas.  What am I doing wrong here.  I want the replace and I need to add in the < > at the beginning and end so I do the findall and create a multidimensional array in the end once it has split everything apart.

答:
The problem is that after you assign d = '<'+b[c]+'>', you do nothing with d, but reassign a value to it. As a result the step where you add <...> is lost.

You can solve it by working on d instead of b[c], like:

```<code>for c in range(0,1):
    d = '<' + b[c] + '>'
    d = <b>d</b>.replace(',', '><') # use d instead of b[c]
    e = re.findall(r'<(.*?)>', d, re.DOTALL)
    print(d)
    print(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])</code>```

Title: Python adding text to a line

Body:
a = open('testlines.csv', 'r')
b = a.readlines()
a.close()

for c in range(0,1):
    d = '<' + b[c] + '>'
    d = b[c].replace(',', '><')
    e = re.findall(r'<(.*?)>', d, re.DOTALL)
    print(d)
    print(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])

d does not print right, the < or > at the beginning of the line and the end of the line doesn't show up.  If I reverse the two line to create/modify d then it doesn't replace the commas.  What am I doing wrong here.  I want the replace and I need to add in the < > at the beginning and end so I do the findall and create a multidimensional array in the end once it has split everything apart.

Body:
The problem is that after you assign d = '<'+b[c]+'>', you do nothing with d, but reassign a value to it. As a result the step where you add <...> is lost.

You can solve it by working on d instead of b[c], like:

for c in range(0,1):
    d = '<' + b[c] + '>'
    d = d.replace(',', '><') # use d instead of b[c]
    e = re.findall(r'<(.*?)>', d, re.DOTALL)
    print(d)
    print(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])


问:
Class 'WC_Order' not found error
I am trying to write a plugin for wordpress. When i the code is like this

But i am getting class not found error. I want to get mobile number from order id. Any help is appreciated.

Entire code of plugin

```<code><?php
/*
Plugin Name: Dorf SMS Plugin
Plugin URI: http://akismet.com/?return=true
Description: amaing sms plugin
Version: 1.0.1
Author: akshay
Author URI: http://www.yourkishore.com
License: GPLv2 or later
*/

include_once('mySettings.php');
if( is_admin() ){
    $my_settings_page = new MySettingsPage();
}

add_action( 'admin_menu', 'send_sms_options_page', $priority = 10, $accepted_args = 1 );
function send_sms_options_page(){
    add_options_page( 'Send Sms', 'Send Sms', 'manage_options', 'send_sms_slag', 'send_sms_func' );
}
function send_sms_func(){
    ?>
        <?php screen_icon(); ?> <h2>Kishore Sms Settings</h2>
        <div id="wrap" style="margin-top:30px">
        <div style="width:400px" id="jw_options">
                    <div style="width:200px;float:left">

                        <b>User name</b>   <br>
                        <b>User Mobile number</b>  <br>
                        <b>User Shipping Address</b>   <br>
                        <b>User Billing Address</b>  <br>
                        <b>User Order date</b>  <br>
                        <b>User Email</b>  <br>

                    </div>
                    <div style="width:200px;float:left">

                        [user_name] <br>
                        [user_number] <br>
                        [user_shipping] <br>
                        [user_billing] <br>
                        [user_order_date] <br>
                        [user_email] <br>
                    </div>
                </div>
                <div style="clear:both"></div>
                <br>
            Enter Order Id :<br> <input id="sa_order_id" type="text" name="" value="" placeholder=""><br><br>
            Enter Message : <br><textarea id="sa_message" style="width:300px;height:200px"></textarea><br><br>
            <button class="button button-primary" onclick="send_sms();">Send Sms</button>
        </div>
        <script type="text/javascript">
        function send_sms(){
            var sa_order_id = document.getElementById('sa_order_id').value;
            var sa_message = document.getElementById('sa_message').value;
            var hr = new XMLHttpRequest();
            var url = "http://localhost/wordpress/wp-admin/options-general.php?page=send_sms_slag";
            var vars = "sa_order_id="+sa_order_id+"&sa_message="+sa_message;
            hr.open("POST",url,true);
            hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            hr.onreadystatechange = function()
            {
                if(hr.readyState == 4 && hr.status == 200)
                {
                    var return_data = hr.responseText;
                    console.log(return_data);
                }
            }
            hr.send(vars);

        }
        </script>
    <?php
}

// Sending message after order placed

function send_confirmation_message($order_id){

    // send order completed message to user
    $order = new WC_Order( $order_id );
    // get options
    $sms_options = get_option( 'my_option_name');
    $to_send = $sms_options['sa_on_payment_success'];
    $admin_number = $sms_options['admin_mobile_number'];

    $to_find = array('[user_order_id]','[user_order_amount]','[user_name]','[user_number]','[user_order_date]','[user_email]');
    $to_replace_with = array($order->id,$order->order_total.' Rs',$order->billing_last_name,$order->billing_phone.','.$admin_number,$order->completed_date,$order->billing_email);
    $id = urlencode(str_replace($to_find, $to_replace_with, $to_send));

    $to_user_url = "http://enterprise.smsgupshup.com/GatewayAPI/rest?method=SendMessage&send_to=".$order->billing_phone."&msg=".$id."&msg_type=TEXT&userid=2012345&auth_scheme=plain&password=testing&v=1.1&format=text";
    file_get_contents($to_user_url);
}
add_action( 'woocommerce_thankyou','send_confirmation_message', $priority = 10, $accepted_args = 1 );

// Sending message on order status completed

function sa_order_status_completed($order_id){

    // send order completed message to user
    $order = new WC_Order( $order_id );
    // get options
    $sms_options = get_option( 'my_option_name');
    $to_send = $sms_options['sa_on_order_completed'];

    $to_find = array('[user_order_id]','[user_order_amount]','[user_name]','[user_number]','[user_order_date]','[user_email]');
    $to_replace_with = array($order->id,$order->order_total.' Rs',$order->billing_last_name,$order->billing_phone,$order->completed_date,$order->billing_email);
    $id = urlencode(str_replace($to_find, $to_replace_with, $to_send));

    $to_user_url = "http://enterprise.smsgupshup.com/GatewayAPI/rest?method=SendMessage&send_to=".$order->billing_phone."&msg=".$id."&msg_type=TEXT&userid=200123456&auth_scheme=plain&password=testing&v=1.1&format=text";
    file_get_contents($to_user_url);
}
add_action( 'woocommerce_order_status_completed', 'sa_order_status_completed' );
?>
</code>```

答:
Initialize the order object inside init function. It will fix you problem.</p>

```<code>add_action('init', 'my_init', 1);
function my_init(){
    $order_id = <my oder id>
    $order = new WC_Order($order_id);
}
</code>```

Title: Class 'WC_Order' not found error

Body:
I am trying to write a plugin for wordpress. When i the code is like this

But i am getting class not found error. I want to get mobile number from order id. Any help is appreciated.

Entire code of plugin

<?php
/*
Plugin Name: Dorf SMS Plugin
Plugin URI: http://akismet.com/?return=true
Description: amaing sms plugin
Version: 1.0.1
Author: akshay
Author URI: http://www.yourkishore.com
License: GPLv2 or later
*/

include_once('mySettings.php');
if( is_admin() ){
    $my_settings_page = new MySettingsPage();
}

add_action( 'admin_menu', 'send_sms_options_page', $priority = 10, $accepted_args = 1 );
function send_sms_options_page(){
    add_options_page( 'Send Sms', 'Send Sms', 'manage_options', 'send_sms_slag', 'send_sms_func' );
}
function send_sms_func(){
    ?>
        <?php screen_icon(); ?>
Kishore Sms Settings

                        User name

                        User Mobile number

                        User Shipping Address

                        User Billing Address

                        User Order date

                        User Email

                        [user_name]

                        [user_number]

                        [user_shipping]

                        [user_billing]

                        [user_order_date]

                        [user_email]

            Enter Order Id :
 <input id="sa_order_id" type="text" name="" value="" placeholder="">

            Enter Message :
<textarea id="sa_message" style="width:300px;height:200px"></textarea>

            <button class="button button-primary" onclick="send_sms();">Send Sms</button>

    <?php
}

// Sending message after order placed

function send_confirmation_message($order_id){

    // send order completed message to user
    $order = new WC_Order( $order_id );
    // get options
    $sms_options = get_option( 'my_option_name');
    $to_send = $sms_options['sa_on_payment_success'];
    $admin_number = $sms_options['admin_mobile_number'];

    $to_find = array('[user_order_id]','[user_order_amount]','[user_name]','[user_number]','[user_order_date]','[user_email]');
    $to_replace_with = array($order->id,$order->order_total.' Rs',$order->billing_last_name,$order->billing_phone.','.$admin_number,$order->completed_date,$order->billing_email);
    $id = urlencode(str_replace($to_find, $to_replace_with, $to_send));

    $to_user_url = "http://enterprise.smsgupshup.com/GatewayAPI/rest?method=SendMessage&send_to=".$order->billing_phone."&msg=".$id."&msg_type=TEXT&userid=2012345&auth_scheme=plain&password=testing&v=1.1&format=text";
    file_get_contents($to_user_url);
}
add_action( 'woocommerce_thankyou','send_confirmation_message', $priority = 10, $accepted_args = 1 );

// Sending message on order status completed

function sa_order_status_completed($order_id){

    // send order completed message to user
    $order = new WC_Order( $order_id );
    // get options
    $sms_options = get_option( 'my_option_name');
    $to_send = $sms_options['sa_on_order_completed'];

    $to_find = array('[user_order_id]','[user_order_amount]','[user_name]','[user_number]','[user_order_date]','[user_email]');
    $to_replace_with = array($order->id,$order->order_total.' Rs',$order->billing_last_name,$order->billing_phone,$order->completed_date,$order->billing_email);
    $id = urlencode(str_replace($to_find, $to_replace_with, $to_send));

    $to_user_url = "http://enterprise.smsgupshup.com/GatewayAPI/rest?method=SendMessage&send_to=".$order->billing_phone."&msg=".$id."&msg_type=TEXT&userid=200123456&auth_scheme=plain&password=testing&v=1.1&format=text";
    file_get_contents($to_user_url);
}
add_action( 'woocommerce_order_status_completed', 'sa_order_status_completed' );
?>

Body:
Initialize the order object inside init function. It will fix you problem.

add_action('init', 'my_init', 1);
function my_init(){
    $order_id = <my oder id>
    $order = new WC_Order($order_id);
}


问:
Android Account Manager not caching the authToken
Hi I'm having issues recovering my authToken when I call

mAccountManager.blockingGetAuthToken(Auth.getAccount(), Auth.AUTH_TOKEN_TYPE, true)

I get a null string back, which lead me to look into my AbstractAccountAuthenticator class, specifically getAuth(). Here's what its doing:

```<code>public Bundle getAuthToken(AccountAuthenticatorResponse response,
        Account account, String authTokenType, Bundle options)
        throws NetworkErrorException {

    final AccountManager am = AccountManager.get(mContext);

    String authToken = am.peekAuthToken(account, authTokenType);
    String uid = am.getUserData(account, AccountManager.KEY_CALLER_UID);

    // return bundle with authToken
    if (!TextUtils.isEmpty(authToken)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        result.putString(AccountManager.KEY_CALLER_UID, uid);
        return result;
    }

    return null;
}
</code>```

The peekAuthToken is returning a null, however I am getting the correct uid from getUserData which lead me to believe I am adding the account correctly. This is how I set the authToken:

```<code>mAccountManager.addAccountExplicitly(account, accountPassword, extraData);
//The addAccount is working, and I can obtain the extraData in getAuth
mAccountManager.setAuthToken(account, Auth.AUTH_TOKEN_TYPE, authtoken);
//I assume this is where the authToken is to be cached…but I can't retrieve it…
//The token does exist at this point
</code>```

Any suggestions?

答:
This can happen if you declare your Authenticator with android:customTokens=true.

You can read more in the AbstractAccountAuthenticator docs.

Body:
Hi I'm having issues recovering my authToken when I call

mAccountManager.blockingGetAuthToken(Auth.getAccount(), Auth.AUTH_TOKEN_TYPE, true)

I get a null string back, which lead me to look into my AbstractAccountAuthenticator class, specifically getAuth(). Here's what its doing:

public Bundle getAuthToken(AccountAuthenticatorResponse response,
        Account account, String authTokenType, Bundle options)
        throws NetworkErrorException {

    final AccountManager am = AccountManager.get(mContext);

    String authToken = am.peekAuthToken(account, authTokenType);
    String uid = am.getUserData(account, AccountManager.KEY_CALLER_UID);

    // return bundle with authToken
    if (!TextUtils.isEmpty(authToken)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        result.putString(AccountManager.KEY_CALLER_UID, uid);
        return result;
    }

    return null;
}

The peekAuthToken is returning a null, however I am getting the correct uid from getUserData which lead me to believe I am adding the account correctly. This is how I set the authToken:

mAccountManager.addAccountExplicitly(account, accountPassword, extraData);
//The addAccount is working, and I can obtain the extraData in getAuth
mAccountManager.setAuthToken(account, Auth.AUTH_TOKEN_TYPE, authtoken);
//I assume this is where the authToken is to be cached…but I can't retrieve it…
//The token does exist at this point

Any suggestions?


问:
Angular Modal window
I've got my modal window in Angular JS. Could some body answer me how to add blur effect to body when I open this modal window.

```<code>vm.OpenLogin = function () {
            var data = loginWizardService.getData().then(function (response) {
                $("#loginWizard").append($compile(response.data)($scope));

                $rootScope.modalInstance = $uibModal.open({
                    templateUrl: templUrl,
                    controller: OpenLoginWizardCtrl,
                    backdrop: 'static',
                    keyboard: false
                });
            });
        };
</code>```

答:
Add a property called, backdropClass to $uibModal.open() method and give a class name

backdropClass: 'newClass'

backdropClass (Type: string) - Additional CSS class(es) to be added to a modal backdrop template.

```<code>$rootScope.modalInstance = $uibModal.open({
  templateUrl: templUrl,
  controller: OpenLoginWizardCtrl,
  backdrop: 'static',
  keyboard: false,
  backdropClass: 'newClass'
});
</code>```

Give this Css to that class,

```<code>.newClass
{
    -webkit-filter: blur(5px);
    -moz-filter: blur(5px);
    -o-filter: blur(5px);
    -ms-filter: blur(5px);
    filter: blur(5px);
    filter: url("https://gist.githubusercontent.com/amitabhaghosh197/b7865b409e835b5a43b5/raw/1a255b551091924971e7dee8935fd38a7fdf7311/blur".svg#blur);
}
</code>```

So, the above class is added as a back-drop and the CSS is for adding BLUR effet to it.

Title: Angular Modal window

Body:
I've got my modal window in Angular JS. Could some body answer me how to add blur effect to body when I open this modal window.

vm.OpenLogin = function () {
            var data = loginWizardService.getData().then(function (response) {
                $("#loginWizard").append($compile(response.data)($scope));

                $rootScope.modalInstance = $uibModal.open({
                    templateUrl: templUrl,
                    controller: OpenLoginWizardCtrl,
                    backdrop: 'static',
                    keyboard: false
                });
            });
        };

Body:
Add a property called, backdropClass to $uibModal.open() method and give a class name

backdropClass: 'newClass'

backdropClass (Type: string) - Additional CSS class(es) to be added to a modal backdrop template.

$rootScope.modalInstance = $uibModal.open({
  templateUrl: templUrl,
  controller: OpenLoginWizardCtrl,
  backdrop: 'static',
  keyboard: false,
  backdropClass: 'newClass'
});

Give this Css to that class,

.newClass
{
    -webkit-filter: blur(5px);
    -moz-filter: blur(5px);
    -o-filter: blur(5px);
    -ms-filter: blur(5px);
    filter: blur(5px);
    filter: url("https://gist.githubusercontent.com/amitabhaghosh197/b7865b409e835b5a43b5/raw/1a255b551091924971e7dee8935fd38a7fdf7311/blur".svg#blur);
}

So, the above class is added as a back-drop and the CSS is for adding BLUR effet to it.


问:
Remove URL parameters JS ES6
I have a url that contains a parameter, which I want to remove. I have created an if...else condition, but I would like to improve it in ES6.

```<code>if ( window.location.search.indexOf('&submit')  > -1 ) {
    window.location = urlBase + '/' + window.location.search;
} else {
    window.location = urlBase + '/' + window.location.search + '&submit=1';
}
</code>```

Thank you in advance.

答:
Not sure what your goal is, but here I've simply used includes and template literals.

```<code>if (window.location.search.includes('&submit')) {
    window.location = `${urlBase}/${window.location.search}`;
} else {
    window.location = `${urlBase}/${window.location.search}&submit=1`;
}
</code>```

Title: Remove URL parameters JS ES6

Body:
I have a url that contains a parameter, which I want to remove. I have created an if...else condition, but I would like to improve it in ES6.

if ( window.location.search.indexOf('&submit')  > -1 ) {
    window.location = urlBase + '/' + window.location.search;
} else {
    window.location = urlBase + '/' + window.location.search + '&submit=1';
}

Thank you in advance.

Body:
Not sure what your goal is, but here I've simply used includes and template literals.

if (window.location.search.includes('&submit')) {
    window.location = `${urlBase}/${window.location.search}`;
} else {
    window.location = `${urlBase}/${window.location.search}&submit=1`;
}


问:
iterate and retrieve nested object in JSON using rapidjson
I am parsing a JSON structure which is similar as follows

```<code>{
    "item1" : "value1"
    "item2" : "value2"
    // ...
    "itemn" : {
        "outernestedItem1" : {
            "innerNestedItem1" : "valuen1"
            "innerNestedItem2" : "valuen2"
        }
        // ....
        "outernestedItemn" : {
            "innerNestedItem1" : "valuen1"
            "innerNestedItem2" : "valuen2"
        }
    }
}
</code>```

The number of outer nested items is not fixed, so I was iterating using iterator from rapidjson, inner-nested objects variables are fixed, so I can get access to them using [].

```<code>const rapidjson::Value& itemn = document["itemn"];
for (rapidjson::Value::ConstMemberIterator itr = itemn.MemberBegin();
itr != itemn.MemberEnd(); ++itr)
{
    rapidjson::StringBuffer sb;
    rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
    itr->value.Accept(writer);

    std::cout << sb["innerNestedItem1"].GetString();
    std::cout << sb["innerNestedItem2"].GetString();
}
</code>```

but [] is not allowed with sb(string buffer), any idea how can I do this?

Edit1:
I did it in very inefficient way, but just sharing the solution, so it might help someone to come up with efficient solution.

```<code>const rapidjson::Value& itemn = document["itemn"];
for (rapidjson::Value::ConstMemberIterator itr = itemn.MemberBegin();
itr != itemn.MemberEnd(); ++itr)
{
    rapidjson::StringBuffer sb;
    rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
    itr->value.Accept(writer);

    //changed from here onwards
    rapidjson::Document for_outer_nested_item;
    std::string temp = sb.GetString();
    char buffer2[100000];
    strcpy_s(buffer2, temp.c_str());
    for_outer_nested_item.ParseInsitu(buffer2);
    std::cout << executive_command["innerNestedItem1"].GetString() << std::endl;
    std::cout << executive_command["innerNestedItem2"].GetString() << std::endl;
}
</code>```

答:
This is something I recently worked on:

```<code>void enter(const Value &obj, size_t indent = 0) { //print JSON tree

if (obj.IsObject()) { //check if object
    for (Value::ConstMemberIterator itr = obj.MemberBegin(); itr != obj.MemberEnd(); ++itr) {   //iterate through object
        const Value& objName = obj[itr->name.GetString()]; //make object value

        for (size_t i = 0; i != indent; ++i) //indent
            cout << " ";

        cout << itr->name.GetString() << ": "; //key name

        if (itr->value.IsNumber()) //if integer
            std::cout << itr->value.GetInt() ;

        else if (itr->value.IsString()) //if string
            std::cout << itr->value.GetString();

        else if (itr->value.IsBool()) //if bool
            std::cout << itr->value.GetBool();

        else if (itr->value.IsArray()){ //if array

            for (SizeType i = 0; i < itr->value.Size(); i++) {
                if (itr->value[i].IsNumber()) //if array value integer
                    std::cout << itr->value[i].GetInt() ;

                else if (itr->value[i].IsString()) //if array value string
                    std::cout << itr->value[i].GetString() ;

                else if (itr->value[i].IsBool()) //if array value bool
                    std::cout << itr->value[i].GetBool() ;

                else if (itr->value[i].IsObject()){ //if array value object
                    cout << "\n  ";
                    const Value& m = itr->value[i];
                    for (auto& v : m.GetObject()) { //iterate through array object
                        if (m[v.name.GetString()].IsString()) //if array object value is string
                            cout << v.name.GetString() << ": " <<   m[v.name.GetString()].GetString();
                        else //if array object value is integer
                            cout << v.name.GetString() << ": "  <<  m[v.name.GetString()].GetInt();

                       cout <<  "\t"; //indent
                    }
                }
                cout <<  "\t"; //indent
            }
        }

        cout << endl;
        enter(objName, indent + 1); //if couldn't find in object, enter object and repeat process recursively
        }
 }
 }
</code>```

This can handle any type of JSON tree. All you have to do is pass a Value as such:

```<code>Value v = document.GetObject();
Value& m= v;
enter(m);
</code>```

And you're done!

Body:
I am parsing a JSON structure which is similar as follows

{
    "item1" : "value1"
    "item2" : "value2"
    // ...
    "itemn" : {
        "outernestedItem1" : {
            "innerNestedItem1" : "valuen1"
            "innerNestedItem2" : "valuen2"
        }
        // ....
        "outernestedItemn" : {
            "innerNestedItem1" : "valuen1"
            "innerNestedItem2" : "valuen2"
        }
    }
}

The number of outer nested items is not fixed, so I was iterating using iterator from rapidjson, inner-nested objects variables are fixed, so I can get access to them using [].

const rapidjson::Value& itemn = document["itemn"];
for (rapidjson::Value::ConstMemberIterator itr = itemn.MemberBegin();
itr != itemn.MemberEnd(); ++itr)
{
    rapidjson::StringBuffer sb;
    rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
    itr->value.Accept(writer);

    std::cout << sb["innerNestedItem1"].GetString();
    std::cout << sb["innerNestedItem2"].GetString();
}

but [] is not allowed with sb(string buffer), any idea how can I do this?

Edit1:
I did it in very inefficient way, but just sharing the solution, so it might help someone to come up with efficient solution.

const rapidjson::Value& itemn = document["itemn"];
for (rapidjson::Value::ConstMemberIterator itr = itemn.MemberBegin();
itr != itemn.MemberEnd(); ++itr)
{
    rapidjson::StringBuffer sb;
    rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
    itr->value.Accept(writer);

    //changed from here onwards
    rapidjson::Document for_outer_nested_item;
    std::string temp = sb.GetString();
    char buffer2[100000];
    strcpy_s(buffer2, temp.c_str());
    for_outer_nested_item.ParseInsitu(buffer2);
    std::cout << executive_command["innerNestedItem1"].GetString() << std::endl;
    std::cout << executive_command["innerNestedItem2"].GetString() << std::endl;
}

Body:
This is something I recently worked on:

void enter(const Value &obj, size_t indent = 0) { //print JSON tree

if (obj.IsObject()) { //check if object
    for (Value::ConstMemberIterator itr = obj.MemberBegin(); itr != obj.MemberEnd(); ++itr) {   //iterate through object
        const Value& objName = obj[itr->name.GetString()]; //make object value

        for (size_t i = 0; i != indent; ++i) //indent
            cout << " ";

        cout << itr->name.GetString() << ": "; //key name

        if (itr->value.IsNumber()) //if integer
            std::cout << itr->value.GetInt() ;

        else if (itr->value.IsString()) //if string
            std::cout << itr->value.GetString();

        else if (itr->value.IsBool()) //if bool
            std::cout << itr->value.GetBool();

        else if (itr->value.IsArray()){ //if array

            for (SizeType i = 0; i < itr->value.Size(); i++) {
                if (itr->value[i].IsNumber()) //if array value integer
                    std::cout << itr->value[i].GetInt() ;

                else if (itr->value[i].IsString()) //if array value string
                    std::cout << itr->value[i].GetString() ;

                else if (itr->value[i].IsBool()) //if array value bool
                    std::cout << itr->value[i].GetBool() ;

                else if (itr->value[i].IsObject()){ //if array value object
                    cout << "\n  ";
                    const Value& m = itr->value[i];
                    for (auto& v : m.GetObject()) { //iterate through array object
                        if (m[v.name.GetString()].IsString()) //if array object value is string
                            cout << v.name.GetString() << ": " <<   m[v.name.GetString()].GetString();
                        else //if array object value is integer
                            cout << v.name.GetString() << ": "  <<  m[v.name.GetString()].GetInt();

                       cout <<  "\t"; //indent
                    }
                }
                cout <<  "\t"; //indent
            }
        }

        cout << endl;
        enter(objName, indent + 1); //if couldn't find in object, enter object and repeat process recursively
        }
 }
 }

This can handle any type of JSON tree. All you have to do is pass a Value as such:

Value v = document.GetObject();
Value& m= v;
enter(m);

And you're done!


问:
How to pass csharp binding variable to Javascript function
I want to pass c# binding variable to javascript function. Here is my code:

```<code><asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%#Bind(variable)%>'); "></asp:LinkButton>
</code>```

But it always generates an error : "htmlfile: Not implemented".

And the code is not intepreted onclick="passAccessory('<%#Bind(variable)%>');"

Does anyone knows how to solve it ?

Thanks.

Edit: I have changed the code to

```<code><asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%# Eval("lblTest.ClientID") %>');"></asp:LinkButton>
</code>```

And this is the code it's related to, it uses the lblTest.ClientID

<asp:Label ID="lblTest" runat="server" Text='<%#Bind("reference")%>' />

But i received an error: HttpException. Databinding ... does not contain a property with the name lblTest. Is there any wrong with my code.

Edit:  These posts gave me a clue.

http://www.west-wind.com/Weblog/posts/5364.aspx

I am trying to learn how to bind an IEnumerable LINQ collection to a repeater

Now i have want to use

```<code><asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>' OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>'></asp:LinkButton>
</code>```

答:
You don't want a two way bind, but rather an Eval.</p>

```<code><asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick='passAccessory(\"<%# Eval("variable") %>\");'></asp:LinkButton>
</code>```

Body:
I want to pass c# binding variable to javascript function. Here is my code:

<asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%#Bind(variable)%>'); "></asp:LinkButton>

But it always generates an error : "htmlfile: Not implemented".

And the code is not intepreted onclick="passAccessory('<%#Bind(variable)%>');"

Does anyone knows how to solve it ?

Thanks.

Edit: I have changed the code to

<asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%# Eval("lblTest.ClientID") %>');"></asp:LinkButton>

And this is the code it's related to, it uses the lblTest.ClientID

<asp:Label ID="lblTest" runat="server" Text='<%#Bind("reference")%>' />

But i received an error: HttpException. Databinding ... does not contain a property with the name lblTest. Is there any wrong with my code.

Edit:  These posts gave me a clue.

http://www.west-wind.com/Weblog/posts/5364.aspx

I am trying to learn how to bind an IEnumerable LINQ collection to a repeater

Now i have want to use

<asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>' OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>'></asp:LinkButton>

Body:
You don't want a two way bind, but rather an Eval.

<asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick='passAccessory(\"<%# Eval("variable") %>\");'></asp:LinkButton>


问:
Auto-Proxy services with Consul Service Discovery
I am attempting to move from Eureka to Consul for service discovery and am having an issue - my gateway service registers and my customer-service registers, but the gateway service will not route requests to the customer-service automatically.  Routes I have specifically defined in the gateway Controller that use Feign clients to route work fine, but before (with Eureka) I could make a request to any path like "/customer-service/blah" (where customer-service is the registered name) and the gateway would just forward the request on to the downstream microservice.

Here is my gateway bootstrap.yml (it's in bootstrap and not application because I am also using consul for config)

```<code>    spring:
  application:
    name: gateway-api
  cloud:
    consul:
      config:
        watch:
          wait-time: 30
      discovery:
        prefer-ip-address: true
        instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
</code>```

答:
Try this I think this help you to solve your problem..

This is my gateway bootstrap.yml file

```<code>spring:
  application:
    name: gateway-service
---

spring:
  profiles: default
  cloud:
    consul:
      config:
        prefix: config/dev/
        format: FILES
      host: localhost
      port: 8500
      discovery:
        prefer-ip-address: true
spring.profiles.active: dev
</code>```

I use this dependency for gateway and for all applications

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
</code>```

consul use as my configuration server. then I add consul to this configurations. configuration path is /config/dev/gateway.yml

```<code>zuul:
  prefix: /api
  ignoredServices: '*'
  host:
    connect-timeout-millis: 20000
    socket-timeout-millis: 20000

  routes:
    customer-service:
        path: /customer/**
        serviceId: customer-service
        stripPrefix: false
        sensitiveHeaders: Cookie,Set-Cookie
</code>```

Gateway service spring boot application annotate like below

```<code>@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class GatewayServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayServiceApplication.class, args);
    } // End main ()

}// End GatewayServiceApplication
</code>```

if you make your application like this you can use routs your prefer way.

sample consul configuration

Body:
I am attempting to move from Eureka to Consul for service discovery and am having an issue - my gateway service registers and my customer-service registers, but the gateway service will not route requests to the customer-service automatically.  Routes I have specifically defined in the gateway Controller that use Feign clients to route work fine, but before (with Eureka) I could make a request to any path like "/customer-service/blah" (where customer-service is the registered name) and the gateway would just forward the request on to the downstream microservice.

Here is my gateway bootstrap.yml (it's in bootstrap and not application because I am also using consul for config)

    spring:
  application:
    name: gateway-api
  cloud:
    consul:
      config:
        watch:
          wait-time: 30
      discovery:
        prefer-ip-address: true
        instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}

Body:
Try this I think this help you to solve your problem..

This is my gateway bootstrap.yml file

spring:
  application:
    name: gateway-service
---

spring:
  profiles: default
  cloud:
    consul:
      config:
        prefix: config/dev/
        format: FILES
      host: localhost
      port: 8500
      discovery:
        prefer-ip-address: true
spring.profiles.active: dev

I use this dependency for gateway and for all applications

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>

consul use as my configuration server. then I add consul to this configurations. configuration path is /config/dev/gateway.yml

zuul:
  prefix: /api
  ignoredServices: '*'
  host:
    connect-timeout-millis: 20000
    socket-timeout-millis: 20000

  routes:
    customer-service:
        path: /customer/**
        serviceId: customer-service
        stripPrefix: false
        sensitiveHeaders: Cookie,Set-Cookie

Gateway service spring boot application annotate like below

@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class GatewayServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayServiceApplication.class, args);
    } // End main ()

}// End GatewayServiceApplication

if you make your application like this you can use routs your prefer way.

sample consul configuration


问:
Sorting 2D Lists in Python 3
I'm having difficulty sorting multidimensional lists in python 3. I want to sort the list below alphabetically based on the name and then in another way based on the age in decesending. I have tried using the sorted function and the lambda key but I get I keep getting the same index error indicating that the list is out of range. How would I sort the entire list?

```<code>    mylist = []
    mylist.append([])
    mylist.append([])
    mylist.append([])
    mylist[0].append("Anna")
    mylist[0].append("Maria")
    mylist[1].append("Doctor")
    mylist[1].append("Teacher")
    mylist[2].append(36)
    mylist[2].append(28)
</code>```

答:
Try this:

```<code>mylist = []
mylist.append([])
mylist.append([])
mylist.append([])
mylist[0].append("Anna")
mylist[1].append("Maria")
mylist[2].append("Aaron")
mylist[0].append("Doctor")
mylist[1].append("Teacher")
mylist[2].append("Student")
mylist[0].append(36)
mylist[1].append(28)
mylist[2].append(13)

mylist.sort(key=lambda x : x[2] , reverse = True)
</code>```

If you want sort by age in descending order...

If you want to sort based on the age then you need to use the lambda function. This works by  setting the key by which you want to sort the list based on an elements index position(i.e in this case the second element in the list->age).
Lastly reverse = True statement is used. This basically explains itself. It simply reverses the list thereby making it in descending order. That's it!

If you want to sort in alphabetical order...

The .sort()function works by initially using the first element in the list. So if you want to sort it in alphabetical order based on the persons name then you can simply use this line of code mylist.sort().

If you still find it difficult  to understand click here.

Title: Sorting 2D Lists in Python 3

Body:
I'm having difficulty sorting multidimensional lists in python 3. I want to sort the list below alphabetically based on the name and then in another way based on the age in decesending. I have tried using the sorted function and the lambda key but I get I keep getting the same index error indicating that the list is out of range. How would I sort the entire list?

    mylist = []
    mylist.append([])
    mylist.append([])
    mylist.append([])
    mylist[0].append("Anna")
    mylist[0].append("Maria")
    mylist[1].append("Doctor")
    mylist[1].append("Teacher")
    mylist[2].append(36)
    mylist[2].append(28)

Body:
Try this:

mylist = []
mylist.append([])
mylist.append([])
mylist.append([])
mylist[0].append("Anna")
mylist[1].append("Maria")
mylist[2].append("Aaron")
mylist[0].append("Doctor")
mylist[1].append("Teacher")
mylist[2].append("Student")
mylist[0].append(36)
mylist[1].append(28)
mylist[2].append(13)

mylist.sort(key=lambda x : x[2] , reverse = True)

If you want sort by age in descending order...

If you want to sort based on the age then you need to use the lambda function. This works by  setting the key by which you want to sort the list based on an elements index position(i.e in this case the second element in the list->age).
Lastly reverse = True statement is used. This basically explains itself. It simply reverses the list thereby making it in descending order. That's it!

If you want to sort in alphabetical order...

The .sort()function works by initially using the first element in the list. So if you want to sort it in alphabetical order based on the persons name then you can simply use this line of code mylist.sort().

If you still find it difficult  to understand click here.