问:
Including an Excel file and call once packed into a jar
I have developed an ExcelReader/Writer program that is intended to be ran on other computers. In this program, it takes in an excel.xls of hard data, reads it and writes it in a formatted way to an excel.xlsx file, and then saves it in a directory "CoC-Forms".

To reduce the steps to run my program, I have included the empty .xlsx file that it writes to in the project. However, when exporting it to an executable jar (to run on other computers), I seem to be having trouble accessing this empty form. I know this is probably a very simple answer, but I have been stuck for over a full work day and it has completely halted my progress.

Here is a snippet of my environment. On the left is my Project directory in Intellij (CoC.xlsx is the empty form) and the highlights on the right are where I am attempting to access the file and where the error is happening respectively.

```<code>JOptionPane.showMessageDialog(null,"About to look for CoC");
    //fileFrom = new File(s + "/out/production/XML Reader/CoC.xlsx");
    //fileFrom = new File("/XML Reader/out/production/XML Reader/CoC.xlsx");
    //fileFrom = new File("CoC.xlsx");
    //fileFrom = new File(ExcelWriter.class.getResource("CoC.xlsx").getPath());
    CodeSource src = ExcelWriter.class.getProtectionDomain().getCodeSource();
    /*if (src != null) {
        URL url = new URL(src.getLocation(), "CoC.xlsx");
        fileFrom = new File()
        System.out.println(url);
    } else {
        JOptionPane.showMessageDialog(null,"Failed");
    } */

    fileFrom = new File(new File("."), "CoC.xlsx");
</code>```

答: I solved my problem by having people download the whole project folder, file referencing with a ../../ from point of execution, and then going deeper into the file path to find the location at which I placed the file. Choppy, but it works and solved the problem.</p>

Body:
I have developed an ExcelReader/Writer program that is intended to be ran on other computers. In this program, it takes in an excel.xls of hard data, reads it and writes it in a formatted way to an excel.xlsx file, and then saves it in a directory "CoC-Forms".

To reduce the steps to run my program, I have included the empty .xlsx file that it writes to in the project. However, when exporting it to an executable jar (to run on other computers), I seem to be having trouble accessing this empty form. I know this is probably a very simple answer, but I have been stuck for over a full work day and it has completely halted my progress.

Here is a snippet of my environment. On the left is my Project directory in Intellij (CoC.xlsx is the empty form) and the highlights on the right are where I am attempting to access the file and where the error is happening respectively.

JOptionPane.showMessageDialog(null,"About to look for CoC");
    //fileFrom = new File(s + "/out/production/XML Reader/CoC.xlsx");
    //fileFrom = new File("/XML Reader/out/production/XML Reader/CoC.xlsx");
    //fileFrom = new File("CoC.xlsx");
    //fileFrom = new File(ExcelWriter.class.getResource("CoC.xlsx").getPath());
    CodeSource src = ExcelWriter.class.getProtectionDomain().getCodeSource();
    /*if (src != null) {
        URL url = new URL(src.getLocation(), "CoC.xlsx");
        fileFrom = new File()
        System.out.println(url);
    } else {
        JOptionPane.showMessageDialog(null,"Failed");
    } */

    fileFrom = new File(new File("."), "CoC.xlsx");


来源: stackexchange

问:
Angular4: router, children (optional) parameters
So, I am looking to produce paths like these:

matches/:page/:team/:season

where :team and :season are optional parameters
so I could have an url like

```<code>matches/results/4/2017 or
matches/results/4 or
matches/results
</code>```

all should be valid and come through in this.route.snapshot.params

I tried this:

```<code>  {path: 'matches', children: [
    {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
    {path: 'competitions', component: CompetitionsPageComponent},
    {path: ':page', component: PageComponent, children: [
      {path: ':team', children:[
          {path: ':season', children:[]}
      ]}
    ]},
  ]},
</code>```

with no luck, only :page comes through as param

答:
I think something you want to think about are you really wanting child routes or just the same page or each level?  The other example will end up rendering both components ... which might be what you want, but if not then you might spell out each one.

```<code>{ path: 'matches/results/', component: ResultsComponent, },
{ path: 'matches/results/:page/', component: PageComponent, },
{ path: 'matches/results/:page/:team/', component: TeamComponent, },
{ path: 'matches/results/:page/:team/:season', component: PageComponent, },
</code>```

also note the name you use in the path is the name you need to use in the param selector:

```<code>params['page']
params['team']
params['season']
</code>```

example code

```<code>this.route.params.subscribe((params) => {
    this.teamService.getTeam(params['team']).subscribe((team) => {
        this.team = team;
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So, I am looking to produce paths like these:

matches/:page/:team/:season

where :team and :season are optional parameters
so I could have an url like

matches/results/4/2017 or
matches/results/4 or
matches/results

all should be valid and come through in this.route.snapshot.params

I tried this:

  {path: 'matches', children: [
    {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
    {path: 'competitions', component: CompetitionsPageComponent},
    {path: ':page', component: PageComponent, children: [
      {path: ':team', children:[
          {path: ':season', children:[]}
      ]}
    ]},
  ]},

with no luck, only :page comes through as param

Body:
I think something you want to think about are you really wanting child routes or just the same page or each level?  The other example will end up rendering both components ... which might be what you want, but if not then you might spell out each one.

{ path: 'matches/results/', component: ResultsComponent, },
{ path: 'matches/results/:page/', component: PageComponent, },
{ path: 'matches/results/:page/:team/', component: TeamComponent, },
{ path: 'matches/results/:page/:team/:season', component: PageComponent, },

also note the name you use in the path is the name you need to use in the param selector:

params['page']
params['team']
params['season']

example code

this.route.params.subscribe((params) => {
    this.teamService.getTeam(params['team']).subscribe((team) => {
        this.team = team;
    });
});


问:
Are consecutive anchors with the same name allowed in div elements if one div is display:none?
I'm creating a page that has two div elements directly above a bit of text that I want to create an anchor to. One of the div elements is display:none above a certain screen size, while the other div element is display:block, like so:

```<code><div class="hidden"><!-- This div class is set to display:none; in CSS -->
<!-- Div content -->
</div>
<div class="show"><!-- This div class is set to display:none; in CSS -->
<!-- Div content -->
</div>
<a name="anchor"></a>
<h2>Paragraph heading</h2>
<p>Paragraph that I want to anchor to</p>
</code>```

When I put the anchor as shown in the above example, it actually appears below the paragraph heading. Is it allowed to put two anchors of the same name, if one of the divs is display:none, like this:

```<code><div class="hidden">
<!-- Div content -->
<a name="anchor"></a>
</div>
<div class="show">
<!-- Div content -->
<a name="anchor"></a>
</div>
<h2>Paragraph heading</h2>
<p>Paragraph that I want to anchor to</p>
</code>```

Is there a way something like this is allowed? I have tested this, and the link to the anchor appears not to work -- is the HTML markup from the display:none div conflicting with the one in the display:block div, even if the one div element is not displayed by the browser?

The only example I could find on Stack Overflow was here: Anchor to element within hidden div , and it seemed to relate more to javascript toggle than my question. Please let me know if there are answers elsewhere.

答:
No. See the specification

If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home subtree.

It must be unique in the document. How you style elements around it has no bearing on that rule.

The spec also says:

Authors should not specify the name attribute on a elements.

The name attribute on a elements was superseded when HTML 4 was released in 1996 and introduced the id attribute (on any element, not just on anchors).

id must also be unique in a document though.

Body:
I'm creating a page that has two div elements directly above a bit of text that I want to create an anchor to. One of the div elements is display:none above a certain screen size, while the other div element is display:block, like so:

Paragraph heading

Paragraph that I want to anchor to

When I put the anchor as shown in the above example, it actually appears below the paragraph heading. Is it allowed to put two anchors of the same name, if one of the divs is display:none, like this:

Paragraph heading

Paragraph that I want to anchor to

Is there a way something like this is allowed? I have tested this, and the link to the anchor appears not to work -- is the HTML markup from the display:none div conflicting with the one in the display:block div, even if the one div element is not displayed by the browser?

The only example I could find on Stack Overflow was here: Anchor to element within hidden div , and it seemed to relate more to javascript toggle than my question. Please let me know if there are answers elsewhere.


问:
Can't create RLS on postgresql
I created a login role in Postgres then I tried to give permissions to modify specified rows on a table using row level security. I've tried thousands times but it doesn't work. I have only one table.

答:
You didn't give enough information on what steps you took to come to your conclusion that it doesn't work, so I'll cover both cases:

You created policy, but didn't enable RLS on table. From documentation:

Note that row-level security must be enabled on the table (using ALTER TABLE ... ENABLE ROW LEVEL SECURITY) in order for created policies to be applied.

You are testing RLS using owner role, superuser role or role that inherits privileges from one of those. They bypass RLS by default. You can force RLS on table owner by ALTER TABLE [..] FORCE ROW LEVEL SECURITY, but you can't do that for superuser.

Title: Can't create RLS on postgresql


问:
MongoError: failed to connect to server [localhost:27017]
This is my db.js:

```<code>import mongoose from 'mongoose';
export default () => {
 mongoose.Promise = global.Promise;
 mongoose.connect('mongodb://localhost/meetupapp');
 mongoose.connection
     .once('open', () => console.log('Mongodb running'))
    .on('error', err => console.error(err));
};
</code>```

and this is the error message: MongoError: failed to connect to server [localhost:27017] on first connect]
  name: 'MongoError

I've installed mongodb!

答:
Verify your mongodb engine is running or not

WINDOWS

1.) Open command prompt
2.) Type mongo

if it works that means mongod is running or else you have to start it manually

COMMAND

```<code>mongod --dbpath [path-of-your-database]
</code>```

create folder where you want to store the database and assign that folderpath in --dbpath

Ex "c:/mongo/db/"

and then try mongo command and it will work..

LINUX

COMMAND

```<code>1.) sudo service mongod start
</code>```

MAC

After installing mongodb

COMMAND

```<code>1.) export PATH=<mongodb-install-directory>/bin:$PATH  [Setting the environment variable]
2.) mkdir -p /data/db   [creating directory for data to store]
3.) mongod --dbpath [path-of-your-database]
</code>```

Body:
This is my db.js:

import mongoose from 'mongoose';
export default () => {
 mongoose.Promise = global.Promise;
 mongoose.connect('mongodb://localhost/meetupapp');
 mongoose.connection
     .once('open', () => console.log('Mongodb running'))
    .on('error', err => console.error(err));
};

and this is the error message: MongoError: failed to connect to server [localhost:27017] on first connect]
  name: 'MongoError

I've installed mongodb!

Body:
Verify your mongodb engine is running or not

WINDOWS

1.) Open command prompt
2.) Type mongo

if it works that means mongod is running or else you have to start it manually

COMMAND

mongod --dbpath [path-of-your-database]

create folder where you want to store the database and assign that folderpath in --dbpath

Ex "c:/mongo/db/"

and then try mongo command and it will work..

LINUX

COMMAND

1.) sudo service mongod start

MAC

After installing mongodb

COMMAND

1.) export PATH=<mongodb-install-directory>/bin:$PATH  [Setting the environment variable]
2.) mkdir -p /data/db   [creating directory for data to store]
3.) mongod --dbpath [path-of-your-database]


问:
Formatting URLs in list to all have a trailing slash in python
There's some similar questions to this on stackoverflow but none do exactly what I want and my various attempts seem to fail.

I have a list of urls, some have trailing slash, others not... I want to check them and add a slash to those that don't.

```<code>url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

