问:
Data bind ObservableCollection<XElement> to a ListBox?
I'm developing a Silverlight application, and want to set the ItemsSource of a ListBox to ObeservableCollection<XElement>  and still be able to use the Binding Path=Element[name].Value syntax to get values for a data template. I can get the binding successfully, but the Element[] syntax is not working. It just renders empty. For example, this does not work:

```<code><DataTemplate x:Key="SearchResultsTemplate">
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=Element[key].Value}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</DataTemplate>
</code>```

But oddly, something like this does render content, which tells me everything is bound to some degree, but something is keeping me from using the Element dynamic property:

```<code><DataTemplate x:Key="SearchResultsTemplate">
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=FirstNode}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</DataTemplate>
</code>```

What am I doing wrong?

答:
Use XPath instead :

```<code><TextBlock Text="{Binding XPath=<..YourXPathSyntax..>}" />
</code>```

EDIT:

As Ian pointed out, you are using Silverlight. So, XPath will not work. Why not use IValueConverter instead?

Example :

```<code>using System.Xml.Linq;
using System.Xml.XPath;

public class IXPathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        String xpath = (String)parameter;
        XElement element = (XElement)value;

        return element.Document.XPathSelectElement(xpath);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

Body:
I'm developing a Silverlight application, and want to set the ItemsSource of a ListBox to ObeservableCollection<XElement>  and still be able to use the Binding Path=Element[name].Value syntax to get values for a data template. I can get the binding successfully, but the Element[] syntax is not working. It just renders empty. For example, this does not work:

<DataTemplate x:Key="SearchResultsTemplate">
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=Element[key].Value}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</DataTemplate>

But oddly, something like this does render content, which tells me everything is bound to some degree, but something is keeping me from using the Element dynamic property:

<DataTemplate x:Key="SearchResultsTemplate">
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=FirstNode}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</DataTemplate>

What am I doing wrong?

Body:
Use XPath instead :

<TextBlock Text="{Binding XPath=<..YourXPathSyntax..>}" />

EDIT:

As Ian pointed out, you are using Silverlight. So, XPath will not work. Why not use IValueConverter instead?

Example :

using System.Xml.Linq;
using System.Xml.XPath;

public class IXPathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        String xpath = (String)parameter;
        XElement element = (XElement)value;

        return element.Document.XPathSelectElement(xpath);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}


来源: stackexchange

问:
Index nested field in elasticsearch from spark DataFrame
Say I have a table like this:

```<code>field1 field2 field3 id
a0     a030   a040   0
a0     a031   a041   0
a0     a032   a042   0
a1     a130   a040   1
</code>```

It's stored in parquet format. I need to read the table in in spark, do a groupBy on 'field1', and then I need to store a nested field (say, called "agg_fields") in ES that contains a list of dictionaries with values for field2 and field3, so that the documents will look like:

```<code>{
  "_id": "0"
  "field1" : "a0",
  "agg_fields" : [
    {
      "field2" : "a030",
      "field3" :  "a040"
    },
    {
      "field2" : "a031",
      "field3" :  "a041"
    },
    {
      "field2" : "a032",
      "field3" :  "a042"
    },
  ]
}
...
</code>```

I can read in the table and do a groupBy:

```<code>df = sqlContext.read.parquet('some-table').groupBy('field1')
</code>```

I can do some aggregation and send the result to es:

```<code>df.withColumn(
    'aggregated', concat('field2', lit('|'), 'field3')
).agg(
    collect_set(aggregated)
).withColumnRenamed(
    'collect_set(aggregated)', 'agg_fields'
).write.format(
    'org.elasticsearch.spark.sql'
).mode(
    'append'
 ).option(
    'es.mapping.id', 'id'
).options(
    **es_config
).option(
    'es.resource', my_resource
).save()
</code>```

But I'm not sure how to change that aggregation to a nested "agg_fields" column which would be interpreted as a nested field by elasticsearch. How can I do this?

ContentLicense: CC BY-SA 3.0

Body:
Say I have a table like this:

field1 field2 field3 id
a0     a030   a040   0
a0     a031   a041   0
a0     a032   a042   0
a1     a130   a040   1

It's stored in parquet format. I need to read the table in in spark, do a groupBy on 'field1', and then I need to store a nested field (say, called "agg_fields") in ES that contains a list of dictionaries with values for field2 and field3, so that the documents will look like:

{
  "_id": "0"
  "field1" : "a0",
  "agg_fields" : [
    {
      "field2" : "a030",
      "field3" :  "a040"
    },
    {
      "field2" : "a031",
      "field3" :  "a041"
    },
    {
      "field2" : "a032",
      "field3" :  "a042"
    },
  ]
}
...

I can read in the table and do a groupBy:

df = sqlContext.read.parquet('some-table').groupBy('field1')

I can do some aggregation and send the result to es:

df.withColumn(
    'aggregated', concat('field2', lit('|'), 'field3')
).agg(
    collect_set(aggregated)
).withColumnRenamed(
    'collect_set(aggregated)', 'agg_fields'
).write.format(
    'org.elasticsearch.spark.sql'
).mode(
    'append'
 ).option(
    'es.mapping.id', 'id'
).options(
    **es_config
).option(
    'es.resource', my_resource
).save()

But I'm not sure how to change that aggregation to a nested "agg_fields" column which would be interpreted as a nested field by elasticsearch. How can I do this?

Body:
df = spark.read.load('file:///path/to/your/example.json', format='json')
df = df.withColumn('agg_fields', f.explode(df['agg_fields']))
df = df.groupBy(df['field1']).agg(f.collect_set(f.concat_ws('|', df['agg_fields']['field2'], df['agg_fields']['field3'])).alias('agg_fields'))

Output:

+------+---------------------------------+
|field1|agg_fields                       |
+------+---------------------------------+
|a0    |[a030|a040, a032|a042, a031|a041]|
+------+---------------------------------+

Do you mean this?


问:
javascript classes call function
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

```<code>class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

module.exports = websocket;
</code>```

websocketModel.js

```<code>const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

module.exports = webSocketModel;
</code>```

答:
You should be calling it from the class this reference:

```<code>class websocket extends webSocketModel {

   constructor() {
      let server = new Server();
      let mongodb = new mongoDB();
      super(server.server);
   }

   onConnMessage(message) {
      let clients = this.clients;
      this.boardCastInit(1);
   }

   boardCastInit(data){
      console.log(data)
   }

}