for url in url_list:
    if url[len(url)-1] != "/":
        url = url + "/"
    else:
        url = url

print url_list
</code>```

returns the same list (last two urls still don't have a trailing slash)

```<code>['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']
</code>```

why isn't it working? any ideas?

thanks :)

答:
The reason why your changes don't work is that when you say url = url + "/" this doesn't edit url in-place in the list. If you want to do it this way, you might be better using enumerate:

```<code>for i, url in enumerate(url_list):
    if url[len(url)-1] != "/":
        url_list[i] = url + "/"

print url_list
</code>```

We could neaten this further by changing url[len(url)-1] to url[-1], which refers to the last character.

But while we're at it, why not use .endswith() and a list comprehension?

```<code>url_list = [u if u.endswith('/') else u + '/' for u in url_list]
</code>```

Body:
There's some similar questions to this on stackoverflow but none do exactly what I want and my various attempts seem to fail.

I have a list of urls, some have trailing slash, others not... I want to check them and add a slash to those that don't.

url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

for url in url_list:
    if url[len(url)-1] != "/":
        url = url + "/"
    else:
        url = url

print url_list

returns the same list (last two urls still don't have a trailing slash)

['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

why isn't it working? any ideas?

thanks :)

Body:
The reason why your changes don't work is that when you say url = url + "/" this doesn't edit url in-place in the list. If you want to do it this way, you might be better using enumerate:

for i, url in enumerate(url_list):
    if url[len(url)-1] != "/":
        url_list[i] = url + "/"

print url_list

We could neaten this further by changing url[len(url)-1] to url[-1], which refers to the last character.

But while we're at it, why not use .endswith() and a list comprehension?

url_list = [u if u.endswith('/') else u + '/' for u in url_list]


问:
Send string to python websocket using JavaScript
I have a locally running python websocket (code below) which I let run infinitely. I mainly copied the code from an example. The example uses another python client script to send data to it (also below). That simply works like a charm and is very simple; just what I need since I have some experience in Python but no clue about the 'web/internet'-thingies.

Now, in stead of using the python client, I'd like to send a message from an html document by javascript. Is there any guidance into a short piece of 'stupid' code, just sending one message (string) to the python websocketserver? The python script would then be able to execute different processes using this data.

Python server: (works :) )

```<code>from socket import *

host = "localhost"
port = 8089
buf = 1024
addr = (host,port)

sock = socket(AF_INET,SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(addr)

print "Websocket active."
print "address:\t"+host+":"+str(port)

while 1:
    data,addr = sock.recvfrom(buf)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", data,"'"

# Close socket
sock.close()
</code>```

Python Client ( works, but not needed)

```<code>from socket import *

host = "localhost"
port = 8089
buf = 1024
addr = (host,port)

sock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg

while (1):
    data = raw_input('>> ')
    if not data:
        break
    else:
        if(sock.sendto(data,addr)):
            print "Sending message '",data,"'....."

sock.close()
</code>```

And now towards the Javascript client..

Can't it be as simple as this? ;

```<code>var socket = new WebSocket("ws://localhost:8089");
socket.onopen = function () {
    alert("alerting you");
    socket.send('Pingel');
};
</code>```

答:
Your Python server implements a regular TCP server, but your JS code is acting as a WebSocket client, which is an actual proper protocol on top of TCP: https://www.rfc-editor.org/rfc/rfc6455

If you want both ends to communicate properly, you need to run a WebSocket server, like this: https://github.com/dpallot/simple-websocket-server

Body:
I have a locally running python websocket (code below) which I let run infinitely. I mainly copied the code from an example. The example uses another python client script to send data to it (also below). That simply works like a charm and is very simple; just what I need since I have some experience in Python but no clue about the 'web/internet'-thingies.

Now, in stead of using the python client, I'd like to send a message from an html document by javascript. Is there any guidance into a short piece of 'stupid' code, just sending one message (string) to the python websocketserver? The python script would then be able to execute different processes using this data.

Python server: (works :) )

from socket import *

host = "localhost"
port = 8089
buf = 1024
addr = (host,port)

sock = socket(AF_INET,SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(addr)

print "Websocket active."
print "address:\t"+host+":"+str(port)

while 1:
    data,addr = sock.recvfrom(buf)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", data,"'"

# Close socket
sock.close()

Python Client ( works, but not needed)

from socket import *

host = "localhost"
port = 8089
buf = 1024
addr = (host,port)

sock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg

while (1):
    data = raw_input('>> ')
    if not data:
        break
    else:
        if(sock.sendto(data,addr)):
            print "Sending message '",data,"'....."

sock.close()

And now towards the Javascript client..

Can't it be as simple as this? ;

var socket = new WebSocket("ws://localhost:8089");
socket.onopen = function () {
    alert("alerting you");
    socket.send('Pingel');
};


问:
Split XML into different XML using xslt with different number of tags
This is a sample xml that I have to break into multiple files.
I had tried many ways using result-document and group, but in all example split was equally distributed.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Sample>
   <A>
      <para>A A A A A A A</para>
   </A>
   <B>
      <para>B B B B B B B</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
   </B>
   <C>
      <para>C C C C C C C</para>
   </C>
   <D>
      <para>D D D D D D D</para>
   </D>
   <G>
      <para>GGGGGGGGGGGGGGGG</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
   </G>
   <E>
      <para>E E E E E E E E E</para>
   </E>
   <F>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
      <para>F F F F F F F F F</para>
   </F>
   <G>
      <para>GGGGGGGGGGGGGGGG</para>
   </G>
   <H>
      <para>H H H H H H H</para>
   </H>
   <I>
      <para>I I I I I I I</para>
   </I>
   <H>
      <para>H H H H H H H</para>
   </H>
</Sample>
</code>```

I have to split the main XML based on group :

ABCD

EF

G

H

I

*In this XML G & H is appearing 2 times so i have to consider them as different groups.

Output1.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<split>
   <A>
      <para>A A A A A A A</para>
   </A>
   <B>
      <para>B B B B B B B</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
   </B>
   <C>
      <para>C C C C C C C</para>
   </C>
   <D>
      <para>D D D D D D D</para>
   </D>
</split>
</code>```

Output2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<split>
   <G>
      <para>GGGGGGGGGGGGGGGG</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
   </G>
</split>
</code>```

Output3.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<split>
    <G>
        <para>
            GGGGGGGGGGGGGGGG
        </para>
    </G>
</split>
</code>```

These are just 3 output file. Other are same in this way. Output files should also have a root tag, I have used split tag as a root tag.

答:
One way to solve that might be using group-starting-with="*[local-name() = $start-group-with]" where the parameter is defined as a sequence of element names <xsl:param name="start-group-with" as="xs:string+" select="'A', 'E', 'G', 'H', 'I'"/> to start a group:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:param name="start-group-with" as="xs:string+" select="'A', 'E', 'G', 'H', 'I'"/>

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes"/>

    <xsl:template match="/*">
        <xsl:for-each-group select="*" group-starting-with="*[local-name() = $start-group-with]">
            <xsl:result-document href="split-group-{position()}-key-{local-name()}.xml">
                <Split>
                    <xsl:copy-of select="current-group()"/>
                </Split>
            </xsl:result-document>
        </xsl:for-each-group>
    </xsl:template>

</xsl:stylesheet>
</code>```

That would of course group A elements with any elements following before a 'E', 'G', 'H', 'I' follows, but you haven't precisely described what are the criteria, for your example input that would group the adjacent A, B, C, D elements together, as E and F, as well as putting each G, H and I into its own group/file.

Body:
This is a sample xml that I have to break into multiple files.
I had tried many ways using result-document and group, but in all example split was equally distributed.

<?xml version="1.0" encoding="UTF-8"?>
<Sample>

      <para>A A A A A A A</para>

      <para>B B B B B B B</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>

   <C>
      <para>C C C C C C C</para>
   </C>
   <D>
      <para>D D D D D D D</para>
   </D>
   <G>
      <para>GGGGGGGGGGGGGGGG</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
   </G>
   <E>
      <para>E E E E E E E E E</para>
   </E>
   <F>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
      <para>F F F F F F F F F</para>
   </F>
   <G>
      <para>GGGGGGGGGGGGGGGG</para>
   </G>
   <H>
      <para>H H H H H H H</para>
   </H>

      <para>I I I I I I I</para>

   <H>
      <para>H H H H H H H</para>
   </H>
</Sample>

I have to split the main XML based on group :

ABCD

EF

G

H

I

*In this XML G & H is appearing 2 times so i have to consider them as different groups.

Output1.xml

<?xml version="1.0" encoding="UTF-8"?>
<split>

      <para>A A A A A A A</para>

      <para>B B B B B B B</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>

   <C>
      <para>C C C C C C C</para>
   </C>
   <D>
      <para>D D D D D D D</para>
   </D>
</split>

Output2.xml

<?xml version="1.0" encoding="UTF-8"?>
<split>
   <G>
      <para>GGGGGGGGGGGGGGGG</para>
      <child1level1>
         <para>first child first level</para>
         <child1level2>
            <para>second level child</para>
         </child1level2>
      </child1level1>
      <child2level1>
         <para>second child first level</para>
      </child2level1>
   </G>
</split>

Output3.xml

<?xml version="1.0" encoding="UTF-8"?>
<split>
    <G>
        <para>
            GGGGGGGGGGGGGGGG
        </para>
    </G>
</split>

These are just 3 output file. Other are same in this way. Output files should also have a root tag, I have used split tag as a root tag.

Body:
One way to solve that might be using group-starting-with="*[local-name() = $start-group-with]" where the parameter is defined as a sequence of element names <xsl:param name="start-group-with" as="xs:string+" select="'A', 'E', 'G', 'H', 'I'"/> to start a group:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:param name="start-group-with" as="xs:string+" select="'A', 'E', 'G', 'H', 'I'"/>

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes"/>

    <xsl:template match="/*">
        <xsl:for-each-group select="*" group-starting-with="*[local-name() = $start-group-with]">
            <xsl:result-document href="split-group-{position()}-key-{local-name()}.xml">
                <Split>
                    <xsl:copy-of select="current-group()"/>
                </Split>
            </xsl:result-document>
        </xsl:for-each-group>
    </xsl:template>

</xsl:stylesheet>

That would of course group A elements with any elements following before a 'E', 'G', 'H', 'I' follows, but you haven't precisely described what are the criteria, for your example input that would group the adjacent A, B, C, D elements together, as E and F, as well as putting each G, H and I into its own group/file.


问:
java actionlistener on a tab
Is it possible to put an actionlistener on a tab in swing? If it is please could you post a small example?</p>

答: The only way to do that is to add a javax.swing.event.ChangeListener to the JTabbedPane itself.  You might have to keep track of the selected tab vs. previously selected tab depending on what you are doing with the state change...

Title: java actionlistener on a tab

ContentLicense: CC BY-SA 2.5


问:
Difference between MQTT and MODBUS protocol?
I've been reading about these two protocols lately and wasn't quite able to understand why to use MQTT when we have MODBUS (or vice versa).

Since, MODBUS is used to transmit data over serial communication between PLC's under low bandwidths, but as far as i understood, MQTT does the same using its PUBLISH/SUBSCRIBE methodology (I know MQTT uses a broker and MODBUS doesn't, but that's not the point).

Can somebody provide a clear distinction between them?

答:
Normal Modbus is a serial communications protocol often used for connecting industrial electronic devices.

MQTTis a messaging protocol for use on top of the TCP/IP protocol often used for sending measurements from electronic devices to another party.

Maybe this link help a bit.
A Comparison of IoT Gateway Protocols: MQTT and Modbus


问:
Most efficient way to select point with the most surrounding points
N.B: there's a major edit at the bottom of the question - check it out

Question

Say I have a set of points:

I want to find the point with the most points surrounding it, within radius  (ie a circle) or within  (ie a square) of the point for 2 dimensions. I'll refer to it as the densest point function.

For the diagrams in this question, I'll represent the surrounding region as circles. In the image above, the middle point's surrounding region is shown in green. This middle point has the most surrounding points of all the points within radius  and would be returned by the densest point function.

What I've tried

A viable way to solve this problem would be to use a range searching solution; this answer explains further and that it has " worst-case time". Using this, I could get the number of points surrounding each point and choose the point with largest surrounding point count.

However, if the points were extremely densely packed (in the order of a million), as such:

then each of these million points () would need to have a range search performed. The worst-case time , where  is the number of points returned in the range, is true for the following point tree types:

kd-trees of two dimensions (which are actually slightly worse, at ),

2d-range trees,

Quadtrees, which have a worst-case time of

So, for a group of  points within radius  of all points within the group, it gives complexity of  for each point. This yields over a trillion operations!

Any ideas on a more efficient, precise way of achieving this, so that I could find the point with the most surrounding points for a group of points, and in a reasonable time (preferably  or less)?

EDIT

Turns out that the method above is correct! I just need help implementing it.

(Semi-)Solution

If I use a 2d-range tree:

A range reporting query costs , for  returned points,

For a range tree with fractional cascading (also known as layered range trees) the complexity is ,

For 2 dimensions, that is ,

Furthermore, if I perform a range counting query (i.e., I do not report each point), then it costs .

I'd perform this on every point - yielding the  complexity I desired!

Problem

However, I cannot figure out how to write the code for a counting query for a 2d layered range tree.

I've found a great resource (from page 113 onwards) about range trees, including 2d-range tree psuedocode. But I can't figure out how to introduce fractional cascading, nor how to correctly implement the counting query so that it is of O(log n) complexity.

I've also found two range tree implementations here and here in Java, and one in C++ here, although I'm not sure this uses fractional cascading as it states above the countInRange method that

It returns the number of such points in worst case
      * O(log(n)^d) time. It can also return the points that are in the rectangle in worst case
      * O(log(n)^d + k) time where k is the number of points that lie in the rectangle.

which suggests to me it does not apply fractional cascading.

Refined question

To answer the question above therefore, all I need to know is if there are any libraries with 2d-range trees with fractional cascading that have a range counting query of complexity  so I don't go reinventing any wheels, or can you help me to write/modify the resources above to perform a query of that complexity?

Also not complaining if you can provide me with any other methods to achieve a range counting query of 2d points in  in any other way!

答:
I suggest using plane sweep algorithm. This allows one-dimensional range queries instead of 2-d queries. (Which is more efficient, simpler, and in case of square neighborhood does not require fractional cascading):

Sort points by Y-coordinate to array S.

Advance 3 pointers to array S: one (C) for currently inspected (center) point; other one, A (a little bit ahead) for nearest point at distance > R below C; and the last one, B (a little bit behind) for farthest point at distance < R above it.

Insert points pointed by A to Order statistic tree (ordered by coordinate X) and remove points pointed by B from this tree. Use this tree to find points at distance R to the left/right from C and use difference of these points' positions in the tree to get number of points in square area around C.

Use results of previous step to select "most surrounded" point.

This algorithm could be optimized if you rotate points (or just exchange X-Y coordinates) so that width of the occupied area is not larger than its height. Also you could cut points into vertical slices (with R-sized overlap) and process slices separately - if there are too many elements in the tree so that it does not fit in CPU cache (which is unlikely for only 1 million points). This algorithm (optimized or not) has time complexity O(n log n).

For circular neighborhood (if R is not too large and points are evenly distributed) you could approximate circle with several rectangles:

In this case step 2 of the algorithm should use more pointers to allow insertion/removal to/from several trees. And on step 3 you should do a linear search near points at proper distance (<=R) to distinguish points inside the circle from the points outside it.

Other way to deal with circular neighborhood is to approximate circle with rectangles of equal height (but here circle should be split into more pieces). This results in much simpler algorithm (where sorted arrays are used instead of order statistic trees):

Cut area occupied by points into horizontal slices, sort slices by Y, then sort points inside slices by X.

For each point in each slice, assume it to be a "center" point and do step 3.

For each nearby slice use binary search to find points with Euclidean distance close to R, then use linear search to tell "inside" points from "outside" ones. Stop linear search where the slice is completely inside the circle, and count remaining points by difference of positions in the array.

Use results of previous step to select "most surrounded" point.

This algorithm allows optimizations mentioned earlier as well as fractional cascading.


问:
WCF Service cant seem to return Object to Form Application
I am trying to make a WCF-service in Visual Studio with a windows form application as a client.

The problem is that I can't seem to receive the data from  my service when calling the method (I would like to get an object of Customer returned) -
the data has to be stored within the service, no database. (Is this possible? no database?)

Here is MyService.cs:

```<code> public class MyService : IMyService
{
    Store store = new Store();

public void RegisterCustomer(string name, string pass)
    {
        Customer c = new Customer(name, pass);
        store.Customers.Add(c);
    }

  public Customer GetCustomer(string name)
    {
        Customer c = new Customer();
        foreach(Customer i in store.Customers)
        {
            if (i.UserName.Equals(name))
            {
                c = i;
            }
        }
        return c;
    }
</code>```

The operations and datamembers are declared in the IMyService Interface

```<code>namespace WcfService
{
[ServiceContract]
public interface IMyService
{
 [OperationContract]
    // register - klant bestaat niet --> voeg toe aan klantenlijst -1.1-
    void RegisterCustomer(string name, string pass);

 [OperationContract]
    // login - klant bestaat niet --> voeg toe aan klantenlijst
    Customer GetCustomer(string name);

 [DataContract]
public class Customer
{
    string username;
    string password;
    int saldo;

    [DataMember]
    public string UserName { get{ return username; }set{ username = value; }
    }

    [DataMember]
    public string Password{get { return password; }set { password = value; }
    }

    [DataMember]
    public int Saldo{get { return saldo; }set { saldo = value; }
    }
    public Customer() { }

    public Customer(string name, string pass)
    {
        this.username = name;
        this.password = pass;
        this.saldo = 100;
    }
}
</code>```

our reference inside the form1: form

```<code>//reference
    ServiceReference1.MyServiceClient client = new ServiceReference1.MyServiceClient();
</code>```

The form app that makes the call to the service

```<code>private void button2_Click(object sender, EventArgs e)
    {
        string name = textBox4.Text;
        string pass;

        if (client.CustomerExists(name))
        {
            label9.Text = "De opgegeven naam bestaat al";
        }
        else {
            pass = client.CreatePass(name); // does work
            client.RegisterCustomer(name,pass);    // does not work

            Customer c = client.GetCustomer(name); // does not work
            label9.Text = "welkom: " + c.UserName + "\njouw pass: " +c.Password;
        } }
</code>```

This line of code should return me the object of Customer... but it does not.

```<code>Customer c = client.GetCustomer(name); // does not work
</code>```

答:
Solution:

The InstanceContextMode was indeed the problem:

```<code>[ServiceBehavior(InstanceContextMode= InstanceContextMode.Single)]
</code>```

This is wrong:

```<code> public class MyService : IMyService{
    Store store = new Store();

    //your methods here

}
</code>```

This is right:

```<code>[ServiceBehavior(InstanceContextMode= InstanceContextMode.Single)]
    Store store = new Store();

    //your methods here

}
</code>```

+1 to Marco

Body:
I am trying to make a WCF-service in Visual Studio with a windows form application as a client.

The problem is that I can't seem to receive the data from  my service when calling the method (I would like to get an object of Customer returned) -
the data has to be stored within the service, no database. (Is this possible? no database?)

Here is MyService.cs:

 public class MyService : IMyService
{
    Store store = new Store();

public void RegisterCustomer(string name, string pass)
    {
        Customer c = new Customer(name, pass);
        store.Customers.Add(c);
    }

  public Customer GetCustomer(string name)
    {
        Customer c = new Customer();
        foreach(Customer i in store.Customers)
        {
            if (i.UserName.Equals(name))
            {
                c = i;
            }
        }
        return c;
    }

The operations and datamembers are declared in the IMyService Interface

namespace WcfService
{
[ServiceContract]
public interface IMyService
{
 [OperationContract]
    // register - klant bestaat niet --> voeg toe aan klantenlijst -1.1-
    void RegisterCustomer(string name, string pass);

 [OperationContract]
    // login - klant bestaat niet --> voeg toe aan klantenlijst
    Customer GetCustomer(string name);

 [DataContract]
public class Customer
{
    string username;
    string password;
    int saldo;

    [DataMember]
    public string UserName { get{ return username; }set{ username = value; }
    }

    [DataMember]
    public string Password{get { return password; }set { password = value; }
    }

    [DataMember]
    public int Saldo{get { return saldo; }set { saldo = value; }
    }
    public Customer() { }

    public Customer(string name, string pass)
    {
        this.username = name;
        this.password = pass;
        this.saldo = 100;
    }
}

our reference inside the form1: form

//reference
    ServiceReference1.MyServiceClient client = new ServiceReference1.MyServiceClient();

The form app that makes the call to the service

private void button2_Click(object sender, EventArgs e)
    {
        string name = textBox4.Text;
        string pass;

        if (client.CustomerExists(name))
        {
            label9.Text = "De opgegeven naam bestaat al";
        }
        else {
            pass = client.CreatePass(name); // does work
            client.RegisterCustomer(name,pass);    // does not work

            Customer c = client.GetCustomer(name); // does not work
            label9.Text = "welkom: " + c.UserName + "\njouw pass: " +c.Password;
        } }

This line of code should return me the object of Customer... but it does not.

Customer c = client.GetCustomer(name); // does not work

Body:
Solution:

The InstanceContextMode was indeed the problem:

[ServiceBehavior(InstanceContextMode= InstanceContextMode.Single)]

This is wrong:

 public class MyService : IMyService{
    Store store = new Store();

    //your methods here

}

This is right:

[ServiceBehavior(InstanceContextMode= InstanceContextMode.Single)]
    Store store = new Store();

    //your methods here

}

+1 to Marco


问:
How to serialize a Marshmallow field under a different name
I want a Marshmallow Schema  with the following output json -

```<code>{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}
</code>```

Marshmallow doesn't serialize private members so this is as close as I can get -

```<code>class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()
</code>```

But I do need the underscores in the output json.

Is there a way to tell Marshmallow to serialize the fields using different names?

答:
The answer's well documented in Marshmallows api reference.

I need to use dump_to :

```<code>class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number(dump_to='_time')
    id = fields.String(dump_to='_id')
</code>```

Body:
I want a Marshmallow Schema  with the following output json -

{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}

Marshmallow doesn't serialize private members so this is as close as I can get -

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

But I do need the underscores in the output json.

Is there a way to tell Marshmallow to serialize the fields using different names?

Body:
The answer's well documented in Marshmallows api reference.

I need to use dump_to :

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number(dump_to='_time')
    id = fields.String(dump_to='_id')


问:
Recursive way to find number of items in a object of array
What is the recursive way to get the number of titi in the following object :

```<code>{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}
</code>```

Expected result is the total. In this example : 7.

答:
var data = {
  titi: "h0",
  history: [{
    titi: "h1",
    history: [{
      titi: "h11"
    }, {
      titi: "h12"
    }]
  }, {
    titi: "h12",
    history: [{
      titi: "h121"
    }, {
      titi: "h122"
    }]
  }]
}

var numberOfTiti = 0;
function process (obj) {
  for (var index in obj) {
    if (index === 'titi') {
      numberOfTiti++;
    }
    if (typeof obj[index] === 'object') {
      process(obj[index]);
    }
  }
}

process(data);
console.log(numberOfTiti);```

Body:
What is the recursive way to get the number of titi in the following object :

{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}

Expected result is the total. In this example : 7.


问:
Using recordselect gem, how can I specify scope or selection parameters?
My Users model has a boolean field show_in_list. I'm using a recordselect widget to present a popup selection window that allows paging through a potentially lengthy list of users.

```<code><%= record_multi_select_field ‘users’, @selected_users,
:controller => ‘/users’, :params => {'show_in_list' => true} %>
</code>```

The first data fetch URL includes the show_in_list=true parameter and yields the correct (limited) set of users.

```<code>/reports/users/browse?show_in_list=true&search=
</code>```

However, clicking the Next button causes a fetch without that parameter resulting in browsing the entire set of users.

```<code>/reports/users/browse?page=2&search=&update=1
</code>```

Is there a way to configure recordselect to work around this apparent bug? Or can I pass the parameter differently or use a scope somehow?

rails (4.2)
active_scaffold (3.4.99)
recordselect (3.6.0)

答:
This is, indeed, a bug in recordselect 3.6.0. The fix was merged here.

Use

gem 'recordselect', :git => 'https://github.com/scambra/recordselect.git'

in your Gemfile to include the pre-release version with the fix, until a new >3.6.0 release is cut.

Body:
My Users model has a boolean field show_in_list. I'm using a recordselect widget to present a popup selection window that allows paging through a potentially lengthy list of users.

<%= record_multi_select_field ‘users’, @selected_users,
:controller => ‘/users’, :params => {'show_in_list' => true} %>

The first data fetch URL includes the show_in_list=true parameter and yields the correct (limited) set of users.

/reports/users/browse?show_in_list=true&search=

However, clicking the Next button causes a fetch without that parameter resulting in browsing the entire set of users.

/reports/users/browse?page=2&search=&update=1

Is there a way to configure recordselect to work around this apparent bug? Or can I pass the parameter differently or use a scope somehow?

rails (4.2)
active_scaffold (3.4.99)
recordselect (3.6.0)


问:
Explode array data into rows in spark
I have a dataset in the following way:

```<code>FieldA    FieldB    ArrayField
1         A         {1,2,3}
2         B         {3,5}
</code>```

I would like to explode the data on ArrayField so the output will look in the following way:

```<code>FieldA    FieldB    ExplodedField
1         A         1
1         A         2
1         A         3
2         B         3
2         B         5
</code>```

I mean I want to generate an output line for each item in the array the in ArrayField while keeping the values of the other fields.

How would you implement it in Spark.
Notice that the input dataset is very large.

Title: Explode array data into rows in spark

Body:
I have a dataset in the following way:

FieldA    FieldB    ArrayField
1         A         {1,2,3}
2         B         {3,5}

I would like to explode the data on ArrayField so the output will look in the following way:

FieldA    FieldB    ExplodedField
1         A         1
1         A         2
1         A         3
2         B         3
2         B         5

I mean I want to generate an output line for each item in the array the in ArrayField while keeping the values of the other fields.

How would you implement it in Spark.
Notice that the input dataset is very large.

Body:
The explode function should get that done.

pyspark version:

>>> df = spark.createDataFrame([(1, "A", [1,2,3]), (2, "B", [3,5])],["col1", "col2", "col3"])
>>> from pyspark.sql.functions import explode
>>> df.withColumn("col3", explode(df.col3)).show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   A|   1|
|   1|   A|   2|
|   1|   A|   3|
|   2|   B|   3|
|   2|   B|   5|
+----+----+----+

Scala version

scala> val df = Seq((1, "A", Seq(1,2,3)), (2, "B", Seq(3,5))).toDF("col1", "col2", "col3")
df: org.apache.spark.sql.DataFrame = [col1: int, col2: string ... 1 more field]

scala> df.withColumn("col3", explode($"col3")).show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   A|   1|
|   1|   A|   2|
|   1|   A|   3|
|   2|   B|   3|
|   2|   B|   5|
+----+----+----+


问:
AngularJS Unknown Provider Error Message
I have an angular app that will not load and is returning the error message:

Error: [$injector:unpr] Unknown provider: navigatorProvider <-
  navigator <- LayoutController

This is ever since I introduced a service I have this registered on the controller, but it still not working. The controller referenced is:

```<code>(function () {
    "use strict";
    angular.module("HtJobPortal").controller("LayoutController",LayoutController);

    LayoutController.$inject = ["$scope", "navigator"];

    function LayoutController($scope, navigator){
        var layout = this;

        // Layout
        layout.loadTemplate = function() {
            return navigator.loadTemplate();
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    }

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

This is the service:

```<code>(function() {

    var navigator = angular.module('navigator', []);
    navigator.factory('loadTemplate', function () {
        var loadTemplate = this;

        // Page Directory
        navigator.login = "templates/login.html";
        navigator.dashboard = "templates/dashboard.html";
        navigator.job = "templates/job.html";

        // Template switcher
        navigator.loadTemplate = function () {
            return navigator.login;
        }

        return loadTemplate;
    });

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

And the app page just in case I've missed something there:

```<code>(function () {
    'use strict';

    angular.module('HtJobPortal', []);
})();
</code>```

答:
To create a factory\service\controllers , you generally don't require a new module every time. It's preferred to declare one module and register your controller\factory\services to same.

In your case, you can do it like:

```<code>(function() {
    angular.module('HtJobPortal', [..define other module dependency here..]);
    angular.module('HtJobPortal')
   .factory('loadTemplate', function () {
        var loadTemplate = {};
        // Page Directory
        loadTemplate.login = "templates/login.html";
        loadTemplate.dashboard = "templates/dashboard.html";
        loadTemplate.job = "templates/job.html";

        // Template switcher
        loadTemplate.loadTemplate = function () {
            return loadTemplate .login;
        }
        return loadTemplate; // return object from factory
    })
    .controller("LayoutController",LayoutController);
    LayoutController.$inject = ["$scope", "loadTemplate"]; //inject factory
    function LayoutController($scope, loadTemplate){
        var layout = this;
        // Layout
        layout.loadTemplate = function() {
            return loadTemplate.loadTemplate(); // call factory method
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    };
}());
</code>```

Body:
I have an angular app that will not load and is returning the error message:

Error: [$injector:unpr] Unknown provider: navigatorProvider <-
  navigator <- LayoutController

This is ever since I introduced a service I have this registered on the controller, but it still not working. The controller referenced is:

(function () {
    "use strict";
    angular.module("HtJobPortal").controller("LayoutController",LayoutController);

    LayoutController.$inject = ["$scope", "navigator"];

    function LayoutController($scope, navigator){
        var layout = this;

        // Layout
        layout.loadTemplate = function() {
            return navigator.loadTemplate();
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    }

})();

This is the service:

(function() {

    var navigator = angular.module('navigator', []);
    navigator.factory('loadTemplate', function () {
        var loadTemplate = this;

        // Page Directory
        navigator.login = "templates/login.html";
        navigator.dashboard = "templates/dashboard.html";
        navigator.job = "templates/job.html";

        // Template switcher
        navigator.loadTemplate = function () {
            return navigator.login;
        }

        return loadTemplate;
    });

}());

And the app page just in case I've missed something there:

(function () {
    'use strict';

    angular.module('HtJobPortal', []);
})();

Body:
To create a factory\service\controllers , you generally don't require a new module every time. It's preferred to declare one module and register your controller\factory\services to same.

In your case, you can do it like:

(function() {
    angular.module('HtJobPortal', [..define other module dependency here..]);
    angular.module('HtJobPortal')
   .factory('loadTemplate', function () {
        var loadTemplate = {};
        // Page Directory
        loadTemplate.login = "templates/login.html";
        loadTemplate.dashboard = "templates/dashboard.html";
        loadTemplate.job = "templates/job.html";

        // Template switcher
        loadTemplate.loadTemplate = function () {
            return loadTemplate .login;
        }
        return loadTemplate; // return object from factory
    })
    .controller("LayoutController",LayoutController);
    LayoutController.$inject = ["$scope", "loadTemplate"]; //inject factory
    function LayoutController($scope, loadTemplate){
        var layout = this;
        // Layout
        layout.loadTemplate = function() {
            return loadTemplate.loadTemplate(); // call factory method
        }

        // Initialise pending and set roles
        layout.init = function () {
            // Global Start up
        };
        layout.init();
    };
}());


问:
Show alert if user selects a date within the next 3 days
Im using xdsoft datetimepicker so users can select a deadline. I would like to show an alert if they choose one of the next 3 days.

Initially I had set a minDate so these days were not selectable but I would prefer if these days can be selected and an alert box is shown instead.

I am not sure if there if an option for this already exists, I could not find one in the documentation.

This is how I've been doing it-

html

```<code><h3>Deadline:</h3>
<input type="text" id="datetimepicker"/>
</code>```

jquery

```<code>$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'d/m/Y',
    formatDate:'Y/m/d',
    minDate:'+1970/01/04',
});
</code>```

I have also set up a jsfiddle

Thanks guys, if you could steer me in the right path it would be much appreciated

答:
check this fiddle for solution. I have used hard coded dates but you can do formatting accordingly. There is  onSelectDate:function( ct ){..... that you can use.

```<code>$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'d/m/Y',
    formatDate:'Y/m/d',
    minDate:'+1970/01/00',
  onSelectDate:function( ct ){

  var dateFrom = "06/08/2017";
  var dateTo = "06/11/2017";
  var dateCheck = "06/09/2017";

  var d1 = dateFrom.split("/");
  var d2 = dateTo.split("/");
  var c = dateCheck.split("/");

  var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
  var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
  var check = new Date(c[2], parseInt(c[1])-1, c[0]);

    alert(check > from && check < to);
  },
});
</code>```

https://jsfiddle.net/oqw90cbu/5/

Body:
Im using xdsoft datetimepicker so users can select a deadline. I would like to show an alert if they choose one of the next 3 days.

Initially I had set a minDate so these days were not selectable but I would prefer if these days can be selected and an alert box is shown instead.

I am not sure if there if an option for this already exists, I could not find one in the documentation.

This is how I've been doing it-

html

Deadline:

<input type="text" id="datetimepicker"/>

jquery

$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'d/m/Y',
    formatDate:'Y/m/d',
    minDate:'+1970/01/04',
});

I have also set up a jsfiddle

Thanks guys, if you could steer me in the right path it would be much appreciated

Body:
check this fiddle for solution. I have used hard coded dates but you can do formatting accordingly. There is  onSelectDate:function( ct ){..... that you can use.

$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'d/m/Y',
    formatDate:'Y/m/d',
    minDate:'+1970/01/00',
  onSelectDate:function( ct ){

  var dateFrom = "06/08/2017";
  var dateTo = "06/11/2017";
  var dateCheck = "06/09/2017";

  var d1 = dateFrom.split("/");
  var d2 = dateTo.split("/");
  var c = dateCheck.split("/");

  var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
  var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
  var check = new Date(c[2], parseInt(c[1])-1, c[0]);

    alert(check > from && check < to);
  },
});

https://jsfiddle.net/oqw90cbu/5/


问:
Gmail: How to send an email programmatically

Possible Exact Duplicate: Sending Email in C#.NET Through Gmail

Hi,

I'm trying to send an email using gmail:

I tried various examples that I found on this site and other sites but I always get the same error:

Unable to connect to the remote server -- > System.net.Sockets.SocketException: No connection could be made because the target actively refused it 209.85.147.109:587

```<code>    public static void Attempt1()
    {
        var client = new SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new NetworkCredential("MyEmailAddress@gmail.com", "MyPassWord"),
            EnableSsl = true
        };
        client.Send("MyEmailAddress@gmail.com", "some.email@some.com", "test", "testbody");
    }
</code>```

Any ideas?

UPDATE

More details.

Maybe I should say what other attempts I made that gave me the same error:
(Note when i didn't specify a port it tryed port 25)

```<code>    public static void Attempt2()
    {
        var fromAddress = new MailAddress("MyEmailAddy@gmail.com", "From Name");
        var toAddress = new MailAddress("MyEmailAddy@dfdf.com", "To Name");
        const string fromPassword = "pass";
        const string subject = "Subject";
        const string body = "Body";
        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        }
            ) { smtp.Send(message); }
    }

    public static void Attempt3()
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("MyEmailAddy@dfdf.com");
        mail.From = new MailAddress("MyEmailAddy@gmail.com");
        mail.Subject = "Email using Gmail";

        string Body = "Hi, this mail is to test sending mail" +
                      "using Gmail in ASP.NET";
        mail.Body = Body;

        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Credentials = new System.Net.NetworkCredential
             ("MyEmailAddy@gmail.com", "pass");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