module.exports = websocket;
</code>```

Title: javascript classes call function

Body:
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

module.exports = websocket;

websocketModel.js

const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

module.exports = webSocketModel;

Body:
You should be calling it from the class this reference:

class websocket extends webSocketModel {

   constructor() {
      let server = new Server();
      let mongodb = new mongoDB();
      super(server.server);
   }

   onConnMessage(message) {
      let clients = this.clients;
      this.boardCastInit(1);
   }

   boardCastInit(data){
      console.log(data)
   }

}

module.exports = websocket;


问:
focus on next tabindex of HTML element onEnter keypress by JQuery
Hi Friends,
I'm working on a small task which is to enable the user to tabindex the html element upon enter keypress.

As im new to jquery , I have written some code which seems to me that It will work ,but there are some problems in it.

Initial findings

The culprit code ,it doesnt work ,as the ouput in the Msg lablel is "Undefined"

```<code>$('*').attr('tabindex').id
</code>```

The code is given below and I have even created a JSFiddle.

JQuery

```<code> $(document).ready(function (eOuter) {
    $('input').bind('keypress', function (eInner) {
        if (eInner.keyCode == 13) //if its a enter key
        {
            var tabindex = $(this).attr('tabindex');
            tabindex++; //increment tabindex
            //after increment of tabindex ,make the next element focus
            $('*').attr('tabindex', tabindex).focus();

                       **//Msg Label**
            //Just to print some msgs to see everything is working
            $('#Msg').text( this.id + " tabindex: " + tabindex
               + " next element: " + $('*').attr('tabindex').id);

            return false; // to cancel out Onenter page postback in asp.net
        }
    });
}
);
</code>```

HTML

```<code><div>
    Employee Info<br />
    Name<br />
    <input name="TxtbxName" type="text" value="ok" id="TxtbxName" tabindex="1" />
    <br />
    Age<br />
    <input name="TxtbxAge" type="text" id="TxtbxAge" tabindex="2" />
    <br />
    Gender<br />
    <select name="DdlGender" id="DdlGender" tabindex="3">
      <option selected="selected" value="Male">Male</option>
      <option value="Female">Female</option>
    </select>
    <br />
    <div>
        Previous Employment<br />
        <select name="DdlCompany" id="DdlCompany" tabindex="4">
   <option selected="selected" value="0">Folio3</option>
   <option value="1">Null Soft</option>
   <option value="2">Object Soft</option>
   <option value="3">Excepption Soft</option>
    </select>
          or Enter Code
        <input name="TxtbxCompanyCode" type="text" id="TxtbxCompanyCode" tabindex="5" />
        <br />
        Address<br />
        <input name="TxtbxAddress" type="text" id="TxtbxAddress" tabindex="6" />
        <br />
       <input type="submit" name="BtnSubmit" value="Submit" id="BtnSubmit" tabindex="7"/>
        <br />
        <label id="Msg">Message here</label>
    </div>
</div>
</code>```

Let me know where I went wrong :/

答:
```<code>var tabindex= $(this).attr("tabindex");
tabindex++;
$("[tabindex='"+tabindex+"']").focus();
</code>```

sample for Editable cells in  table

```<code>    $(document).on('dblclick', 'td', function () {
        console.log('clicked');
        this.contentEditable = 'true';
    });
 $(document).on('keydown', 'td', function (event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            this.contentEditable = 'false';
            //  $(this).next().focus().dblclick().focus();
            var tabindex = $(this).attr('tabindex');
            tabindex++;
            var next = $('[tabindex=' + tabindex + ']').focus().dblclick();
            if (next.is('td') == false)
                return true;
            var sel, range;
            if (window.getSelection && document.createRange) {
                range = document.createRange();
                range.selectNodeContents(next[0]);
                range.collapse(true);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(next[0]);
                range.collapse(true);
                range.select();
            }

            return false;
        }
    });
</code>```

Editable cells in dynamic table

Body:
Hi Friends,
I'm working on a small task which is to enable the user to tabindex the html element upon enter keypress.

As im new to jquery , I have written some code which seems to me that It will work ,but there are some problems in it.

Initial findings

The culprit code ,it doesnt work ,as the ouput in the Msg lablel is "Undefined"

$('*').attr('tabindex').id

The code is given below and I have even created a JSFiddle.

JQuery

 $(document).ready(function (eOuter) {
    $('input').bind('keypress', function (eInner) {
        if (eInner.keyCode == 13) //if its a enter key
        {
            var tabindex = $(this).attr('tabindex');
            tabindex++; //increment tabindex
            //after increment of tabindex ,make the next element focus
            $('*').attr('tabindex', tabindex).focus();

                       **//Msg Label**
            //Just to print some msgs to see everything is working
            $('#Msg').text( this.id + " tabindex: " + tabindex
               + " next element: " + $('*').attr('tabindex').id);

            return false; // to cancel out Onenter page postback in asp.net
        }
    });
}
);

HTML

    Employee Info

    Name

    <input name="TxtbxName" type="text" value="ok" id="TxtbxName" tabindex="1" />

    Age

    <input name="TxtbxAge" type="text" id="TxtbxAge" tabindex="2" />

    Gender

    <select name="DdlGender" id="DdlGender" tabindex="3">
      <option selected="selected" value="Male">Male</option>
      <option value="Female">Female</option>
    </select>

        Previous Employment

        <select name="DdlCompany" id="DdlCompany" tabindex="4">
   <option selected="selected" value="0">Folio3</option>
   <option value="1">Null Soft</option>
   <option value="2">Object Soft</option>
   <option value="3">Excepption Soft</option>
    </select>
          or Enter Code
        <input name="TxtbxCompanyCode" type="text" id="TxtbxCompanyCode" tabindex="5" />

        Address

        <input name="TxtbxAddress" type="text" id="TxtbxAddress" tabindex="6" />

       <input type="submit" name="BtnSubmit" value="Submit" id="BtnSubmit" tabindex="7"/>

        Message here

Let me know where I went wrong :/

Body:
var tabindex= $(this).attr("tabindex");
tabindex++;
$("[tabindex='"+tabindex+"']").focus();

sample for Editable cells in  table

    $(document).on('dblclick', 'td', function () {
        console.log('clicked');
        this.contentEditable = 'true';
    });
 $(document).on('keydown', 'td', function (event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            this.contentEditable = 'false';
            //  $(this).next().focus().dblclick().focus();
            var tabindex = $(this).attr('tabindex');
            tabindex++;
            var next = $('[tabindex=' + tabindex + ']').focus().dblclick();
            if (next.is('td') == false)
                return true;
            var sel, range;
            if (window.getSelection && document.createRange) {
                range = document.createRange();
                range.selectNodeContents(next[0]);
                range.collapse(true);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(next[0]);
                range.collapse(true);
                range.select();
            }

            return false;
        }
    });

Editable cells in dynamic table


问:
Compare files names regardless of extension in node
So I have a node script that currently spits out two arrays:

```<code>$ yarn run header:test
yarn run v0.22.0
$ ./bin/create_header.js
[ 'LucidEventIcon.md', 'LucidStates.md' ] [ 'LucidEventIcon.js', 'LucidStates.js' ]
</code>```

What I would like to do is use some kind of find method to say:

"LucideEventIcon.md should match the LucidEventIcon.js", what I care about is matching on name. I need to keep the file extension so I can, later, prepend the contends of the .md to the .js

How can I match on name, regardless of extension? while looping over the first and checking the second array?

Expected result should be true for both elements in the first array, they should match to the two JS files in the second array.

答:
You can create your own little function for comparing the base name (without file extension) and then just loop through the first array calling this function for both arrays.  The path module can be used to parse out just the base name (without extension or path).

```<code>const path = require('path');