</code>```

答: Are you sure that your GMail account is set up to allow POP/SMTP connections?  It is a configurable option that you can turn on and off as you choose.  </p>

OwnerDisplayName: Clint

Body:
Possible Exact Duplicate: Sending Email in C#.NET Through Gmail

Hi,

I'm trying to send an email using gmail:

I tried various examples that I found on this site and other sites but I always get the same error:

Unable to connect to the remote server -- > System.net.Sockets.SocketException: No connection could be made because the target actively refused it 209.85.147.109:587

    public static void Attempt1()
    {
        var client = new SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new NetworkCredential("MyEmailAddress@gmail.com", "MyPassWord"),
            EnableSsl = true
        };
        client.Send("MyEmailAddress@gmail.com", "some.email@some.com", "test", "testbody");
    }

Any ideas?

UPDATE

More details.

Maybe I should say what other attempts I made that gave me the same error:
(Note when i didn't specify a port it tryed port 25)

    public static void Attempt2()
    {
        var fromAddress = new MailAddress("MyEmailAddy@gmail.com", "From Name");
        var toAddress = new MailAddress("MyEmailAddy@dfdf.com", "To Name");
        const string fromPassword = "pass";
        const string subject = "Subject";
        const string body = "Body";
        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        }
            ) { smtp.Send(message); }
    }

    public static void Attempt3()
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("MyEmailAddy@dfdf.com");
        mail.From = new MailAddress("MyEmailAddy@gmail.com");
        mail.Subject = "Email using Gmail";

        string Body = "Hi, this mail is to test sending mail" +
                      "using Gmail in ASP.NET";
        mail.Body = Body;

        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Credentials = new System.Net.NetworkCredential
             ("MyEmailAddy@gmail.com", "pass");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }


问:
Javascript - dumping all global variables
Is there a way in Javascript to get a list or dump the contents of all global variables declared by Javascript/jQuery script on a page? I am particularly interested in arrays. If I can get the array names, it will be enough to me. Seeing its values is a bonus.</p>

答:
Greasymonkey script to get leaked globals

```<code>// ==UserScript==
// @name        SCI
// @namespace   ns
// @version     1
// @grant       none
// @run-at      document-start
// ==/UserScript==
console.log('SCI loaded');
var SCI = window.SCI = {
        defprops: [],
        collect: function(){
            var wprops = [];
            for(var prop in window){
                wprops.push(prop);
            }
            return wprops;
        },
        collectDef: function(){
            this.defprops = this.collect();
        },
        diff: function(){
            var def = this.defprops,
                cur = this.collect();
            var dif = [];
            for(var i = 0; i < cur.length; i++){
                var p = cur[i];
                if(def.indexOf(p) === -1){
                    dif.push(p);
                }
            }
            return dif;
        },
        diffObj: function(){
            var diff = this.diff();
            var dobj = {};
            for (var i = 0; i < diff.length; i++){
                var p = diff[i];
                dobj[p]=window[p];
            }
            return dobj;

        }
};
SCI.collectDef();
</code>```

To use run in console SCI.diff() to get list of names or SCI.diffObj() to get object with variables

Body:
Greasymonkey script to get leaked globals

// ==UserScript==
// @name        SCI
// @namespace   ns
// @version     1
// @grant       none
// @run-at      document-start
// ==/UserScript==
console.log('SCI loaded');
var SCI = window.SCI = {
        defprops: [],
        collect: function(){
            var wprops = [];
            for(var prop in window){
                wprops.push(prop);
            }
            return wprops;
        },
        collectDef: function(){
            this.defprops = this.collect();
        },
        diff: function(){
            var def = this.defprops,
                cur = this.collect();
            var dif = [];
            for(var i = 0; i < cur.length; i++){
                var p = cur[i];
                if(def.indexOf(p) === -1){
                    dif.push(p);
                }
            }
            return dif;
        },
        diffObj: function(){
            var diff = this.diff();
            var dobj = {};
            for (var i = 0; i < diff.length; i++){
                var p = diff[i];
                dobj[p]=window[p];
            }
            return dobj;

        }
};
SCI.collectDef();

To use run in console SCI.diff() to get list of names or SCI.diffObj() to get object with variables


问:
Can closure in swift be used for communication between 2 classes?
I have a custom cell for a UITableView. When user taps on a button in cell, user has to get navigated from the current ViewController1 to ViewController2. I have defined the button action in the custom cell class. But needs a call back to the ViewController1.

I tried using closure similar to how we use blocks in objective C. It works fine while using in the same class. But getting errors while using in 2 different classes.

答:
You need to use delegate protocols there.

Example: Protocol for sending UserItem when something happened in cell:

```<code>protocol TappedUserDelegate: class {
    func userInfoTapped(_ tappedUser: UserItem?)
}
</code>```

In your controller:

```<code>extension Controller: TappedUserDelegate {
    func userInfoTapped(_ user: UserItem?) {
        // user is tapped user in cell
    }
}
</code>```

In your tableView func:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // ........
    cell.delegateUserTaps = self // for user info taps to perform segue
    // ........
}
</code>```