function compareFileNames(f1, f2) {
    let name1 = path.parse(f1).name;
    let name2 = path.parse(f2).name;
    return name1 === name2;
}
</code>```

It's not clear to me exactly what type of output you want, but you could create an array of booleans that tell you what matches.  If the two arrays are arr1 and arr2:

```<code>let results = arr1.map(function(f1, index) {
    let f2 = arr2[index];
    return typeof f2 === "string" && compareFileNames(f1, f2);
});
</code>```

If you're just trying to see if they all match:

```<code>let match = arr1.every(function(f1, index) {
    let f2 = arr2[index];
    return typeof f2 === "string"  && compareFileNames(f1, f2);
});
</code>```

Body:
So I have a node script that currently spits out two arrays:

$ yarn run header:test
yarn run v0.22.0
$ ./bin/create_header.js
[ 'LucidEventIcon.md', 'LucidStates.md' ] [ 'LucidEventIcon.js', 'LucidStates.js' ]

What I would like to do is use some kind of find method to say:

"LucideEventIcon.md should match the LucidEventIcon.js", what I care about is matching on name. I need to keep the file extension so I can, later, prepend the contends of the .md to the .js

How can I match on name, regardless of extension? while looping over the first and checking the second array?

Expected result should be true for both elements in the first array, they should match to the two JS files in the second array.

Body:
You can create your own little function for comparing the base name (without file extension) and then just loop through the first array calling this function for both arrays.  The path module can be used to parse out just the base name (without extension or path).

const path = require('path');

function compareFileNames(f1, f2) {
    let name1 = path.parse(f1).name;
    let name2 = path.parse(f2).name;
    return name1 === name2;
}

It's not clear to me exactly what type of output you want, but you could create an array of booleans that tell you what matches.  If the two arrays are arr1 and arr2:

let results = arr1.map(function(f1, index) {
    let f2 = arr2[index];
    return typeof f2 === "string" && compareFileNames(f1, f2);
});

If you're just trying to see if they all match:

let match = arr1.every(function(f1, index) {
    let f2 = arr2[index];
    return typeof f2 === "string"  && compareFileNames(f1, f2);
});


答: You are missing this (should be this.boardCastInit(1)).</p>

Title: javascript classes call function


问:
How can I select random files from a directory in bash?
I have a directory with about 2000 files. How can I select a random sample of N files through using either a bash script or a list of piped commands?

答:
How about a Perl solution slightly doctored from Mr. Kang over here:

 How can I shuffle the lines of a text file on the Unix command line or in a shell script?

$ ls | perl -MList::Util=shuffle -e '@lines = shuffle(<>); print
  @lines[0..4]'

OwnerDisplayName: Marlo Guthrie


问:
Getting Django's staticfiles includes working inside Vue.js .vue templates
I have a Django SPA built with Vue.js v2 / webpack.

I want to be able to use Django static template tags to add in references to images, etc inside Vue.js template .vue files.

Right now in my base.html template for Django:

```<code>{% load static %}
{% load render_bundle from webpack_loader %}
<html>
   <head>
      <!-- This works fine here! -->
      <link rel="stylesheet" href="{% static 'css/test.css' %}" />
      ...
   </head>
   <body>
      <div id="app">
        <!-- Vue.js app gets mounted here -->
      </div>
   </body>
</html>
</code>```

and that is of course the HTML page I use for the SPA (single page application).

But when I try to use static tags in my .vue template files like so:

```<code>{% static 'js/test.js' %}
</code>```

It doesn't work - it never gets interpolated because of course Django is server-side and Vue is client-side.

I want to keep using the staticfiles tags (and not hard links) because I use different storage backends for static files, media, and even from local/staging/prod environments.

Any ideas for how to handle this with Django/Vue.js? What's a good solution here to get staticfiles linking into templates clientside?

答: A good solution? Separation of duties. Why should Django templates be involved at all? Your front end code can handle all rendering. Your back end can just serve up rest api endpoints.</p>

Body:
I have a Django SPA built with Vue.js v2 / webpack.

I want to be able to use Django static template tags to add in references to images, etc inside Vue.js template .vue files.

Right now in my base.html template for Django:

{% load static %}
{% load render_bundle from webpack_loader %}

      <link rel="stylesheet" href="{% static 'css/test.css' %}" />
      ...

and that is of course the HTML page I use for the SPA (single page application).

But when I try to use static tags in my .vue template files like so:

{% static 'js/test.js' %}

It doesn't work - it never gets interpolated because of course Django is server-side and Vue is client-side.

I want to keep using the staticfiles tags (and not hard links) because I use different storage backends for static files, media, and even from local/staging/prod environments.

Any ideas for how to handle this with Django/Vue.js? What's a good solution here to get staticfiles linking into templates clientside?


问:
Import Polygon Data from geojson files into PostGIS using GeoDjango
Am using GeoDjango with PostGIS as Backend. I have few geojson files with features as following example. GeoDjango has provided information to import shape files and other formats but geojson formats. How do I import these geojson files into DB?

```<code>  "features": [
{ "type": "Feature", "properties": { "SubName": "X", "SubSubName": "A" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 70.693828, 37.074496 ], [ 70.693828, 37.074496 ] ] ] } }
,
{ "type": "Feature", "properties": { "SubName": "X", "SubSubName": "B" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 70.502913, 27.065997 ],  [ 70.502913, 27.065997 ] ] ] } }
</code>```

I have two core requirements:

Load the Subregion polygons on webportal using D3JS Map library

When i have a lat-long, find in which polygon does this point exist and get the SubName & SubSubName from the polygon properties.

It would be great, if there is proper documentation on PostGIS usage & import files for GeoDjango.

Thanks in Advance.

答:
Taken from - https://docs.djangoproject.com/en/1.9/ref/contrib/gis/geos/

```<code>from django.contrib.gis.geos import GEOSGeometry
# load from geo-json str
pnt = GEOSGeometry('{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }')
</code>```

The geojson can be for anything like polygon, multi-polygon, etc.

Body:
Am using GeoDjango with PostGIS as Backend. I have few geojson files with features as following example. GeoDjango has provided information to import shape files and other formats but geojson formats. How do I import these geojson files into DB?

  "features": [
{ "type": "Feature", "properties": { "SubName": "X", "SubSubName": "A" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 70.693828, 37.074496 ], [ 70.693828, 37.074496 ] ] ] } }
,
{ "type": "Feature", "properties": { "SubName": "X", "SubSubName": "B" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 70.502913, 27.065997 ],  [ 70.502913, 27.065997 ] ] ] } }

I have two core requirements:

Load the Subregion polygons on webportal using D3JS Map library

When i have a lat-long, find in which polygon does this point exist and get the SubName & SubSubName from the polygon properties.

It would be great, if there is proper documentation on PostGIS usage & import files for GeoDjango.

Thanks in Advance.

Body:
Taken from - https://docs.djangoproject.com/en/1.9/ref/contrib/gis/geos/

from django.contrib.gis.geos import GEOSGeometry
# load from geo-json str
pnt = GEOSGeometry('{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }')

The geojson can be for anything like polygon, multi-polygon, etc.


问:
Java Program giving Method/Return related errors.
I'm working on Java homework, which is divided into several parts. I'm stuck on part 2. This is not meant to be a homework dump, I'm just stuck on part 2, I included part 1 and 3 for context. I'd really appreciate any help or feedback. Thanks!

(1) Prompt the user to enter a string of their choosing. Store the text in a string. Output the string. (1 pt)

Ex:

Enter a sample text:
We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

You entered: We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

(2) Implement a printMenu() method, which outputs a menu of user options for analyzing/editing the string, and returns the user's entered menu option. Each option is represented by a single character.

If an invalid character is entered, continue to prompt for a valid choice. Hint: Implement Quit before implementing other options. Call printMenu() in the main() method. Continue to call printMenu() until the user enters q to Quit. (3 pts)

Ex:

MENU
c - Number of non-whitespace characters
w - Number of words
f - Find text
r - Replace all !'s
s - Shorten spaces
q - Quit

Choose an option:

(3) Implement the getNumOfNonWSCharacters() method. getNumOfNonWSCharacters() has a string as a parameter and returns the number of characters in the string, excluding all whitespace. Call getNumOfNonWSCharacters() in the main() method. (4 pts)

Ex:

Enter a sample text:
We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

You entered: We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

MENU
c - Number of non-whitespace characters
w - Number of words
f - Find text
r - Replace all !'s
s - Shorten spaces
q - Quit

Choose an option:
c
Number of non-whitespace characters: 181

My code:

```<code>import java.util.Scanner;

public class AuthoringAssistant {

   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      String userInput = sc.nextLine();
      System.out.println("Enter a sample text: ");
      System.out.println(userInput);