In your custom cell:

```<code>class CustomCell: UITableViewCell {
   weak var delegateUserTaps: TappedUserDelegate? // for sending user info

   // ........
   func userInfoTapped() {
       delegateUserTaps?.userInfoTapped(userItem) // <- send data to controller
   }
}
</code>```

When userInfoTapped will be called, your function in controller will be performed with this user.

I've given you an idea.

Hope it helps

Body:
You need to use delegate protocols there.

Example: Protocol for sending UserItem when something happened in cell:

protocol TappedUserDelegate: class {
    func userInfoTapped(_ tappedUser: UserItem?)
}

In your controller:

extension Controller: TappedUserDelegate {
    func userInfoTapped(_ user: UserItem?) {
        // user is tapped user in cell
    }
}

In your tableView func:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // ........
    cell.delegateUserTaps = self // for user info taps to perform segue
    // ........
}

In your custom cell:

class CustomCell: UITableViewCell {
   weak var delegateUserTaps: TappedUserDelegate? // for sending user info

   // ........
   func userInfoTapped() {
       delegateUserTaps?.userInfoTapped(userItem) // <- send data to controller
   }
}

When userInfoTapped will be called, your function in controller will be performed with this user.

I've given you an idea.

Hope it helps


问:
How to get complete address from latitude and longitude?
I want to get following values from Latitude and Longitude in android