      return printMenu;
   }

   public static int printMenu(Character[] menu) {
      Scanner in = new Scanner(System.in);
      Character userChar = in.nextCharacter();
      System.out.println("MENU");
      System.out.println("c - Number of non-whitespace characters");
      System.out.println("w - Number of words");
      System.out.println("f - Find text");
      System.out.println("r - Replace all !'s");
      System.out.println("s - Shorten spaces");
      System.out.println("q - Quit");
      System.out.println("Choose an option: ");

      if (userChar == 'q') {
         System.out.println("q");
         System.out.println("Quit");
      }
      else if (userChar == 'w') {
         System.out.println("w");
         System.out.println("Number of words: ");
      }
      else if (userChar == 'f') {
         System.out.println("f");
         System.out.println("Find text: ");
      }
      else if (userChar == 'r') {
         System.out.println("r");
         System.out.println("Replace all !'s: ");
      }
      else if (userChar == 's') {
         System.out.println("s");
         System.out.println("Shorten spaces: ");
      }
      else if (userChar == 'c') {
         System.out.println("c");
         System.out.println("Number of non-whitespace characters: ");
      }
      else {
         System.out.println("Please select a valid character.");
      }

      return char in.nextCharacter();
   }
}
</code>```

I'm getting the following errors:

```<code>AuthoringAssistant.java:55: error: '.class' expected
      return char in.nextCharacter();
              ^
AuthoringAssistant.java:55: error: illegal start of expression
      return char in.nextCharacter();
                ^
AuthoringAssistant.java:55: error: ';' expected
      return char in.nextCharacter();
                              ^
3 errors
</code>```

答:
You need to change your return statement.

1) You are trying to return a char, but your method returns an int.

```<code>public static int printMenu(...){
   ...
   return char ... ;
}
</code>```

2) ".nextCharacter()" doesn't exist. You need to use ".nextLine()" and then ".charAt(x)"

Eg.:

```<code> in.nextLine().charAt(0); //To get the first character from the line
</code>```

3) Even if your method did return chars, you only declare the type when declaring a variable or casting to a different type.

So instead of:

```<code>return char myVariable;
</code>```

You would just write:

```<code>return myVariable;
</code>```

Body:
I'm working on Java homework, which is divided into several parts. I'm stuck on part 2. This is not meant to be a homework dump, I'm just stuck on part 2, I included part 1 and 3 for context. I'd really appreciate any help or feedback. Thanks!

(1) Prompt the user to enter a string of their choosing. Store the text in a string. Output the string. (1 pt)

Ex:

Enter a sample text:
We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

You entered: We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

(2) Implement a printMenu() method, which outputs a menu of user options for analyzing/editing the string, and returns the user's entered menu option. Each option is represented by a single character.

If an invalid character is entered, continue to prompt for a valid choice. Hint: Implement Quit before implementing other options. Call printMenu() in the main() method. Continue to call printMenu() until the user enters q to Quit. (3 pts)

Ex:

MENU
c - Number of non-whitespace characters
w - Number of words
f - Find text
r - Replace all !'s
s - Shorten spaces
q - Quit

Choose an option:

(3) Implement the getNumOfNonWSCharacters() method. getNumOfNonWSCharacters() has a string as a parameter and returns the number of characters in the string, excluding all whitespace. Call getNumOfNonWSCharacters() in the main() method. (4 pts)

Ex:

Enter a sample text:
We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

You entered: We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

MENU
c - Number of non-whitespace characters
w - Number of words
f - Find text
r - Replace all !'s
s - Shorten spaces
q - Quit

Choose an option:
c
Number of non-whitespace characters: 181

My code:

import java.util.Scanner;

public class AuthoringAssistant {

   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      String userInput = sc.nextLine();
      System.out.println("Enter a sample text: ");
      System.out.println(userInput);

      return printMenu;
   }

   public static int printMenu(Character[] menu) {
      Scanner in = new Scanner(System.in);
      Character userChar = in.nextCharacter();
      System.out.println("MENU");
      System.out.println("c - Number of non-whitespace characters");
      System.out.println("w - Number of words");
      System.out.println("f - Find text");
      System.out.println("r - Replace all !'s");
      System.out.println("s - Shorten spaces");
      System.out.println("q - Quit");
      System.out.println("Choose an option: ");

      if (userChar == 'q') {
         System.out.println("q");
         System.out.println("Quit");
      }
      else if (userChar == 'w') {
         System.out.println("w");
         System.out.println("Number of words: ");
      }
      else if (userChar == 'f') {
         System.out.println("f");
         System.out.println("Find text: ");
      }
      else if (userChar == 'r') {
         System.out.println("r");
         System.out.println("Replace all !'s: ");
      }
      else if (userChar == 's') {
         System.out.println("s");
         System.out.println("Shorten spaces: ");
      }
      else if (userChar == 'c') {
         System.out.println("c");
         System.out.println("Number of non-whitespace characters: ");
      }
      else {
         System.out.println("Please select a valid character.");
      }

      return char in.nextCharacter();
   }
}

I'm getting the following errors:

AuthoringAssistant.java:55: error: '.class' expected
      return char in.nextCharacter();
              ^
AuthoringAssistant.java:55: error: illegal start of expression
      return char in.nextCharacter();
                ^
AuthoringAssistant.java:55: error: ';' expected
      return char in.nextCharacter();
                              ^
3 errors

Body:
You need to change your return statement.

1) You are trying to return a char, but your method returns an int.

public static int printMenu(...){
   ...
   return char ... ;
}

2) ".nextCharacter()" doesn't exist. You need to use ".nextLine()" and then ".charAt(x)"

Eg.:

 in.nextLine().charAt(0); //To get the first character from the line

3) Even if your method did return chars, you only declare the type when declaring a variable or casting to a different type.

So instead of:

return char myVariable;

You would just write:

return myVariable;


问:
What is Dispatcher Servlet in Spring?
In this image (which I got from here), HTTP request sends something to Dispatcher Servlet.

My Question is what does Dispatcher Servlet do?

Is it something like getting the information thrown from the web page and throwing it to the controller?

答:
I know this question is marked as solved already but I want to add a newer image explaining this pattern in detail(source: spring in action 4):

Explanation

When the request leaves the browser (1), it carries information about what the user is asking for. At the least, the request will be carrying the requested URL. But it may also carry additional data, such as the information submitted in a form by the user.

The first stop in the request’s travels is at Spring’s DispatcherServlet. Like most Java- based web frameworks, Spring MVC funnels requests through a single front controller servlet. A front controller is a common web application pattern where a single servlet delegates responsibility for a request to other components of an application to perform actual processing. In the case of Spring MVC, DispatcherServlet is the front controller.

The DispatcherServlet’s job is to send the request on to a Spring MVC controller. A controller is a Spring component that processes the request. But a typical application may have several controllers, and DispatcherServlet needs some help deciding which controller to send the request to.

So the DispatcherServlet consults one or more handler mappings (2) to figure out where the request’s next stop will be. The handler mapping pays particular attention to the URL carried by the request when making its decision.
Once an appropriate controller has been chosen, DispatcherServlet sends the request on its merry way to the chosen controller (3).

At the controller, the request drops off its payload (the information submitted by the user) and patiently waits while the controller processes that information. (Actually, a well-designed controller performs little or no processing itself and instead delegates responsibility for the business logic to one or more service objects.)
The logic performed by a controller often results in some information that needs to be carried back to the user and displayed in the browser. This information is referred to as the model. But sending raw information back to the user isn’t sufficient. It needs to be formatted in a user-friendly format, typically HTML. For that, the information needs to be given to a view, typically a JavaServer Page (JSP).
One of the last things a controller does is package up the model data and identify the name of a view that should render the output. It then sends the request, along with the model and view name, back to the DispatcherServlet (4).

So that the controller doesn’t get coupled to a particular view, the view name passed back to DispatcherServlet doesn’t directly identify a specific JSP. It doesn’t even necessarily suggest that the view is a JSP. Instead, it only carries a logical name that will be used to look up the actual view that will produce the result. The DispatcherServlet consults a view resolver (5) to map the logical view name to a specific view implementation, which may or may not be a JSP.

Now that DispatcherServlet knows which view will render the result, the request’s job is almost over. Its final stop is at the view implementation (6), typically a JSP, where it delivers the model data. The request’s job is finally done. The view will use the model data to render output that will be carried back to the client by the (not- so-hardworking) response object (7).

Title: What is Dispatcher Servlet in Spring?

ContentLicense: CC BY-SA 4.0


问:
Polymorphic JSON unmarshalling of embedded structs
Here is an example (see also https://play.golang.org/p/or7z4Xc8tN):

```<code>package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    X string
    Y int
}