Street Address

City / State

Zip

Complete Address

How to achieve this?

答:
You can easily use the following code to get the address.</p>

```<code>import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSService extends Service implements LocationListener {

// saving the context for later use
private final Context mContext;

// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;

// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;

// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;

// Declaring a Location Manager
protected LocationManager mLocationManager;

public GPSService(Context context) {
    this.mContext = context;
    mLocationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

}

/**
 * Returs the Location
 *
 * @return Location or null if no location is found
 */
public Location getLocation() {
    try {

        // Getting GPS status
        isGPSEnabled = mLocationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // If GPS enabled, get latitude/longitude using GPS Services
        if (isGPSEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                                                // location is available
                    return mLocation;
                }
            }
        }

        // If we are reaching this part, it means GPS was not able to fetch
        // any location
        // Getting network status
        isNetworkEnabled = mLocationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                                                // location is available
                    return mLocation;
                }
            }
        }
        // If reaching here means, we were not able to get location neither
        // from GPS not Network,
        if (!isGPSEnabled) {
            // so asking user to open GPS
            askUserToOpenGPS();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    // if reaching here means, location was not available, so setting the
    // flag as false
    isLocationAvailable = false;
    return null;
}

/**
 * Gives you complete address of the location
 *
 * @return complete address in String
 */
public String getLocationAddress() {

    if (isLocationAvailable) {

        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        // Get the current location from the input parameter list
        // Create a list to contain the result address
        List<Address> addresses = null;
        try {
            /*
             * Return 1 address.
             */
            addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
        } catch (IOException e1) {
            e1.printStackTrace();
            return ("IO Exception trying to get address:" + e1);
        } catch (IllegalArgumentException e2) {
            // Error message to post in the log
            String errorString = "Illegal arguments "
                    + Double.toString(mLatitude) + " , "
                    + Double.toString(mLongitude)
                    + " passed to address service";
            e2.printStackTrace();
            return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {
            // Get the first address
            Address address = addresses.get(0);
            /*
             * Format the first line of address (if available), city, and
             * country name.
             */
            String addressText = String.format(
                    "%s, %s, %s",
                    // If there's a street address, add it
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "",
                    // Locality is usually a city
                    address.getLocality(),
                    // The country of the address
                    address.getCountryName());
            // Return the text
            return addressText;
        } else {
            return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
        }
    } else {
        return "Location Not available";
    }

}

/**
 * get latitude
 *
 * @return latitude in double
 */
public double getLatitude() {
    if (mLocation != null) {
        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}

/**
 * get longitude
 *
 * @return longitude in double
 */
public double getLongitude() {
    if (mLocation != null) {
        mLongitude = mLocation.getLongitude();
    }
    return mLongitude;
}

/**
 * close GPS to save battery
 */
public void closeGPS() {
    if (mLocationManager != null) {
        mLocationManager.removeUpdates(GPSService.this);
    }
}

/**
 * show settings to open GPS
 */
public void askUserToOpenGPS() {
    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    mAlertDialog.setTitle("Location not available, Open GPS?")
    .setMessage("Activate GPS to use use location services?")
    .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
            }
        })
        .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                }
            }).show();
}

/**
 * Updating the location when location changes
 */
@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}
</code>```