type B struct {
    A
    Y string
}

func main() {
    data := []byte(`{"X": "me", "Y": "hi"}`)
    b := &B{}
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)

    b = &B{}
    data = []byte(`{"X": "me", "Y": 123}`)
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)
}
</code>```

Which outputs:

```<code>&{{me 0} hi}
{me 0}
&{{me 0} }
{me 0}
</code>```

Is there a way to polymorphically unmarshal the field Y to either an int or a string? Or even unmarshal into A.Y at all since B.Y is defined?

I know some might suggest unmarshalling with something like json.Unmarshall(data, &b.A), but I don't know if I can fit that into my current design.

答:
Go's only polymorphism is interfaces. Embedding does not offer polymorphism.

If you're trying to unmarshal JSON where you can't assume what type one of the fields is going to be, you can use a field of type interface{} along with type assertions, fmt.Sprint, or reflection. Which you should use depends on the particular use case - once you've got the value, what are you going to do with it? At some point you have to care if it's an int or a string, which will determine how you handle the value.

Body:
Here is an example (see also https://play.golang.org/p/or7z4Xc8tN):

package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    X string
    Y int
}

type B struct {
    A
    Y string
}

func main() {
    data := []byte(`{"X": "me", "Y": "hi"}`)
    b := &B{}
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)

    b = &B{}
    data = []byte(`{"X": "me", "Y": 123}`)
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)
}

Which outputs:

&{{me 0} hi}
{me 0}
&{{me 0} }
{me 0}

Is there a way to polymorphically unmarshal the field Y to either an int or a string? Or even unmarshal into A.Y at all since B.Y is defined?

I know some might suggest unmarshalling with something like json.Unmarshall(data, &b.A), but I don't know if I can fit that into my current design.


问:
How to correctly implement custom iterators and const_iterators?
I have a custom container class for which I'd like to write the iterator and const_iterator classes.

I never did this before and I failed to find an appropriate how-to. What are the guidelines regarding iterator creation, and what should I be aware of ?

I'd also like to avoid code duplication (I feel that const_iterator and iterator share many things; should one subclass the other ?).

Foot note: I'm pretty sure Boost has something to ease this but I can't use it here, for many stupid reasons.

答:
There are plenty of good answers but I created a template header I use that is quite concise and easy to use.

To add an iterator to your class it is only necessary to write a small class to represent the state of the iterator with 7 small functions, of which 2 are optional:

```<code>#include <iostream>
#include <vector>
#include "iterator_tpl.h"

struct myClass {
  std::vector<float> vec;

  // Add some sane typedefs for STL compliance:
  STL_TYPEDEFS(float);

  struct it_state {
    int pos;
    inline void begin(const myClass* ref) { pos = 0; }
    inline void next(const myClass* ref) { ++pos; }
    inline void end(const myClass* ref) { pos = ref->vec.size(); }
    inline float& get(myClass* ref) { return ref->vec[pos]; }
    inline bool equals(const it_state& s) const { return pos == s.pos; }

    // Optional to allow operator--() and reverse iterators:
    inline void prev(const myClass* ref) { --pos; }
    // Optional to allow `const_iterator`:
    inline const float& get(const myClass* ref) const { return ref->vec[pos]; }
  };
  // Declare typedef ... iterator;, begin() and end() functions:
  SETUP_ITERATORS(myClass, float&, it_state);
  // Declare typedef ... reverse_iterator;, rbegin() and rend() functions:
  SETUP_REVERSE_ITERATORS(myClass, float&, it_state);
};
</code>```

Then you can use it as you would expect from an STL iterator:

```<code>int main() {
  myClass c1;
  c1.vec.push_back(1.0);
  c1.vec.push_back(2.0);
  c1.vec.push_back(3.0);

  std::cout << "iterator:" << std::endl;
  for (float& val : c1) {
    std::cout << val << " "; // 1.0 2.0 3.0
  }

  std::cout << "reverse iterator:" << std::endl;
  for (auto it = c1.rbegin(); it != c1.rend(); ++it) {
    std::cout << *it << " "; // 3.0 2.0 1.0
  }
}
</code>```

I hope it helps.

Body:
There are plenty of good answers but I created a template header I use that is quite concise and easy to use.

To add an iterator to your class it is only necessary to write a small class to represent the state of the iterator with 7 small functions, of which 2 are optional:

#include <iostream>
#include <vector>
#include "iterator_tpl.h"

struct myClass {
  std::vector<float> vec;

  // Add some sane typedefs for STL compliance:
  STL_TYPEDEFS(float);

  struct it_state {
    int pos;
    inline void begin(const myClass* ref) { pos = 0; }
    inline void next(const myClass* ref) { ++pos; }
    inline void end(const myClass* ref) { pos = ref->vec.size(); }
    inline float& get(myClass* ref) { return ref->vec[pos]; }
    inline bool equals(const it_state& s) const { return pos == s.pos; }

    // Optional to allow operator--() and reverse iterators:
    inline void prev(const myClass* ref) { --pos; }
    // Optional to allow `const_iterator`:
    inline const float& get(const myClass* ref) const { return ref->vec[pos]; }
  };
  // Declare typedef ... iterator;, begin() and end() functions:
  SETUP_ITERATORS(myClass, float&, it_state);
  // Declare typedef ... reverse_iterator;, rbegin() and rend() functions:
  SETUP_REVERSE_ITERATORS(myClass, float&, it_state);
};

Then you can use it as you would expect from an STL iterator:

int main() {
  myClass c1;
  c1.vec.push_back(1.0);
  c1.vec.push_back(2.0);
  c1.vec.push_back(3.0);

  std::cout << "iterator:" << std::endl;
  for (float& val : c1) {
    std::cout << val << " "; // 1.0 2.0 3.0
  }

  std::cout << "reverse iterator:" << std::endl;
  for (auto it = c1.rbegin(); it != c1.rend(); ++it) {
    std::cout << *it << " "; // 3.0 2.0 1.0
  }
}

I hope it helps.


问:
snappydata Unable to access SnappyData store from an Existing Spark Installation using Smart Connector by Java
I try to connect to SnappyData store by smart connector style as description in http://snappydatainc.github.io/snappydata/howto/#how-to-access-snappydata-store-from-an-existing-spark-installation-using-smart-connector, but got com.gemstone.gemfire.SerializationException root caused by java.nio.BufferUnderflowException.

Here is the stacktrace:

```<code>com.gemstone.gemfire.SerializationException: Could not create an instance of  com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage .
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2900)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)
    at com.gemstone.gemfire.distributed.internal.ReplyException.fixUpRemoteEx(ReplyException.java:109)
    at com.gemstone.gemfire.distributed.internal.ReplyException.handleAsUnexpected(ReplyException.java:87)
    at com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor.waitForProfileResponse(UpdateAttributesProcessor.java:94)
    at com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor.distribute(UpdateAttributesProcessor.java:79)
    at com.gemstone.gemfire.distributed.internal.DistributionAdvisor.exchangeProfiles(DistributionAdvisor.java:1231)
    at com.gemstone.gemfire.distributed.internal.DistributionAdvisor.initializationGate(DistributionAdvisor.java:485)
    at com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor.handshake(GfxdDistributionAdvisor.java:235)
    at com.pivotal.gemfirexd.internal.engine.store.GemFireStore$StoreAdvisee.start(GemFireStore.java:2565)
    at com.pivotal.gemfirexd.internal.engine.store.GemFireStore$StoreAdvisee.access$000(GemFireStore.java:2501)
    at com.pivotal.gemfirexd.internal.engine.store.GemFireStore.boot(GemFireStore.java:1208)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.boot(BaseMonitor.java:2245)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.TopService.bootModule(TopService.java:314)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.startModule(BaseMonitor.java:720)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.FileMonitor.startModule(FileMonitor.java:65)
    at com.pivotal.gemfirexd.internal.iapi.services.monitor.Monitor.bootServiceModule(Monitor.java:497)
    at com.pivotal.gemfirexd.internal.engine.db.FabricDatabase.bootStore(FabricDatabase.java:2358)
    at com.pivotal.gemfirexd.internal.engine.db.FabricDatabase.boot(FabricDatabase.java:354)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.boot(BaseMonitor.java:2245)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.TopService.bootModule(TopService.java:314)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.bootService(BaseMonitor.java:2043)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.startProviderService(BaseMonitor.java:1906)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.findProviderAndStartService(BaseMonitor.java:1786)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.startPersistentService(BaseMonitor.java:1196)
    at com.pivotal.gemfirexd.internal.iapi.services.monitor.Monitor.startPersistentService(Monitor.java:620)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection.bootDatabase(EmbedConnection.java:3379)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection.<init>(EmbedConnection.java:452)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection30.<init>(EmbedConnection30.java:94)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection40.<init>(EmbedConnection40.java:75)
    at com.pivotal.gemfirexd.internal.jdbc.Driver40.getNewEmbedConnection(Driver40.java:95)
    at com.pivotal.gemfirexd.internal.jdbc.InternalDriver.connect(InternalDriver.java:351)
    at com.pivotal.gemfirexd.internal.jdbc.InternalDriver.connect(InternalDriver.java:219)
    at com.pivotal.gemfirexd.internal.jdbc.InternalDriver.connect(InternalDriver.java:195)
    at io.snappydata.jdbc.AutoloadedDriver.connect(AutoloadedDriver.java:153)
    at com.pivotal.gemfirexd.internal.engine.fabricservice.FabricServiceImpl.startImpl(FabricServiceImpl.java:279)
    at com.pivotal.gemfirexd.internal.engine.fabricservice.FabricServerImpl.start(FabricServerImpl.java:60)
    at io.snappydata.impl.LeadImpl.internalStart(LeadImpl.scala:188)
    at io.snappydata.impl.LeadImpl$.invokeLeadStart(LeadImpl.scala:489)
    at org.apache.spark.scheduler.cluster.SnappyEmbeddedModeClusterManager.initialize(SnappyEmbeddedModeClusterManager.scala:88)
    at org.apache.spark.SparkContext$.org$apache$spark$SparkContext$$createTaskScheduler(SparkContext.scala:2506)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:489)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2258)
    at org.apache.spark.sql.SparkSession$Builder$$anonfun$8.apply(SparkSession.scala:831)
    at org.apache.spark.sql.SparkSession$Builder$$anonfun$8.apply(SparkSession.scala:823)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:823)
    at com.meituan.hotel.pegasuscollect.spark.SmartConnectorMain.main(SmartConnectorMain.java:11)
    at com.meituan.hotel.pegasuscollect.controller.SparkController.getCompActualPriceModelFromCache(SparkController.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:669)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1448)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1419)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:455)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1075)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:384)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1009)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:368)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
    at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:942)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1004)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:640)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.gemstone.gemfire.SerializationException: Could not create an instance of  com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile .
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2900)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.readGfxdMessage(DSFIDFactory.java:986)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:775)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readObject(InternalDataSerializer.java:3424)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.basicReadObject(InternalDataSerializer.java:3417)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readObject(DataSerializer.java:3342)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage.fromData(UpdateAttributesProcessor.java:356)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)
Caused by: java.nio.BufferUnderflowException
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.Buffer.nextGetIndex(Buffer.java:506)
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:681)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.readInt(ByteBufferInputStream.java:190)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readInteger(DataSerializer.java:881)
    at Remote Member 'host-07(41099)<v7>:32671' in com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile.fromData(GfxdDistributionAdvisor.java:1574)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    ... 13 more
Caused by:
com.gemstone.gemfire.SerializationException: Could not create an instance of  com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile .
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2900)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.readGfxdMessage(DSFIDFactory.java:986)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:775)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readObject(InternalDataSerializer.java:3424)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.basicReadObject(InternalDataSerializer.java:3417)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readObject(DataSerializer.java:3342)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage.fromData(UpdateAttributesProcessor.java:356)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)
Caused by: java.nio.BufferUnderflowException
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.Buffer.nextGetIndex(Buffer.java:506)
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:681)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.readInt(ByteBufferInputStream.java:190)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readInteger(DataSerializer.java:881)
    at Remote Member 'host-07(41099)<v7>:32671' in com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile.fromData(GfxdDistributionAdvisor.java:1574)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    ... 13 more
Caused by:
java.nio.BufferUnderflowException
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.Buffer.nextGetIndex(Buffer.java:506)
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:681)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.readInt(ByteBufferInputStream.java:190)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readInteger(DataSerializer.java:881)
    at Remote Member 'host-07(41099)<v7>:32671' in com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile.fromData(GfxdDistributionAdvisor.java:1574)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.readGfxdMessage(DSFIDFactory.java:986)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:775)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readObject(InternalDataSerializer.java:3424)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.basicReadObject(InternalDataSerializer.java:3417)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readObject(DataSerializer.java:3342)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage.fromData(UpdateAttributesProcessor.java:356)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)
</code>```

Here is the code:

```<code>public class SmartConnectorMain{
public static void main(String [] args){

    SparkSession spark = SparkSession
            .builder()
            .appName("SmartConnectorMainJava")
            .master("snappydata://host-01:9999,host05-:9999")
            .config("snappydata.store.locators", "host-01:9999,host-05:9999")
            .getOrCreate();

    JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());
    SnappySession snappy = new SnappySession(spark.sparkContext());

    println(" ####  Creating a table TestColumnTable  #### \n");

    snappy.dropTable("TestColumnTable",  true);

    DataSet<Row> dataFrame = snappy.range(1000).selectExpr("id", "floor(rand() * 10000) as k");

    snappy.sql("create table TestColumnTable (id bigint not null, k bigint not null) using column");

    println(" ####  Write to table completed. ### \n\n" +
            "Now you can query table TestColumnTable using $SNAPPY_HOME/bin/snappy-shell");
}