Body:
You can easily use the following code to get the address.

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSService extends Service implements LocationListener {

// saving the context for later use
private final Context mContext;

// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;

// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;

// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;

// Declaring a Location Manager
protected LocationManager mLocationManager;

public GPSService(Context context) {
    this.mContext = context;
    mLocationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

}

/**
 * Returs the Location
 *
 * @return Location or null if no location is found
 */
public Location getLocation() {
    try {

        // Getting GPS status
        isGPSEnabled = mLocationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // If GPS enabled, get latitude/longitude using GPS Services
        if (isGPSEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                                                // location is available
                    return mLocation;
                }
            }
        }

        // If we are reaching this part, it means GPS was not able to fetch
        // any location
        // Getting network status
        isNetworkEnabled = mLocationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                                                // location is available
                    return mLocation;
                }
            }
        }
        // If reaching here means, we were not able to get location neither
        // from GPS not Network,
        if (!isGPSEnabled) {
            // so asking user to open GPS
            askUserToOpenGPS();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    // if reaching here means, location was not available, so setting the
    // flag as false
    isLocationAvailable = false;
    return null;
}

/**
 * Gives you complete address of the location
 *
 * @return complete address in String
 */
public String getLocationAddress() {

    if (isLocationAvailable) {

        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        // Get the current location from the input parameter list
        // Create a list to contain the result address
        List<Address> addresses = null;
        try {
            /*
             * Return 1 address.
             */
            addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
        } catch (IOException e1) {
            e1.printStackTrace();
            return ("IO Exception trying to get address:" + e1);
        } catch (IllegalArgumentException e2) {
            // Error message to post in the log
            String errorString = "Illegal arguments "
                    + Double.toString(mLatitude) + " , "
                    + Double.toString(mLongitude)
                    + " passed to address service";
            e2.printStackTrace();
            return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {
            // Get the first address
            Address address = addresses.get(0);
            /*
             * Format the first line of address (if available), city, and
             * country name.
             */
            String addressText = String.format(
                    "%s, %s, %s",
                    // If there's a street address, add it
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "",
                    // Locality is usually a city
                    address.getLocality(),
                    // The country of the address
                    address.getCountryName());
            // Return the text
            return addressText;
        } else {
            return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
        }
    } else {
        return "Location Not available";
    }

}

/**
 * get latitude
 *
 * @return latitude in double
 */
public double getLatitude() {
    if (mLocation != null) {
        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}

/**
 * get longitude
 *
 * @return longitude in double
 */
public double getLongitude() {
    if (mLocation != null) {
        mLongitude = mLocation.getLongitude();
    }
    return mLongitude;
}

/**
 * close GPS to save battery
 */
public void closeGPS() {
    if (mLocationManager != null) {
        mLocationManager.removeUpdates(GPSService.this);
    }
}

/**
 * show settings to open GPS
 */
public void askUserToOpenGPS() {
    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    mAlertDialog.setTitle("Location not available, Open GPS?")
    .setMessage("Activate GPS to use use location services?")
    .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
            }
        })
        .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                }
            }).show();
}