private static void println(String s){
    System.out.println(s);
}
</code>```

And here is the configuration in cluster:

```<code>Name    Value
jobserver.enabled   true
snappydata.embedded true
snappydata.store.critical-heap-percentage   90.0
snappydata.store.eviction-heap-percentage   81.0
snappydata.store.host-data  true
snappydata.store.locators   host-01:9999,host-05:9999
snappydata.store.log-file   snappyleader.log
snappydata.store.mcast-port 0
snappydata.store.statistic-archive-file snappyleader.gfs
spark.app.id    snappy-app-1494920649221
spark.app.name  leaderLauncher
spark.closure.serializer    org.apache.spark.serializer.PooledKryoSerializer
spark.driver.host   10.16.118.36
spark.driver.port   25490
spark.executor.cores    10
spark.executor.id   driver
spark.master    snappydata://host-01:9999,host-05:9999
spark.scheduler.mode    FAIR
spark.serializer    org.apache.spark.serializer.PooledKryoSerializer
spark.ui.port   9411
</code>```

答:
The problem seems to be your SnappyData locators and Spark master URL is using the same host and port. I quickly verified with SnappyData 0.8 version, with Spark2.0 local mode cluster using spark package 0.8-s_2.11 from https://spark-packages.org/package/SnappyDataInc/snappydata.

I was able to query the table through snappy-sql shell as well.
Here is screenshot of my program

Body:
I try to connect to SnappyData store by smart connector style as description in http://snappydatainc.github.io/snappydata/howto/#how-to-access-snappydata-store-from-an-existing-spark-installation-using-smart-connector, but got com.gemstone.gemfire.SerializationException root caused by java.nio.BufferUnderflowException.

Here is the stacktrace:

com.gemstone.gemfire.SerializationException: Could not create an instance of  com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage .
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2900)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)
    at com.gemstone.gemfire.distributed.internal.ReplyException.fixUpRemoteEx(ReplyException.java:109)
    at com.gemstone.gemfire.distributed.internal.ReplyException.handleAsUnexpected(ReplyException.java:87)
    at com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor.waitForProfileResponse(UpdateAttributesProcessor.java:94)
    at com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor.distribute(UpdateAttributesProcessor.java:79)
    at com.gemstone.gemfire.distributed.internal.DistributionAdvisor.exchangeProfiles(DistributionAdvisor.java:1231)
    at com.gemstone.gemfire.distributed.internal.DistributionAdvisor.initializationGate(DistributionAdvisor.java:485)
    at com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor.handshake(GfxdDistributionAdvisor.java:235)
    at com.pivotal.gemfirexd.internal.engine.store.GemFireStore$StoreAdvisee.start(GemFireStore.java:2565)
    at com.pivotal.gemfirexd.internal.engine.store.GemFireStore$StoreAdvisee.access$000(GemFireStore.java:2501)
    at com.pivotal.gemfirexd.internal.engine.store.GemFireStore.boot(GemFireStore.java:1208)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.boot(BaseMonitor.java:2245)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.TopService.bootModule(TopService.java:314)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.startModule(BaseMonitor.java:720)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.FileMonitor.startModule(FileMonitor.java:65)
    at com.pivotal.gemfirexd.internal.iapi.services.monitor.Monitor.bootServiceModule(Monitor.java:497)
    at com.pivotal.gemfirexd.internal.engine.db.FabricDatabase.bootStore(FabricDatabase.java:2358)
    at com.pivotal.gemfirexd.internal.engine.db.FabricDatabase.boot(FabricDatabase.java:354)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.boot(BaseMonitor.java:2245)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.TopService.bootModule(TopService.java:314)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.bootService(BaseMonitor.java:2043)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.startProviderService(BaseMonitor.java:1906)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.findProviderAndStartService(BaseMonitor.java:1786)
    at com.pivotal.gemfirexd.internal.impl.services.monitor.BaseMonitor.startPersistentService(BaseMonitor.java:1196)
    at com.pivotal.gemfirexd.internal.iapi.services.monitor.Monitor.startPersistentService(Monitor.java:620)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection.bootDatabase(EmbedConnection.java:3379)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection.<init>(EmbedConnection.java:452)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection30.<init>(EmbedConnection30.java:94)
    at com.pivotal.gemfirexd.internal.impl.jdbc.EmbedConnection40.<init>(EmbedConnection40.java:75)
    at com.pivotal.gemfirexd.internal.jdbc.Driver40.getNewEmbedConnection(Driver40.java:95)
    at com.pivotal.gemfirexd.internal.jdbc.InternalDriver.connect(InternalDriver.java:351)
    at com.pivotal.gemfirexd.internal.jdbc.InternalDriver.connect(InternalDriver.java:219)
    at com.pivotal.gemfirexd.internal.jdbc.InternalDriver.connect(InternalDriver.java:195)
    at io.snappydata.jdbc.AutoloadedDriver.connect(AutoloadedDriver.java:153)
    at com.pivotal.gemfirexd.internal.engine.fabricservice.FabricServiceImpl.startImpl(FabricServiceImpl.java:279)
    at com.pivotal.gemfirexd.internal.engine.fabricservice.FabricServerImpl.start(FabricServerImpl.java:60)
    at io.snappydata.impl.LeadImpl.internalStart(LeadImpl.scala:188)
    at io.snappydata.impl.LeadImpl$.invokeLeadStart(LeadImpl.scala:489)
    at org.apache.spark.scheduler.cluster.SnappyEmbeddedModeClusterManager.initialize(SnappyEmbeddedModeClusterManager.scala:88)
    at org.apache.spark.SparkContext$.org$apache$spark$SparkContext$$createTaskScheduler(SparkContext.scala:2506)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:489)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2258)
    at org.apache.spark.sql.SparkSession$Builder$$anonfun$8.apply(SparkSession.scala:831)
    at org.apache.spark.sql.SparkSession$Builder$$anonfun$8.apply(SparkSession.scala:823)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:823)
    at com.meituan.hotel.pegasuscollect.spark.SmartConnectorMain.main(SmartConnectorMain.java:11)
    at com.meituan.hotel.pegasuscollect.controller.SparkController.getCompActualPriceModelFromCache(SparkController.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:669)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1448)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1419)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:455)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1075)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:384)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1009)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:368)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
    at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:942)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1004)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:640)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.gemstone.gemfire.SerializationException: Could not create an instance of  com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile .
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2900)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.readGfxdMessage(DSFIDFactory.java:986)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:775)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readObject(InternalDataSerializer.java:3424)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.basicReadObject(InternalDataSerializer.java:3417)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readObject(DataSerializer.java:3342)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage.fromData(UpdateAttributesProcessor.java:356)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)
Caused by: java.nio.BufferUnderflowException
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.Buffer.nextGetIndex(Buffer.java:506)
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:681)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.readInt(ByteBufferInputStream.java:190)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readInteger(DataSerializer.java:881)
    at Remote Member 'host-07(41099)<v7>:32671' in com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile.fromData(GfxdDistributionAdvisor.java:1574)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    ... 13 more
Caused by:
com.gemstone.gemfire.SerializationException: Could not create an instance of  com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile .
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2900)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.readGfxdMessage(DSFIDFactory.java:986)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:775)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readObject(InternalDataSerializer.java:3424)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.basicReadObject(InternalDataSerializer.java:3417)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readObject(DataSerializer.java:3342)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage.fromData(UpdateAttributesProcessor.java:356)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)
Caused by: java.nio.BufferUnderflowException
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.Buffer.nextGetIndex(Buffer.java:506)
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:681)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.readInt(ByteBufferInputStream.java:190)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readInteger(DataSerializer.java:881)
    at Remote Member 'host-07(41099)<v7>:32671' in com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile.fromData(GfxdDistributionAdvisor.java:1574)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    ... 13 more
Caused by:
java.nio.BufferUnderflowException
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.Buffer.nextGetIndex(Buffer.java:506)
    at Remote Member 'host-07(41099)<v7>:32671' in java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:681)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.readInt(ByteBufferInputStream.java:190)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readInteger(DataSerializer.java:881)
    at Remote Member 'host-07(41099)<v7>:32671' in com.pivotal.gemfirexd.internal.engine.distributed.GfxdDistributionAdvisor$GfxdProfile.fromData(GfxdDistributionAdvisor.java:1574)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.readGfxdMessage(DSFIDFactory.java:986)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:775)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readObject(InternalDataSerializer.java:3424)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.basicReadObject(InternalDataSerializer.java:3417)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.DataSerializer.readObject(DataSerializer.java:3342)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.cache.UpdateAttributesProcessor$UpdateAttributesMessage.fromData(UpdateAttributesProcessor.java:356)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.invokeFromData(InternalDataSerializer.java:2887)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.DSFIDFactory.create(DSFIDFactory.java:819)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.InternalDataSerializer.readDSFID(InternalDataSerializer.java:3311)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.processNIOBuffer(Connection.java:3573)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.runNioReader(Connection.java:1840)
    at Remote Member 'host-07(41099)<v7>:32671' in com.gemstone.gemfire.internal.tcp.Connection.run(Connection.java:1715)
    at Remote Member 'host-07(41099)<v7>:32671' in java.lang.Thread.run(Thread.java:745)

Here is the code:

public class SmartConnectorMain{
public static void main(String [] args){

    SparkSession spark = SparkSession
            .builder()
            .appName("SmartConnectorMainJava")
            .master("snappydata://host-01:9999,host05-:9999")
            .config("snappydata.store.locators", "host-01:9999,host-05:9999")
            .getOrCreate();

    JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());
    SnappySession snappy = new SnappySession(spark.sparkContext());

    println(" ####  Creating a table TestColumnTable  #### \n");

    snappy.dropTable("TestColumnTable",  true);

    DataSet<Row> dataFrame = snappy.range(1000).selectExpr("id", "floor(rand() * 10000) as k");

    snappy.sql("create table TestColumnTable (id bigint not null, k bigint not null) using column");

    println(" ####  Write to table completed. ### \n\n" +
            "Now you can query table TestColumnTable using $SNAPPY_HOME/bin/snappy-shell");
}

private static void println(String s){
    System.out.println(s);
}

And here is the configuration in cluster:

Name    Value
jobserver.enabled   true
snappydata.embedded true
snappydata.store.critical-heap-percentage   90.0
snappydata.store.eviction-heap-percentage   81.0
snappydata.store.host-data  true
snappydata.store.locators   host-01:9999,host-05:9999
snappydata.store.log-file   snappyleader.log
snappydata.store.mcast-port 0
snappydata.store.statistic-archive-file snappyleader.gfs
spark.app.id    snappy-app-1494920649221
spark.app.name  leaderLauncher
spark.closure.serializer    org.apache.spark.serializer.PooledKryoSerializer
spark.driver.host   10.16.118.36
spark.driver.port   25490
spark.executor.cores    10
spark.executor.id   driver
spark.master    snappydata://host-01:9999,host-05:9999
spark.scheduler.mode    FAIR
spark.serializer    org.apache.spark.serializer.PooledKryoSerializer
spark.ui.port   9411


问:
How to address Port names (PORTB etc) in an array (arduino uno)
Is it possible to put the names of ports in an array?

I'm looking something like:

```<code>const ??? my_ports_config[8]= { PORTB, PORTD, PORTB, PORTB, PORTD, PORTB, PORTB, PORTD };
</code>```

So to do (direct register bit set):

```<code>my_ports_config[i] |= _BV(7);
</code>```

Is it possible?

答: Of course you can.  The PORTB name is nothing but a handy alias, a #define for an address on the chip.  Depending on the Arduino model, that can vary of course.  The easiest way to learn these addresses is to study the datasheet for the microcontroller part on your device.  In the Atmel documentation they're always listed late in the document in a chapter called "Register Summary."  But for the Uno I think you need the  328P datasheet Check out page 615.  The 328 only has ports B C and D though, so actually setting the ports directly will probably take fewer instructions.

Body:
Is it possible to put the names of ports in an array?

I'm looking something like:

const ??? my_ports_config[8]= { PORTB, PORTD, PORTB, PORTB, PORTD, PORTB, PORTB, PORTD };

So to do (direct register bit set):

my_ports_config[i] |= _BV(7);

Is it possible?


问:
How to start a python file while Windows starts?
I have a python file and I am running the file.

If Windows is shutdown and booted up again, how I can run that file every time Windows starts?

答:
Haven't tested this, but I'd create a batch file that contains "python yourfile.py" and put that in the autostart folder.

On Windows 7 you can find it here:

```<code>%APPDATA%\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
</code>```

Body:
Haven't tested this, but I'd create a batch file that contains "python yourfile.py" and put that in the autostart folder.

On Windows 7 you can find it here:

%APPDATA%\Roaming\Microsoft\Windows\Start Menu\Programs\Startup


问:
Why are there no archives under the organizer section in xcode?
I am in the process of uploading my ios app to the app store and I clicked on the organizer button but no archives came up. All that came up was "Use the Archive command within an Xcode project or import an archive from an Xcode Server bot." Does anyone have any idea what the problem is?</p>

答:
To build your archive you need to:

1 - Set "Generic iOS Device" as the selected device (top left corner near the scheme) instead of a simulator device.

2 - Click on "Product" on the top bar, and then "Archive". This will start building your archive. When it finishes the Organizer will comes up and you will be able to see your archive.


问:
Heroku CLI suddenly broken
Suddenly, from one command to the next, the Heroic CLI stopped working. No matter what I type into the command line, I get the same error. See below.

```<code>$heroku help
 ▸    commands is not a heroku command.
 ▸    Perhaps you meant domains
 ▸    Run heroku help for a list of available commands.
 !    error getting commands pid 24643 exit 127
</code>```

What the heck is going on?

答:
This just happened to me. I fixed it by removing the heroku app the same way i installed it. I had the gem installed, so i uninstalled that.

gem uninstall heroku

Then i used homebrew to reinstall it.

brew install heroku

and it worked.

Title: Heroku CLI suddenly broken

Body:
Suddenly, from one command to the next, the Heroic CLI stopped working. No matter what I type into the command line, I get the same error. See below.

$heroku help
 ▸    commands is not a heroku command.
 ▸    Perhaps you meant domains
 ▸    Run heroku help for a list of available commands.
 !    error getting commands pid 24643 exit 127

What the heck is going on?


问:
Media-query max-width not functioning properly
Good day everybody! I am currently working on a web app, and I am using media-queries, in aims to support mobile and desktop.

I have tried to use max-width: 414px as my first break-point, to work on the current iPhones and other phones with smaller screen sizes. However, even after rereading various forum posts, responsive web design tutorials, and web documentations, to no luck, it wouldn't work the way I need it to.

See here that whenever I use max-width, even on screen sizes of 414px, or lower (I have tried), it really wouldn't work. The styles wouldn't apply.

Now, when I would use, min-width, it does work, however, I've read it's better RWD practice to use max-width for better functionality.

What are your suggestions? Thank you!

答: So I think your problem is that you are in zoom mode (like 2x or 3x). If you are in Safari responsive mode, please remember to go to use View > Actual Size , make sure it's not zoomed in in any way, as this will surely affect the media query used. Have a good day!