/**
 * Updating the location when location changes
 */
@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}


问:
Creating A List of Possible String Combination

Possible Duplicate:

Generate list of all possible permutations of a string

I need to work on a small algorithm project where I need to be able to list and write to a text file the possible combination of a given set of characters based on a given limit.

For example, if I enter the characters "a", "b", and "c" and set the limit to 3 the possible output would be:

```<code>a
b
c
aa
bb
cc
ab
ac
ba
bc
ca
cb
...
    aaa
    bbb
    ccc
    ...
    ...
    abc
    acb
    bac
    bca
    cab
    cba
</code>```

Until all possible combinations have been devised.

Writing this to a text file is no problem with me. Having an algorithm that would write the combination is something that I am quite not good at.

Appreciate in .NET (C# or VB) codes.

Thanks.

PS

On a side note, I wonder how long it would take for an application to create a string combination of all possible keyboard characters and how big the file would get to be.

Updated:
I should also show character combination from n characters to the implied limit..

答: See Generate list of all possible permutations of a string</p>

ContentLicense: CC BY-SA 4.0

Body:
Possible Duplicate:

Generate list of all possible permutations of a string

I need to work on a small algorithm project where I need to be able to list and write to a text file the possible combination of a given set of characters based on a given limit.

For example, if I enter the characters "a", "b", and "c" and set the limit to 3 the possible output would be:

a
b
c
aa
bb
cc
ab
ac
ba
bc
ca
cb
...
    aaa
    bbb
    ccc
    ...
    ...
    abc
    acb
    bac
    bca
    cab
    cba

Until all possible combinations have been devised.

Writing this to a text file is no problem with me. Having an algorithm that would write the combination is something that I am quite not good at.

Appreciate in .NET (C# or VB) codes.

Thanks.

PS

On a side note, I wonder how long it would take for an application to create a string combination of all possible keyboard characters and how big the file would get to be.

Updated:
I should also show character combination from n characters to the implied limit..


答:
You can use explode function
Below is the simple example for your case

```<code>import org.apache.spark.sql.functions._
import spark.implicits._

  val data = spark.sparkContext.parallelize(Seq(
    (1, "A", List(1,2,3)),
    (2, "B", List(3, 5))
  )).toDF("FieldA", "FieldB", "FieldC")

    data.withColumn("ExplodedField", explode($"FieldC")).drop("FieldC")
</code>```

Hope this helps!

Title: Explode array data into rows in spark

Body:
You can use explode function
Below is the simple example for your case

import org.apache.spark.sql.functions._
import spark.implicits._

  val data = spark.sparkContext.parallelize(Seq(
    (1, "A", List(1,2,3)),
    (2, "B", List(3, 5))
  )).toDF("FieldA", "FieldB", "FieldC")

    data.withColumn("ExplodedField", explode($"FieldC")).drop("FieldC")

Hope this helps!


问:
how to crop an image (frame) within canvas
I have multiple frames in one single image. How do I paint the crop of an image within the canvas?

Party pooper is that the canvas is stretched out and responsive via CSS. Example:

Say, every frame is 100x100px and I want to paint frame "5". So I have to paint frame following position: x100, y200, width100, height 100

My code looks something like this:

```<code>this.ctx = this.canvas.get(0).getContext("2d");
this.ctx.drawImage(this.image, - this.imageWidth * x, - this.imageHeight * y, this.image.width, this.image.height);
</code>```

All values come out correct in my console but the result is jack shit. Did I interpret drawImage wrong?

答:
why are you using negative values ?

for the "5", you should use :

```<code>this.ctx.drawImage(this.image, 100, 100);
</code>```

or if your sprite hasn't the right size :

```<code>this.ctx.drawImage(this.image, 100, 100, 100, 100);
</code>```

doc for drawImage :
https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage

Body:
I have multiple frames in one single image. How do I paint the crop of an image within the canvas?

Party pooper is that the canvas is stretched out and responsive via CSS. Example:

Say, every frame is 100x100px and I want to paint frame "5". So I have to paint frame following position: x100, y200, width100, height 100

My code looks something like this:

this.ctx = this.canvas.get(0).getContext("2d");
this.ctx.drawImage(this.image, - this.imageWidth * x, - this.imageHeight * y, this.image.width, this.image.height);

All values come out correct in my console but the result is jack shit. Did I interpret drawImage wrong?

Body:
why are you using negative values ?

for the "5", you should use :

this.ctx.drawImage(this.image, 100, 100);

or if your sprite hasn't the right size :

this.ctx.drawImage(this.image, 100, 100, 100, 100);

doc for drawImage :
https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage


问:
Hive error : Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterable
I am facing an error when I try to query a table in hive when hive uses spark. For example, when I do:

```<code>select count(*) from ma_table;
</code>```

I get this:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterable
    at org.apache.hadoop.hive.ql.parse.spark.GenSparkProcContext.<init>(GenSparkProcContext.java:163)
    at org.apache.hadoop.hive.ql.parse.spark.SparkCompiler.generateTaskTree(SparkCompiler.java:195)
    at org.apache.hadoop.hive.ql.parse.TaskCompiler.compile(TaskCompiler.java:267)
    at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.analyzeInternal(SemanticAnalyzer.java:10947)
    at org.apache.hadoop.hive.ql.parse.CalcitePlanner.analyzeInternal(CalcitePlanner.java:246)
    at org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.analyze(BaseSemanticAnalyzer.java:250)
    at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:477)
    at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1242)
    at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1384)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1171)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1161)
    at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:232)
    at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:183)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:399)
    at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:776)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:714)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:641)
    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:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:234)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:148)
Caused by: java.lang.ClassNotFoundException: scala.collection.Iterable
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more
</code>```

After some research, I tried to had this to my bashrc (and sourced it ;) ) :

```<code>for f in ${HIVE_LIB}/*.jar; do
    CLASSPATH=${CLASSPATH}:$f;
done

 for f in ${SPARK_HOME}/jars/*.jar; do
     CLASSPATH=${CLASSPATH}:$f;
 done

for f in ${SCALA_HOME}/lib/*.jar; do
     CLASSPATH=${CLASSPATH}:$f;
done
</code>```

I checked and I have all these jars in the CLASSPATH and still get the error.
I am using Hive 2.1, Hadoop 2.8 and Spark 2.1.
Any ideas? Thanks a lot by advance!

答:
After coming back to it, I found that scala jars files weren't in the lib of Hive.
If you are facing something similar, have a look there:
https://www.linkedin.com/pulse/hive-spark-configuration-common-issues-mohamed-k</p>

Body:
I am facing an error when I try to query a table in hive when hive uses spark. For example, when I do:

select count(*) from ma_table;

I get this:

Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterable
    at org.apache.hadoop.hive.ql.parse.spark.GenSparkProcContext.<init>(GenSparkProcContext.java:163)
    at org.apache.hadoop.hive.ql.parse.spark.SparkCompiler.generateTaskTree(SparkCompiler.java:195)
    at org.apache.hadoop.hive.ql.parse.TaskCompiler.compile(TaskCompiler.java:267)
    at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.analyzeInternal(SemanticAnalyzer.java:10947)
    at org.apache.hadoop.hive.ql.parse.CalcitePlanner.analyzeInternal(CalcitePlanner.java:246)
    at org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.analyze(BaseSemanticAnalyzer.java:250)
    at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:477)
    at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1242)
    at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1384)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1171)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1161)
    at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:232)
    at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:183)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:399)
    at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:776)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:714)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:641)
    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:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:234)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:148)
Caused by: java.lang.ClassNotFoundException: scala.collection.Iterable
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more

After some research, I tried to had this to my bashrc (and sourced it ;) ) :

for f in ${HIVE_LIB}/*.jar; do
    CLASSPATH=${CLASSPATH}:$f;
done

 for f in ${SPARK_HOME}/jars/*.jar; do
     CLASSPATH=${CLASSPATH}:$f;
 done

for f in ${SCALA_HOME}/lib/*.jar; do
     CLASSPATH=${CLASSPATH}:$f;
done

I checked and I have all these jars in the CLASSPATH and still get the error.
I am using Hive 2.1, Hadoop 2.8 and Spark 2.1.
Any ideas? Thanks a lot by advance!


答:
A funny, easy, and infinitely recursive way to do this :

let obj = {
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}

let count = JSON.stringify(obj).match(/"titi":/g).length

console.log(count) // 7```

Title: Recursive way to find number of items in a object of array

Body:
What is the recursive way to get the number of titi in the following object :

{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}

Expected result is the total. In this example : 7.