问:
Current and next props are the same in componentWillReceiveProps call
I am updating my redux store variables and pass them as props to a component but in this piece of code both current and next props are the same, equal to new ones when I change them via dispatch from outside.

```<code>componentWillReceiveProps (nextProps) {
    console.log(this.props.data);
    console.log(nextProps.data);
}
</code>```

Why does it happen so? Should they be different at all if changed via dispatch?

答:
I found the core of the problem.

I used this to clone my current state in a reducer:

```<code>export const cloneDeep = (state) => ({...state});
</code>```

Which seemed to be mutating current state.
I replaced it with this one:

```<code>export const cloneDeep = (state) => JSON.parse(JSON.stringify(state));
</code>```

Which doesn't do any changes to current state and current props are not equal to nextProps now if changed.

Body:
I am updating my redux store variables and pass them as props to a component but in this piece of code both current and next props are the same, equal to new ones when I change them via dispatch from outside.

componentWillReceiveProps (nextProps) {
    console.log(this.props.data);
    console.log(nextProps.data);
}

Why does it happen so? Should they be different at all if changed via dispatch?

Body:
I found the core of the problem.

I used this to clone my current state in a reducer:

export const cloneDeep = (state) => ({...state});

Which seemed to be mutating current state.
I replaced it with this one:

export const cloneDeep = (state) => JSON.parse(JSON.stringify(state));

Which doesn't do any changes to current state and current props are not equal to nextProps now if changed.


来源: stackexchange

问:
Python Kivy Is Printing numbers while importing it
I just installed Kivy in my virtualenv

I installed it using  pip install https://github.com/kivy/kivy/archive/master.zip

My dependencies

```<code>Python 2.7.10
Kivy==1.10.1.dev0
Cython==0.26.1
Kivy-Garden==0.1.4
</code>```

When I tried to run it in my terminal
using command from kivy.app import App

Its printing integers recursively  I have attached screenshot below

Thanks in advance!!

I Have Raised A GIT ISSUE ALSO :- https://github.com/kivy/kivy/issues/5515

答:
I'll propose a workaround: it's to turn off printing from python during imports. It's lame but will fix in while they're fixing the forgotten print properly:

```<code>import sys

def write(x):
    pass
saved = sys.stdout.write
sys.stdout.write = write

from kivy.app import App  # works for any import that uses stdout to print stuff

sys.stdout.write = saved
</code>```

just save sys.stdout.write, then override it with a method that does nothing, then import. Restore standard output after importing.

I've tested it with a custom module that prints stuff when imported, and it suppresses the prints. If it doesn't work, the same thing can be tried with sys.stderr.write

ContentLicense: CC BY-SA 3.0

Body:
I just installed Kivy in my virtualenv

I installed it using  pip install https://github.com/kivy/kivy/archive/master.zip

My dependencies

Python 2.7.10
Kivy==1.10.1.dev0
Cython==0.26.1
Kivy-Garden==0.1.4

When I tried to run it in my terminal
using command from kivy.app import App

Its printing integers recursively  I have attached screenshot below

Thanks in advance!!

I Have Raised A GIT ISSUE ALSO :- https://github.com/kivy/kivy/issues/5515

Body:
I'll propose a workaround: it's to turn off printing from python during imports. It's lame but will fix in while they're fixing the forgotten print properly:

import sys

def write(x):
    pass
saved = sys.stdout.write
sys.stdout.write = write

from kivy.app import App  # works for any import that uses stdout to print stuff

sys.stdout.write = saved

just save sys.stdout.write, then override it with a method that does nothing, then import. Restore standard output after importing.

I've tested it with a custom module that prints stuff when imported, and it suppresses the prints. If it doesn't work, the same thing can be tried with sys.stderr.write


问:
Flex menu, first element on whole row after line break
Responsive flex menu (code bellow) is on smaller viewports arranged like this:

```    |first item| |item| |item| |item| |item| |item|
                    |last item|```

Last item is on whole line in the middle.
Is it possible to do this? :

```                     |first item|
    |item| |item| |item| |item| |item| |last item|```

Looking for common solution. Menu can has any number of items.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ul>
     <li class="first">first item</li>
     <li>second item</li>
     <li>next item</li>
     <li>item</li>
     <li>pretty item</li>
     <li class="almostlast"><span>item</span></li>
     <li class="last">last item</li>
</ul></code>```

答:
I'm not sure if this is possible using pure CSS. But you can achieve this by using flex-flow:row-reverse wrap-reverse; then also make your li items in reverse.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-flow:row-reverse wrap-reverse;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ul>
     <li class="last">last item</li>
     <li class="almostlast"><span>item</span></li>
     <li>pretty item</li>
     <li>item</li>
     <li>next item</li>
     <li>second item</li>
     <li class="first">first item</li>
</ul></code>```

Body:
Responsive flex menu (code bellow) is on smaller viewports arranged like this:

    |first item| |item| |item| |item| |item| |item|
                    |last item|

Last item is on whole line in the middle.
Is it possible to do this? :

                     |first item|
    |item| |item| |item| |item| |item| |last item|

Looking for common solution. Menu can has any number of items.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

first item

second item

next item

item

pretty item

item

last item

Body:
I'm not sure if this is possible using pure CSS. But you can achieve this by using flex-flow:row-reverse wrap-reverse; then also make your li items in reverse.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-flow:row-reverse wrap-reverse;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

 <ul>
     <li class="last"><a href="#">last item</a></li>
     <li class="almostlast"><span><a href="#">item</a></span></li>
     <li><a href="#">pretty item</a></li>
     <li><a href="#">item</a></li>
     <li><a href="#">next item</a></li>
     <li><a href="#">second item</a></li>
     <li class="first"><a href="#">first item</a></li>
</ul>


问:
How to get string based on id from json
i am giving text as a input and getting responses through text razor API. Now how to get the words(string) based on word position(id).

Here string and id are in different nodes.

NOTE: Here getting  word position 0,1 I want to display   "The Tiger"  in my front end using Jquery

JSON

```<code>{
    "response": {
        "sentences": [{
            "position": "0",
            "words": [{
                "position": "0",
                "token": "The"
            },
            {
                "position": 1,
                "token": "Tiger"
            }],
            "nounPhrases": [{
                "id": "0",
                "wordPositions": ["0", "1"]
            }]
        }]
    }
}
</code>```

What I have Tried

```<code>var entailments = data["entailmentsAnalysis"];
        entailments = JSON.parse(entailments);
        var Razorentailments = entailments["response"]["nounPhrases"];
        for (var i = 0; i < Razorentailments.count; i++) {
            html = '';
            html += '<tr><td>' + Razorentailments[i]["wordPositions"] + '</td></tr>'
            $("#TextRazorEntailments").append(html);
        }
</code>```

My Json format

```<code>"response": {
        "sentences":[],
         "nounPhrases":[]
}
</code>```

答:
I assume data["entailmentsAnalysis"] is outside of what you have provided but I've adjusted accordingly.

EDIT - Adjusted to accommodate change in JSON requirements

```<code>var entailments = data["entailmentsAnalysis"];
var json = JSON.parse(entailments);
var sentenceList = json["response"]["sentences"];
var nounPhraseList = json["response"]["nounPhrases"];
for (var i = 0; i < nounPhraseList.length; i++) {
    for (var j = 0; j < sentenceList.length; j++) {
        var html = '<tr><td>';
        var wordList = sentenceList[j]["words"];
        for (var k = 0; k < wordList.length; k++) {
            if (nounPhraseList[i].wordPositions.indexOf(wordList[k].position.toString()) != -1) {
                html += wordList[k].token + " ";
            }
        }
        html = html.slice(0, -1);
        html += '</td></tr>';
        $("#TextRazorEntailments").append(html);
    }

}
</code>```

Title: How to get string based on id from json

Body:
i am giving text as a input and getting responses through text razor API. Now how to get the words(string) based on word position(id).

Here string and id are in different nodes.

NOTE: Here getting  word position 0,1 I want to display   "The Tiger"  in my front end using Jquery

JSON

{
    "response": {
        "sentences": [{
            "position": "0",
            "words": [{
                "position": "0",
                "token": "The"
            },
            {
                "position": 1,
                "token": "Tiger"
            }],
            "nounPhrases": [{
                "id": "0",
                "wordPositions": ["0", "1"]
            }]
        }]
    }
}

What I have Tried

var entailments = data["entailmentsAnalysis"];
        entailments = JSON.parse(entailments);
        var Razorentailments = entailments["response"]["nounPhrases"];
        for (var i = 0; i < Razorentailments.count; i++) {
            html = '';
            html += '
' + Razorentailments[i]["wordPositions"] + '
'
            $("#TextRazorEntailments").append(html);
        }

My Json format

"response": {
        "sentences":[],
         "nounPhrases":[]
}

Body:
I assume data["entailmentsAnalysis"] is outside of what you have provided but I've adjusted accordingly.

EDIT - Adjusted to accommodate change in JSON requirements

var entailments = data["entailmentsAnalysis"];
var json = JSON.parse(entailments);
var sentenceList = json["response"]["sentences"];
var nounPhraseList = json["response"]["nounPhrases"];
for (var i = 0; i < nounPhraseList.length; i++) {
    for (var j = 0; j < sentenceList.length; j++) {
        var html = '<tr><td>';
        var wordList = sentenceList[j]["words"];
        for (var k = 0; k < wordList.length; k++) {
            if (nounPhraseList[i].wordPositions.indexOf(wordList[k].position.toString()) != -1) {
                html += wordList[k].token + " ";
            }
        }
        html = html.slice(0, -1);
        html += '</td></tr>';
        $("#TextRazorEntailments").append(html);
    }

}


问:
angular 2 + OAuth 1.0 + signature with '+' character
I am integrating OAuth 1.0 in Angular2 application. I am using simple http.get method and it is working fine until the signature doesn't have '+' character.
 Eg: Signature = I8RxZ0I78ALux4T683QYxTFE9vQ=

If signature contains '+' character then i am getting status as 400 and response as signature invalid error.
Eg: Signature = uyF+uHFTg5KjwCZxP5J6g9yOYpw=

If I debug the application on browser, the signature shown correctly on the url, but the quest string parameter instead of '+' char it shows 'whitespace'.

oauth_signature:uyF uHFTg5KjwCZxP5J6g9yOYpw=

Can anybody has any idea about this?

Thanks

can

答: you must set your token in authorization header then send your http request (get or post)</p>


问:
Python produce function names from string
I would like to use functions based on strings passed in argument as below. The code gives the following error: AttributeError: 'Obj' object has no attribute 'funA'

The functions funA and funB are defined within fun because they are only used within fun and nowhere else

```<code>class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter
            getattr(self, name)()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])
</code>```

答:
I wouldn't recommend it, but if you really need it, then you can do it this way:

```<code>class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter + '()'
            exec(name)

obj_instance=Obj()
obj_instance.fun(['A', 'B'])
</code>```

exec() executes any string that you put in parentheses as if it was python code.

Body:
I would like to use functions based on strings passed in argument as below. The code gives the following error: AttributeError: 'Obj' object has no attribute 'funA'

The functions funA and funB are defined within fun because they are only used within fun and nowhere else

class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter
            getattr(self, name)()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])

Body:
I wouldn't recommend it, but if you really need it, then you can do it this way:

class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter + '()'
            exec(name)

obj_instance=Obj()
obj_instance.fun(['A', 'B'])

exec() executes any string that you put in parentheses as if it was python code.


问:
Not getting keycode in keyup function
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

```<code>$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");
</code>```

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

```<code>function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}
</code>```

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

答:
```<code>    $("#testTextbox").on("keyup", function(e){
    if (e.key=="Enter"){
        // Your logic here
    }
    })

    <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <input id='testTextbox' name='testTextbox' type='text' >
</code>```

As @edkeveked answered above, but I would use event.key instead of event.keycode, as keycode and which are being deprecated according to https://developer.mozilla.org/en-US/docs/Web/Events/keyup

Title: Not getting keycode in keyup function

Body:
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

Body:
    $("#testTextbox").on("keyup", function(e){
    if (e.key=="Enter"){
        // Your logic here
    }
    })

    <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <input id='testTextbox' name='testTextbox' type='text' >

As @edkeveked answered above, but I would use event.key instead of event.keycode, as keycode and which are being deprecated according to https://developer.mozilla.org/en-US/docs/Web/Events/keyup


问:
Access classes in implicitly loaded Jenkins global library
I have a global library configured in Jenkins. It works. But when my Pipeline is stored in SCM, it tells me that it cannot find it when I tried to load it. A workaround is to load it implicitly.

But how can I access the classes in the library then? I can not do

```<code>@Library("mylib") import ...
</code>```

Because that triggers the error.

答:
I'm getting used to this myself at the moment.

I initially read https://jenkins.io/doc/book/pipeline/shared-libraries/#loading-libraries-dynamically to mean that unless you're in a Jenkinsfile, you need to use the syntax:

```<code>library 'mylib'
</code>```

However, I have since realised that actually you can use Library but need to include an underscore or a specific import, i.e.

```<code>@Library('mylib') _
</code>```

See https://issues.jenkins-ci.org/browse/JENKINS-42807?attachmentViewMode=list for where I discovered that.

Does that help at all?

Body:
I have a global library configured in Jenkins. It works. But when my Pipeline is stored in SCM, it tells me that it cannot find it when I tried to load it. A workaround is to load it implicitly.

But how can I access the classes in the library then? I can not do

@Library("mylib") import ...

Because that triggers the error.

Body:
I'm getting used to this myself at the moment.

I initially read https://jenkins.io/doc/book/pipeline/shared-libraries/#loading-libraries-dynamically to mean that unless you're in a Jenkinsfile, you need to use the syntax:

library 'mylib'

However, I have since realised that actually you can use Library but need to include an underscore or a specific import, i.e.

@Library('mylib') _

See https://issues.jenkins-ci.org/browse/JENKINS-42807?attachmentViewMode=list for where I discovered that.

Does that help at all?


问:
Not sure how to create ArangoDB graph using columns in existing collection

Background

I have a rocksdb collection that contains three fields: _id, author, subreddit.

Problem

I would like to create a Arango graph that creates a graph connecting these two existing columns. But the examples and the drivers seem to only accept collections as its edge definitions.

Issue

The ArangoDb documentation is lacking information on how I can create a graph using edges and nodes pulled from the same collection.

EDIT:

Solution

This was fixed with a code change at this Arangodb issues ticket.

答:
Please note that the following queries take a while to complete on this huge dataset, however they should complete sucessfully after some hours.

We start the arangoimp to import our base dataset:

```<code>arangoimp --create-collection true  --collection RawSubReddits --type jsonl ./RC_2017-01
</code>```

We use arangosh to create the collections where our final data is going to live in:

```<code>db._create("authors")
db._createEdgeCollection("authorsToSubreddits")
</code>```

We fill the authors collection by simply ignoring any subsequently occuring duplicate authors;
We will calculate the _key of the author by using the MD5 function,
so it obeys the restrictions for allowed chars in _key, and we can know it later on by calling MD5() again on the author field:

```<code>db._query(`
  FOR item IN RawSubReddits
    INSERT {
      _key: MD5(item.author),
      author: item.author
      } INTO authors
        OPTIONS { ignoreErrors: true }`);
</code>```

After the we have filled the second vertex collection (we will keep the imported collection as the first vertex collection) we have to calculate the edges.
Since each author can have created several subreds, its most probably going to be several edges originating from each author. As previously mentioned,
we can use the MD5()-function again to reference the author previously created:

```<code> db._query(`
   FOR onesubred IN RawSubReddits
     INSERT {
       _from: CONCAT('authors/', MD5(onesubred.author)),
       _to: CONCAT('RawSubReddits/', onesubred._key)
     } INTO  authorsToSubreddits")
</code>```

After the edge collection is filled (which may again take a while - we're talking about 40 million edges herer, right? - we create the graph description:

```<code>db._graphs.save({
  "_key": "reddits",
  "orphanCollections" : [ ],
  "edgeDefinitions" : [
    {
      "collection": "authorsToSubreddits",
      "from": ["authors"],
      "to": ["RawSubReddits"]
    }
  ]
})
</code>```

We now can use the UI to browse the graphs, or use AQL queries to browse the graph. Lets pick the sort of random first author from that list:

```<code>db._query(`for author IN authors LIMIT 1 RETURN author`).toArray()
[
  {
    "_key" : "1cec812d4e44b95e5a11f3cbb15f7980",
    "_id" : "authors/1cec812d4e44b95e5a11f3cbb15f7980",
    "_rev" : "_W_Eu-----_",
    "author" : "punchyourbuns"
  }
]
</code>```

We identified an author, and now run a graph query for him:

```<code>db._query(`FOR vertex, edge, path IN 0..1
   OUTBOUND 'authors/1cec812d4e44b95e5a11f3cbb15f7980'
   GRAPH 'reddits'
   RETURN path`).toArray()
</code>```

One of the resulting paths looks like that:

```<code>{
  "edges" : [
    {
      "_key" : "128327199",
      "_id" : "authorsToSubreddits/128327199",
      "_from" : "authors/1cec812d4e44b95e5a11f3cbb15f7980",
      "_to" : "RawSubReddits/38026350",
      "_rev" : "_W_LOxgm--F"
    }
  ],
  "vertices" : [
    {
      "_key" : "1cec812d4e44b95e5a11f3cbb15f7980",
      "_id" : "authors/1cec812d4e44b95e5a11f3cbb15f7980",
      "_rev" : "_W_HAL-y--_",
      "author" : "punchyourbuns"
    },
    {
      "_key" : "38026350",
      "_id" : "RawSubReddits/38026350",
      "_rev" : "_W-JS0na--b",
      "distinguished" : null,
      "created_utc" : 1484537478,
      "id" : "dchfe6e",
      "edited" : false,
      "parent_id" : "t1_dch51v3",
      "body" : "I don't understand tension at all."
         "Mine is set to auto."
         "I'll replace the needle and rethread. Thanks!",
      "stickied" : false,
      "gilded" : 0,
      "subreddit" : "sewing",
      "author" : "punchyourbuns",
      "score" : 3,
      "link_id" : "t3_5o66d0",
      "author_flair_text" : null,
      "author_flair_css_class" : null,
      "controversiality" : 0,
      "retrieved_on" : 1486085797,
      "subreddit_id" : "t5_2sczp"
    }
  ]
}
</code>```

Body:
Please note that the following queries take a while to complete on this huge dataset, however they should complete sucessfully after some hours.

We start the arangoimp to import our base dataset:

arangoimp --create-collection true  --collection RawSubReddits --type jsonl ./RC_2017-01

We use arangosh to create the collections where our final data is going to live in:

db._create("authors")
db._createEdgeCollection("authorsToSubreddits")

We fill the authors collection by simply ignoring any subsequently occuring duplicate authors;
We will calculate the _key of the author by using the MD5 function,
so it obeys the restrictions for allowed chars in _key, and we can know it later on by calling MD5() again on the author field:

db._query(`
  FOR item IN RawSubReddits
    INSERT {
      _key: MD5(item.author),
      author: item.author
      } INTO authors
        OPTIONS { ignoreErrors: true }`);

After the we have filled the second vertex collection (we will keep the imported collection as the first vertex collection) we have to calculate the edges.
Since each author can have created several subreds, its most probably going to be several edges originating from each author. As previously mentioned,
we can use the MD5()-function again to reference the author previously created:

 db._query(`
   FOR onesubred IN RawSubReddits
     INSERT {
       _from: CONCAT('authors/', MD5(onesubred.author)),
       _to: CONCAT('RawSubReddits/', onesubred._key)
     } INTO  authorsToSubreddits")

After the edge collection is filled (which may again take a while - we're talking about 40 million edges herer, right? - we create the graph description:

db._graphs.save({
  "_key": "reddits",
  "orphanCollections" : [ ],
  "edgeDefinitions" : [
    {
      "collection": "authorsToSubreddits",
      "from": ["authors"],
      "to": ["RawSubReddits"]
    }
  ]
})

We now can use the UI to browse the graphs, or use AQL queries to browse the graph. Lets pick the sort of random first author from that list:

db._query(`for author IN authors LIMIT 1 RETURN author`).toArray()
[
  {
    "_key" : "1cec812d4e44b95e5a11f3cbb15f7980",
    "_id" : "authors/1cec812d4e44b95e5a11f3cbb15f7980",
    "_rev" : "_W_Eu-----_",
    "author" : "punchyourbuns"
  }
]

We identified an author, and now run a graph query for him:

db._query(`FOR vertex, edge, path IN 0..1
   OUTBOUND 'authors/1cec812d4e44b95e5a11f3cbb15f7980'
   GRAPH 'reddits'
   RETURN path`).toArray()

One of the resulting paths looks like that:

{
  "edges" : [
    {
      "_key" : "128327199",
      "_id" : "authorsToSubreddits/128327199",
      "_from" : "authors/1cec812d4e44b95e5a11f3cbb15f7980",
      "_to" : "RawSubReddits/38026350",
      "_rev" : "_W_LOxgm--F"
    }
  ],
  "vertices" : [
    {
      "_key" : "1cec812d4e44b95e5a11f3cbb15f7980",
      "_id" : "authors/1cec812d4e44b95e5a11f3cbb15f7980",
      "_rev" : "_W_HAL-y--_",
      "author" : "punchyourbuns"
    },
    {
      "_key" : "38026350",
      "_id" : "RawSubReddits/38026350",
      "_rev" : "_W-JS0na--b",
      "distinguished" : null,
      "created_utc" : 1484537478,
      "id" : "dchfe6e",
      "edited" : false,
      "parent_id" : "t1_dch51v3",
      "body" : "I don't understand tension at all."
         "Mine is set to auto."
         "I'll replace the needle and rethread. Thanks!",
      "stickied" : false,
      "gilded" : 0,
      "subreddit" : "sewing",
      "author" : "punchyourbuns",
      "score" : 3,
      "link_id" : "t3_5o66d0",
      "author_flair_text" : null,
      "author_flair_css_class" : null,
      "controversiality" : 0,
      "retrieved_on" : 1486085797,
      "subreddit_id" : "t5_2sczp"
    }
  ]
}


问:
Find items in a text file that is a incantinated string of capitalized words that begin with a certain capital letter in python
I am trying to pull a string of input names that get saved to a text file.  I need to pull them by capital letter which is input.  I.E.  the saved text file contains names DanielDanClark,  and I need to pull the names that begin with D.  I am stuck at this part           </p>

```<code>for i in range(num):

    print("Name",i+1," >> Enter the name:")
    n=input("")
    names+=n
file=open("names.txt","w")
file.write(names)
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
    quit()
else:
    letter=input("Enter the first letter of the names you want to look up in uppercase:")
    file=open("names.txt","r")
    fileNames=[]
    file.list()
    for letter in file:
        fileNames.index(letter)
    fileNames.close()
</code>```

<p>I know that the last 4 lines are probably way wrong.  It is what I tried in my last failed attempt                        </p>

答:
Lets break down your code block by block

```<code>num = 5
names = ""
for i in range(num)
    print("Name",i+1," >> Enter the name:")
    n=input("")
    names+=n
</code>```

I took the liberty of giving num a value of 5, and names a value of "", just so the code will run. This block has no problems. And will create a string called names with all the input taken. You might consider putting a delimiter in, which makes it more easier to read back your data. A suggestion would be to use \n which is a line break, so when you get to writing the file, you actually have one name on each line, example:

```<code>num = 5
names = ""
for i in range(num)
    print("Name",i+1," >> Enter the name:")
    n = input()
    names += n + "\n"
</code>```

Now you are going to write the file:

```<code>file=open("names.txt","w")
file.write(names)
</code>```

In this block you forget to close the file, and a better way is to fully specify the pathname of the file, example:

```<code>file = open(r"c:\somedir\somesubdir\names.txt","w")
file.write(names)
file.close()
</code>```

or even better using with:

```<code>with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
    openfile.write(names)
</code>```

The following block you are asking if the user want to lookup a name, and then exit:

```<code>lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
    quit()
</code>```

First thing is that you are using quit() which should not be used in production code, see answers here you really should use sys.exit() which means you need to import the sys module. You then proceed to get the numeric value of the answer being either N or n and you check this in a if statement. You do not have to do ord() you can use a string comparisson directly in your if statement. Example:

```<code>lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
    sys.exit()
</code>```

Then you proceed to lookup the requested data, in the else: block of previous if statement:

```<code>else:
    letter=input("Enter the first letter of the names you want to look up in uppercase:")
    file=open("names.txt","r")
    fileNames=[]
    file.list()
    for letter in file:
        fileNames.index(letter)
    fileNames.close()
</code>```

This is not really working properly either, so this is where the delimiter \n is coming in handy. When a text file is opened, you can use a for line in file block to enumerate through the file line by line, and with \n delimiter added in your first block, each line is a name. You also go wrong in the for letter in file block, it does not do what you think it should be doing. It actually returns each letter in the file, regardless of whay you type in the input earlier. Here is a working example:

```<code>letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
    for line in openfile:  ## loop thru the file line by line
        line = line.strip('\n')  ## get rid of the delimiter
        if line[0].lower() == letter.lower():  ## compare the first (zero) character of the line
            result.append(line)  ## append to result
print(result)  ## do something with the result
</code>```

Putting it all together:

```<code>import sys

num = 5
names = ""
for i in range(num)
    print("Name",i+1," >> Enter the name:")
    n = input("")
    names += n + "\n"

with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
    openfile.write(names)

lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
    sys.exit()

letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
    for line in openfile:
        line = line.strip('\n')
        if line[0].lower() == letter.lower():
            result.append(line)
print(result)
</code>```

One caveat I like to point out, when you create the file, you open the file in w mode, which will create a new file every time, therefore overwriting the a previous file. If you like to append to a file, you need to open it in a mode, which will append to an existing file, or create a new file when the file does not exist.

Body:
I am trying to pull a string of input names that get saved to a text file.  I need to pull them by capital letter which is input.  I.E.  the saved text file contains names DanielDanClark,  and I need to pull the names that begin with D.  I am stuck at this part

for i in range(num):

    print("Name",i+1," >> Enter the name:")
    n=input("")
    names+=n
file=open("names.txt","w")
file.write(names)
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
    quit()
else:
    letter=input("Enter the first letter of the names you want to look up in uppercase:")
    file=open("names.txt","r")
    fileNames=[]
    file.list()
    for letter in file:
        fileNames.index(letter)
    fileNames.close()

I know that the last 4 lines are probably way wrong.  It is what I tried in my last failed attempt

Body:
Lets break down your code block by block

num = 5
names = ""
for i in range(num)
    print("Name",i+1," >> Enter the name:")
    n=input("")
    names+=n

I took the liberty of giving num a value of 5, and names a value of "", just so the code will run. This block has no problems. And will create a string called names with all the input taken. You might consider putting a delimiter in, which makes it more easier to read back your data. A suggestion would be to use \n which is a line break, so when you get to writing the file, you actually have one name on each line, example:

num = 5
names = ""
for i in range(num)
    print("Name",i+1," >> Enter the name:")
    n = input()
    names += n + "\n"

Now you are going to write the file:

file=open("names.txt","w")
file.write(names)

In this block you forget to close the file, and a better way is to fully specify the pathname of the file, example:

file = open(r"c:\somedir\somesubdir\names.txt","w")
file.write(names)
file.close()

or even better using with:

with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
    openfile.write(names)

The following block you are asking if the user want to lookup a name, and then exit:

lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
    quit()

First thing is that you are using quit() which should not be used in production code, see answers here you really should use sys.exit() which means you need to import the sys module. You then proceed to get the numeric value of the answer being either N or n and you check this in a if statement. You do not have to do ord() you can use a string comparisson directly in your if statement. Example:

lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
    sys.exit()

Then you proceed to lookup the requested data, in the else: block of previous if statement:

else:
    letter=input("Enter the first letter of the names you want to look up in uppercase:")
    file=open("names.txt","r")
    fileNames=[]
    file.list()
    for letter in file:
        fileNames.index(letter)
    fileNames.close()

This is not really working properly either, so this is where the delimiter \n is coming in handy. When a text file is opened, you can use a for line in file block to enumerate through the file line by line, and with \n delimiter added in your first block, each line is a name. You also go wrong in the for letter in file block, it does not do what you think it should be doing. It actually returns each letter in the file, regardless of whay you type in the input earlier. Here is a working example:

letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
    for line in openfile:  ## loop thru the file line by line
        line = line.strip('\n')  ## get rid of the delimiter
        if line[0].lower() == letter.lower():  ## compare the first (zero) character of the line
            result.append(line)  ## append to result
print(result)  ## do something with the result

Putting it all together:

import sys

num = 5
names = ""
for i in range(num)
    print("Name",i+1," >> Enter the name:")
    n = input("")
    names += n + "\n"

with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
    openfile.write(names)

lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
    sys.exit()

letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
    for line in openfile:
        line = line.strip('\n')
        if line[0].lower() == letter.lower():
            result.append(line)
print(result)

One caveat I like to point out, when you create the file, you open the file in w mode, which will create a new file every time, therefore overwriting the a previous file. If you like to append to a file, you need to open it in a mode, which will append to an existing file, or create a new file when the file does not exist.


Title: MySQL: Any good way to get cumulative counts and diff counts?

Body:
Suppose I have the following dataset.

+--------------------+
| item_id count date |
+--------------------+
| 000 10 2017-11-01  |
| 001 15 2017-11-01  |
| 002 2 2017-11-01   |
| 003 100 2017-11-01 |
| 000 20 2017-11-02  |
| 001 20 2017-11-02  |
| 002 22 2017-11-02  |
| 003 101 2017-11-02 |
| 000 30 2017-11-03  |
| 001 25 2017-11-03  |
| 002 42 2017-11-03  |
| 003 102 2017-11-03 |
| 000 40 2017-11-04  |
| 001 30 2017-11-04  |
| 002 62 2017-11-04  |
| 003 103 2017-11-04 |
+--------------------+

Is there any way to get cumulative counts and diff counts for each day between two arbitrary dates?

(As for the diff counts, if the selected dates are 2017-11-01 and 2017-11-04, the first diff count(2017-11-01) does not have to be included in the final SQL result as there is no data available before that date)

The following two tables are the expected SQL result.

Cumulative Counts

+--------------------+
| item_id count date |
+--------------------+
| 000 10 2017-11-01  |
| 000 30 2017-11-02  |
| 000 60 2017-11-03  |
| 000 100 2017-11-03 |
| 001 15 2017-11-01  |
| 001 35 2017-11-02  |
| 001 60 2017-11-03  |
| 001 90 2017-11-04  |
| 002 2 2017-11-01   |
| 002 24 2017-11-02  |
| 002 66 2017-11-03  |
| 002 128 2017-11-04 |
| 003 100 2017-11-01 |
| 003 201 2017-11-02 |
| 003 303 2017-11-03 |
| 003 406 2017-11-04 |
+--------------------+

Diff Counts

+--------------------+
| item_id count date |
+--------------------+
| 000 10 2017-11-02  |
| 000 10 2017-11-03  |
| 000 10 2017-11-04  |
| 001 5 2017-11-02   |
| 001 5 2017-11-03   |
| 001 5 2017-11-04   |
| 002 20 2017-11-02  |
| 002 20 2017-11-03  |
| 002 20 2017-11-04  |
| 003 1 2017-11-02   |
| 003 1 2017-11-03   |
| 003 1 2017-11-04   |
+--------------------+

Body:
As MySQL doesn't support windows OLAP functions(except the latest version), you can use variables.

Cumulative SUM:

set @item_id := 0;
set @val := 0;

select t.item_id, t.count, t.date, t.CSUM as CummulativeSUM
from (
select t1.*,
       @val := if(@item_id=item_id, @val + t1.count, t1.count) as CSUM,
       @item_id := item_id
from table1 t1
order by t1.item_id, t1.date
    ) t;

Result:

+---------+-------+---------------------+----------------+
| item_id | count |        date         | CummulativeSUM |
+---------+-------+---------------------+----------------+
|       0 |    10 | 01.11.2017 00:00:00 |             10 |
|       0 |    20 | 02.11.2017 00:00:00 |             30 |
|       0 |    30 | 03.11.2017 00:00:00 |             60 |
|       0 |    40 | 04.11.2017 00:00:00 |            100 |
|       1 |    15 | 01.11.2017 00:00:00 |             15 |
|       1 |    20 | 02.11.2017 00:00:00 |             35 |
|       1 |    25 | 03.11.2017 00:00:00 |             60 |
|       1 |    30 | 04.11.2017 00:00:00 |             90 |
|       2 |     2 | 01.11.2017 00:00:00 |              2 |
|       2 |    22 | 02.11.2017 00:00:00 |             24 |
|       2 |    42 | 03.11.2017 00:00:00 |             66 |
|       2 |    62 | 04.11.2017 00:00:00 |            128 |
|       3 |   100 | 01.11.2017 00:00:00 |            100 |
|       3 |   101 | 02.11.2017 00:00:00 |            201 |
|       3 |   102 | 03.11.2017 00:00:00 |            303 |
|       3 |   103 | 04.11.2017 00:00:00 |            406 |
+---------+-------+---------------------+----------------+

Cumulative SUM DEMO

DIFF Count:

set @item_id1 := 0;
set @val1 := 0;
set @count := 0;

select t.item_id, t.count, t.date, t.CSUM as diffSUM
from (
select t1.*,
       @val1 := if(@item_id1=item_id, t1.count - @count, t1.count) as CSUM,
       @item_id1 := item_id,
       @count := count
from table1 t1
order by t1.item_id, t1.date
    ) t
where count <> csum;

Result:

+---------+-------+---------------------+-----------+
| item_id | count |        date         | diffCount |
+---------+-------+---------------------+-----------+
|       0 |    20 | 02.11.2017 00:00:00 |        10 |
|       0 |    30 | 03.11.2017 00:00:00 |        10 |
|       0 |    40 | 04.11.2017 00:00:00 |        10 |
|       1 |    20 | 02.11.2017 00:00:00 |         5 |
|       1 |    25 | 03.11.2017 00:00:00 |         5 |
|       1 |    30 | 04.11.2017 00:00:00 |         5 |
|       2 |    22 | 02.11.2017 00:00:00 |        20 |
|       2 |    42 | 03.11.2017 00:00:00 |        20 |
|       2 |    62 | 04.11.2017 00:00:00 |        20 |
|       3 |   101 | 02.11.2017 00:00:00 |         1 |
|       3 |   102 | 03.11.2017 00:00:00 |         1 |
|       3 |   103 | 04.11.2017 00:00:00 |         1 |
+---------+-------+---------------------+-----------+

DIFF Count DEMO


问:
How to stop generating wixpdb file in wix setup project?
Is there any configuration available to stop generation of wixpdb file.
Since we do not require that file during deployment.</p>

答:
See the SuppressPdbOutput setting in the light build task:</p>

```<code>Optional boolean parameter.

Specifies that the linker should suppress outputting .wixpdb files. This is
equivalent to the -spdb switch in light.exe.
</code>```

Body:
See the SuppressPdbOutput setting in the light build task:

Optional boolean parameter.

Specifies that the linker should suppress outputting .wixpdb files. This is
equivalent to the -spdb switch in light.exe.


问:
How to pass 2 dimension arrays to function in C?

Possible Duplicates:

  Passing multidimensional arrays as function arguments in C

  Converting multidimensional arrays to pointers in c++

Hi,

I try to pass 2 dimension arrays to function in C, and
the following code works

```<code> void printArray(int a[][4], int size) {
        int i = 0;
        for (; i < size; ++i) {
            int j = 0;
            for (; j < size; ++j) {
                printf("%d,", a[i][j]);
            }
            printf("\n");
        }
    }
</code>```

but if I replace "int a[][4]" to "int **a"
it won't work, can anyone tell what's the difference ?

Thanks

答: Obligatory link: http://c-faq.com/aryptr/pass2dary.html.  Everything you need to know should be in there; I won't bother writing it all out here...</p>

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicates:

  Passing multidimensional arrays as function arguments in C

  Converting multidimensional arrays to pointers in c++

Hi,

I try to pass 2 dimension arrays to function in C, and
the following code works

 void printArray(int a[][4], int size) {
        int i = 0;
        for (; i < size; ++i) {
            int j = 0;
            for (; j < size; ++j) {
                printf("%d,", a[i][j]);
            }
            printf("\n");
        }
    }

but if I replace "int a[][4]" to "int **a"
it won't work, can anyone tell what's the difference ?

Thanks


问:
Connect to MongoDB failed when using .NET Core running on Linux
I'm building a website using ASP.NET Core 2.0 (just upgraded from 1.1 one month ago). MongoDB is hosted by Mongo Atlas on AWS as well.This MongoDB instance has 3 replica set, require SSL to connect and already set can be access from any IP.

It runs quite ok on my machine (Windows 10 x64) and AWS (Windows Server 2016).

I try to deploy it on Linux machines, I use apt to install dotnet-runtime-2.0.0 on Ubuntu Server 16.04, then I try to run my site , and got the following error (for security reason I hide the exact server domain name)

```<code>System.TimeoutException: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = WritableServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-00-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-00-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..
</code>```

and two same error for the rest of replica set.

But I can successfully connect to MongoDB server by MongoDB shell use the same machine.

Am I missing some dependencies on Ubuntu or there's a bug in MongoDB .NET SDK?

Full stacktrace:

```<code>System.TimeoutException: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = WritableServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-00-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-00-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.<ExecuteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.ConnectionInitializer.<InitializeConnectionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()" }, { ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-01-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-01-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.<ExecuteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.ConnectionInitializer.<InitializeConnectionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()" }, { ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-02-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-02-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.<ExecuteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.ConnectionInitializer.<InitializeConnectionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()" }] }.
   at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description)
   at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask)
   at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Clusters.Cluster.SelectServer(IServerSelector selector, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Bindings.WritableServerBinding.GetWriteChannelSource(CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.CreateIndexesOperation.Execute(IWriteBinding binding, CancellationToken cancellationToken)
   at MongoDB.Driver.OperationExecutor.ExecuteWriteOperation[TResult](IWriteBinding binding, IWriteOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.ExecuteWriteOperation[TResult](IWriteOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.MongoIndexManager.CreateMany(IEnumerable`1 models, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoIndexManagerBase`1.CreateOne(IndexKeysDefinition`1 keys, CreateIndexOptions options, CancellationToken cancellationToken)
</code>```

答:
.NET Core library does not support the SNI TLS extension on Linux and OSX.

Hence you will not be able to connect to a FREE Tier MongoDB Atlas.

https://docs.atlas.mongodb.com/driver-connection/#c-net-driver-example

IMPORTANT The .NET Core library does not support the SNI TLS extension
  on Linux and OSX. Applications using .NET Core on these operating
  systems cannot connect to a Atlas Free Tier cluster.

The issue is tracked on the dotnet/corefx github page.

Body:
I'm building a website using ASP.NET Core 2.0 (just upgraded from 1.1 one month ago). MongoDB is hosted by Mongo Atlas on AWS as well.This MongoDB instance has 3 replica set, require SSL to connect and already set can be access from any IP.

It runs quite ok on my machine (Windows 10 x64) and AWS (Windows Server 2016).

I try to deploy it on Linux machines, I use apt to install dotnet-runtime-2.0.0 on Ubuntu Server 16.04, then I try to run my site , and got the following error (for security reason I hide the exact server domain name)

System.TimeoutException: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = WritableServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-00-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-00-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..

and two same error for the rest of replica set.

But I can successfully connect to MongoDB server by MongoDB shell use the same machine.

Am I missing some dependencies on Ubuntu or there's a bug in MongoDB .NET SDK?

Full stacktrace:

System.TimeoutException: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = WritableServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-00-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-00-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.<ExecuteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.ConnectionInitializer.<InitializeConnectionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()" }, { ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-01-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-01-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.<ExecuteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.ConnectionInitializer.<InitializeConnectionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()" }, { ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/*****-shard-00-02-*****.mongodb.net:27017" }", EndPoint: "Unspecified/*****-shard-00-02-*****.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoCommandException: Command isMaster failed: no SNI name sent, make sure using a MongoDB 3.4+ driver/shell..
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
   at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.<ExecuteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.ConnectionInitializer.<InitializeConnectionAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
   --- End of inner exception stack trace ---
   at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()" }] }.
   at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description)
   at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask)
   at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Clusters.Cluster.SelectServer(IServerSelector selector, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Bindings.WritableServerBinding.GetWriteChannelSource(CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.CreateIndexesOperation.Execute(IWriteBinding binding, CancellationToken cancellationToken)
   at MongoDB.Driver.OperationExecutor.ExecuteWriteOperation[TResult](IWriteBinding binding, IWriteOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.ExecuteWriteOperation[TResult](IWriteOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.MongoIndexManager.CreateMany(IEnumerable`1 models, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoIndexManagerBase`1.CreateOne(IndexKeysDefinition`1 keys, CreateIndexOptions options, CancellationToken cancellationToken)


问:
Messaging Centre - Subscribing Event in the ViewModel Constructor
I am trying to send data from one ViewModel to another using Messaging Centre.
I have subscribed the event in 2nd ViewModel's constructor. But the event is not subscribed as the constructor is not compiled until I open the page/view  corresponding to the ViewModel.

I am using MVVM Light, until now I had an understanding that the VM's constructor are compiled when ViewModelLocator is called at the app startup.

Can someone help me understand this better and how can I subscribe the event i.e. compile the constructor without the VM being called.

答: Perhaps you are thinking about this in the wrong way. Without seeing code it's difficult to see what you are trying to achieve exactly, but what you could do is subscribe to the event elsewhere in your app, for example in your App.xaml.cs. When the event fires, at that point navigate to a new page of type ViewModel2 and pass any details required as a navigation parameter.</p>


问:
Caesar Cipher in Java. Encode, decode an rotate a String

Hi, I am trying to make a program, which allows the user to encode, decode and rotate a String. For example:

User Input: "Caesar"
System  Output: "Fdhvdu"

The user may decide how much the word is to be rotated. The program is not finished yet, I just made a method for option V: encode and wanted to know if I made it is appropriate? or if it works completely different way!

```<code>public class CaesarsChiffre {

    public static void main(String[] args) {

        char benutzerBefehl;
        String benutzerText;
        int rotation=0;

        System.out.println("Caesars Chiffre encode, decode, rotate.");
        System.out.println("Waehlen Sie:");
        System.out.println("V for encode");
        System.out.println("E for decode");
        System.out.println("B for rotation");
        benutzerBefehl=V; //Input.readChar();
        System.out.println("Enter text to encode:");
        benutzerText=Input.readString();
        System.out.println("which rotation do you want?");
        rotation=Input.readInt();

        switch (benutzerBefehl){
        case V: System.out.println(": Encoded text: "+Caesar.encode(benutzerText,rotation));
            break;
        case E: (": Decoded text: "+Ceasar.decode(benutzerText,rotation));
            break;
        case B: // will be filled
            break;
        default:
            System.out.println("Invalid option..");
        }

        public static String Caesar.encode(String original_text, int rot){

            String []s= original_text.split(" ");

            for(int i=0;i<s.length();i++){
                Stringbuilder letter=new StringBuilder();
                letter.append(s.[i]+rot);
            }

            return String;

        }

    }

}
</code>```

答:
You need to read something about oop, because you put everything to one single method, this is not java way. When you continue to write code in this way you will suffer and waste big amount of time trying to debug and understand what's going on. In resolving tasks first point is thinking, writing code is the last point. First we need to decomposit task. Caesar cypher is about to shift every letter in sentence to new position from it initial point. So we will create class Letter and tell this Letter class to shift itself to right or left.

```<code>public class Main {

    public static void main(String[] args) {
        String word = "Caesar";
        String expected = "Fdhvdu";
        String result = word.chars()
                .mapToObj(character -> new Letter((char) character))
                .map(letter -> letter.shiftRightTo(3))
                .map(letter -> letter.toString())
                .collect(Collectors.joining());
        System.out.println(result.equals(expected));
        System.out.println(result);
    }
}

class Letter {
    private final String alphabet = "abcdefghijklmnopqrstuvwxyz";
    private final boolean isLowerCase;
    private final char letter;

    public Letter(char letter) {
        this.isLowerCase = Character.isLowerCase(letter);
        this.letter = Character.toLowerCase(letter);
    }

    Letter shiftRightTo(final int shift) {
        int letterPosition = alphabet.indexOf(letter);
        for (int i = 0; i < shift; i++) {
            letterPosition++;
            if (letterPosition == alphabet.length()) {
                letterPosition = 0;
            }
        }
        char shiftedLetter = alphabet.charAt(letterPosition);
        return new Letter(isLowerCase ? shiftedLetter : Character.toUpperCase(shiftedLetter));
    }

    Letter shiftLeftTo(final int shift) {
        int letterPosition = alphabet.indexOf(letter);
        for (int i = 0; i < shift; i++) {
            letterPosition--;
            if (letterPosition == -1) {
                letterPosition = alphabet.length() - 1;
            }
        }
        char shiftedLetter = alphabet.charAt(letterPosition);
        return new Letter(isLowerCase ? shiftedLetter : Character.toUpperCase(shiftedLetter));
    }

    public String toString() {
        char result = isLowerCase ? letter : Character.toUpperCase(letter);
        return Character.toString(result);
    }
}
</code>```

This code works but need to refactor to remove code duplication. You may improve it further to introduce another one class that calls Word and hide existence of Letter class behind it.

Body:
Hi, I am trying to make a program, which allows the user to encode, decode and rotate a String. For example:

User Input: "Caesar"
System  Output: "Fdhvdu"

The user may decide how much the word is to be rotated. The program is not finished yet, I just made a method for option V: encode and wanted to know if I made it is appropriate? or if it works completely different way!

public class CaesarsChiffre {

    public static void main(String[] args) {

        char benutzerBefehl;
        String benutzerText;
        int rotation=0;

        System.out.println("Caesars Chiffre encode, decode, rotate.");
        System.out.println("Waehlen Sie:");
        System.out.println("V for encode");
        System.out.println("E for decode");
        System.out.println("B for rotation");
        benutzerBefehl=V; //Input.readChar();
        System.out.println("Enter text to encode:");
        benutzerText=Input.readString();
        System.out.println("which rotation do you want?");
        rotation=Input.readInt();

        switch (benutzerBefehl){
        case V: System.out.println(": Encoded text: "+Caesar.encode(benutzerText,rotation));
            break;
        case E: (": Decoded text: "+Ceasar.decode(benutzerText,rotation));
            break;
        case B: // will be filled
            break;
        default:
            System.out.println("Invalid option..");
        }

        public static String Caesar.encode(String original_text, int rot){

            String []s= original_text.split(" ");

            for(int i=0;i<s.length();i++){
                Stringbuilder letter=new StringBuilder();
                letter.append(s.[i]+rot);
            }

            return String;

        }

    }

}

Body:
You need to read something about oop, because you put everything to one single method, this is not java way. When you continue to write code in this way you will suffer and waste big amount of time trying to debug and understand what's going on. In resolving tasks first point is thinking, writing code is the last point. First we need to decomposit task. Caesar cypher is about to shift every letter in sentence to new position from it initial point. So we will create class Letter and tell this Letter class to shift itself to right or left.

public class Main {

    public static void main(String[] args) {
        String word = "Caesar";
        String expected = "Fdhvdu";
        String result = word.chars()
                .mapToObj(character -> new Letter((char) character))
                .map(letter -> letter.shiftRightTo(3))
                .map(letter -> letter.toString())
                .collect(Collectors.joining());
        System.out.println(result.equals(expected));
        System.out.println(result);
    }
}

class Letter {
    private final String alphabet = "abcdefghijklmnopqrstuvwxyz";
    private final boolean isLowerCase;
    private final char letter;

    public Letter(char letter) {
        this.isLowerCase = Character.isLowerCase(letter);
        this.letter = Character.toLowerCase(letter);
    }

    Letter shiftRightTo(final int shift) {
        int letterPosition = alphabet.indexOf(letter);
        for (int i = 0; i < shift; i++) {
            letterPosition++;
            if (letterPosition == alphabet.length()) {
                letterPosition = 0;
            }
        }
        char shiftedLetter = alphabet.charAt(letterPosition);
        return new Letter(isLowerCase ? shiftedLetter : Character.toUpperCase(shiftedLetter));
    }

    Letter shiftLeftTo(final int shift) {
        int letterPosition = alphabet.indexOf(letter);
        for (int i = 0; i < shift; i++) {
            letterPosition--;
            if (letterPosition == -1) {
                letterPosition = alphabet.length() - 1;
            }
        }
        char shiftedLetter = alphabet.charAt(letterPosition);
        return new Letter(isLowerCase ? shiftedLetter : Character.toUpperCase(shiftedLetter));
    }

    public String toString() {
        char result = isLowerCase ? letter : Character.toUpperCase(letter);
        return Character.toString(result);
    }
}

This code works but need to refactor to remove code duplication. You may improve it further to introduce another one class that calls Word and hide existence of Letter class behind it.


问:
SQLiteException failed to insert row
What are the possible reasons for a failed insertion into an sqlite3 database? The trace from the SQLiteException isn't especially helpful.

Is there any way to obtain better information about what caused the exception?

Where the table is created (sorry for any wonky spacing):

http://pastebin.com/QqUgdDz0

Where the values are parsed in endElement of a SAX parser:

http://pastebin.com/iN1M8QMe

Where the insert is called:

http://pastebin.com/xUqrmexw

Insert case in the provider:

```<code>case SUBMATERIAL_SINGLE_URI:
            rowId = db.insert(jobName+JobMetaData.SubmaterialTableMetaData.TABLE_NAME_SUFFIX,
                              JobMetaData.SubmaterialTableMetaData.TYPE, validValues);
            if (rowId > 0)
            {
                Uri submaterialUri = ContentUris.withAppendedId(JobMetaData.SubmaterialTableMetaData.CONTENT_URI,
                        rowId);
                getContext().getContentResolver().notifyChange(submaterialUri, null);
                return submaterialUri;
            }
            break;
</code>```

Stacktrace:

```<code>System.err( 8048): android.database.SQLException: Failed to insert row into content://dsndata.sds2mobile.jobprovider/C_1/submaterial/NULL
System.err( 8048):  at dsndata.sds2mobile.JobProvider.insert(JobProvider.java:341)
System.err( 8048):  at android.content.ContentProvider$Transport.insert(ContentProvider.java:180)
System.err( 8048):  at android.content.ContentResolver.insert(ContentResolver.java:587)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.endElement(MobileParser.java:227)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.endElement(XMLReaderAdapter.java:355)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.endElement(ExpatParser.java:160)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.append(Native Method)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:505)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:492)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:308)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:264)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.parse(XMLReaderAdapter.java:225)
System.err( 8048):  at javax.xml.parsers.SAXParser.parse(SAXParser.java:361)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.parse(MobileParser.java:120)
System.err( 8048):  at dsndata.sds2mobile.UI.onClick(UI.java:90)
System.err( 8048):  at android.view.View.performClick(View.java:2408)
System.err( 8048):  at android.view.View$PerformClick.run(View.java:8817)
System.err( 8048):  at android.os.Handler.handleCallback(Handler.java:587)
System.err( 8048):  at android.os.Handler.dispatchMessage(Handler.java:92)
System.err( 8048):  at android.os.Looper.loop(Looper.java:144)
System.err( 8048):  at android.app.ActivityThread.main(ActivityThread.java:4937)
System.err( 8048):  at java.lang.reflect.Method.invokeNative(Native Method)
System.err( 8048):  at java.lang.reflect.Method.invoke(Method.java:521)
System.err( 8048):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
System.err( 8048):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
System.err( 8048):  at dalvik.system.NativeStart.main(Native Method)
</code>```

I should note that NULL in the URI here is a string value and is acceptable according to the URI matching scheme. This is a test run and isn't using real values yet.

Update:
It turns out that my partner (who was producing the XML) left out a few items. Got it all figured out.

Thanks for your help! I appreciate the time.

答: Maybe you're trying to insert a row that violates a "PRIMARY KEY" or "UNIQUE" restriction (I see, though, that you don't have any "UNIQUE" fields in your database)?</p>

Title: SQLiteException failed to insert row

Body:
What are the possible reasons for a failed insertion into an sqlite3 database? The trace from the SQLiteException isn't especially helpful.

Is there any way to obtain better information about what caused the exception?

Where the table is created (sorry for any wonky spacing):

http://pastebin.com/QqUgdDz0

Where the values are parsed in endElement of a SAX parser:

http://pastebin.com/iN1M8QMe

Where the insert is called:

http://pastebin.com/xUqrmexw

Insert case in the provider:

case SUBMATERIAL_SINGLE_URI:
            rowId = db.insert(jobName+JobMetaData.SubmaterialTableMetaData.TABLE_NAME_SUFFIX,
                              JobMetaData.SubmaterialTableMetaData.TYPE, validValues);
            if (rowId > 0)
            {
                Uri submaterialUri = ContentUris.withAppendedId(JobMetaData.SubmaterialTableMetaData.CONTENT_URI,
                        rowId);
                getContext().getContentResolver().notifyChange(submaterialUri, null);
                return submaterialUri;
            }
            break;

Stacktrace:

System.err( 8048): android.database.SQLException: Failed to insert row into content://dsndata.sds2mobile.jobprovider/C_1/submaterial/NULL
System.err( 8048):  at dsndata.sds2mobile.JobProvider.insert(JobProvider.java:341)
System.err( 8048):  at android.content.ContentProvider$Transport.insert(ContentProvider.java:180)
System.err( 8048):  at android.content.ContentResolver.insert(ContentResolver.java:587)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.endElement(MobileParser.java:227)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.endElement(XMLReaderAdapter.java:355)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.endElement(ExpatParser.java:160)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.append(Native Method)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:505)
System.err( 8048):  at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:492)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:308)
System.err( 8048):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:264)
System.err( 8048):  at org.xml.sax.helpers.XMLReaderAdapter.parse(XMLReaderAdapter.java:225)
System.err( 8048):  at javax.xml.parsers.SAXParser.parse(SAXParser.java:361)
System.err( 8048):  at dsndata.sds2mobile.parser.MobileParser.parse(MobileParser.java:120)
System.err( 8048):  at dsndata.sds2mobile.UI.onClick(UI.java:90)
System.err( 8048):  at android.view.View.performClick(View.java:2408)
System.err( 8048):  at android.view.View$PerformClick.run(View.java:8817)
System.err( 8048):  at android.os.Handler.handleCallback(Handler.java:587)
System.err( 8048):  at android.os.Handler.dispatchMessage(Handler.java:92)
System.err( 8048):  at android.os.Looper.loop(Looper.java:144)
System.err( 8048):  at android.app.ActivityThread.main(ActivityThread.java:4937)
System.err( 8048):  at java.lang.reflect.Method.invokeNative(Native Method)
System.err( 8048):  at java.lang.reflect.Method.invoke(Method.java:521)
System.err( 8048):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
System.err( 8048):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
System.err( 8048):  at dalvik.system.NativeStart.main(Native Method)

I should note that NULL in the URI here is a string value and is acceptable according to the URI matching scheme. This is a test run and isn't using real values yet.

Update:
It turns out that my partner (who was producing the XML) left out a few items. Got it all figured out.

Thanks for your help! I appreciate the time.


问:
update apk programmatically (without root)
I want to update my android application programmatically.

I used following code:

```<code> final Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setDataAndType(Uri.fromFile(new
       File(Environment.getExternalStorageDirectory()+"/AndroidTest.apk")), "application/vnd.android.package-archive");

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

This code display dialogue box to install application.

I want to install apk automatically.

Please help me.

答:
Yes It is possible Please check this out
For this you need SUPER_USERACCESS
Add this permission: <uses-permission android:name="android.permission.ACCESS_SUPERUSER" />

Body:
I want to update my android application programmatically.

I used following code:

 final Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setDataAndType(Uri.fromFile(new
       File(Environment.getExternalStorageDirectory()+"/AndroidTest.apk")), "application/vnd.android.package-archive");

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

This code display dialogue box to install application.

I want to install apk automatically.

Please help me.


问:
powershell script to get both size and size on disk of directory
I was writing a power shell script to get a size of directory

```<code>(get-childitem <path> -recurse | measure-object -property length -sum).sum/1MB
</code>```

now I want both "size" and "size on the disk" of a folder to be displayed as output

答:
Try this:</p>
```<code>GCI <Path> -Recurse |
Group-Object -Property Directory | % {
  New-Object psobject -Property @{
    Name = $_.Name
    Size = ($_.Group | ? {!($_.PSIsContainer)} | Measure-Object Length -Sum).Sum
  }
} |
Sort-Object -Property Size -Descending
</code>```

Body:
I was writing a power shell script to get a size of directory

(get-childitem <path> -recurse | measure-object -property length -sum).sum/1MB

now I want both "size" and "size on the disk" of a folder to be displayed as output

Body:
Try this:

GCI <Path> -Recurse |
Group-Object -Property Directory | % {
  New-Object psobject -Property @{
    Name = $_.Name
    Size = ($_.Group | ? {!($_.PSIsContainer)} | Measure-Object Length -Sum).Sum
  }
} |
Sort-Object -Property Size -Descending

ContentLicense: CC BY-SA 4.0


问:
Getting Error while Reading Excel Using Spring-batch-excel
I am using Spring-batch-excel for reading a excel file in my new application. It is configured as a batch job and triggered using JobManager. Now i getting this error.
InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream

```<code>Caused by: java.lang.IllegalStateException: InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream
at org.springframework.batch.item.excel.poi.PoiItemReader.openExcelFile(PoiItemReader.java:82) ~[spring-batch-excel-0.5.0-SNAPSHOT.jar:?]
at org.springframework.batch.item.excel.AbstractExcelItemReader.doOpen(AbstractExcelItemReader.java:111) ~[spring-batch-excel-0.5.0-SNAPSHOT.jar:?]
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:144) ~[spring-batch-infrastructure-3.0.5.RELEASE.jar:3.0.5.RELEASE].
</code>```

Any please help me.

答:
I know this is an old issue , but i faced this issue, yet for those who have the same issue like me, i commented out this code of block and it worked

```<code>if (!workbookStream.markSupported() && !(workbookStream instanceof PushbackInputStream)) {
        throw new IllegalStateException("InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream");
    }
</code>```

to understand why please refer to this code :
https://github.com/spring-projects/spring-batch-extensions/issues/34

Body:
I am using Spring-batch-excel for reading a excel file in my new application. It is configured as a batch job and triggered using JobManager. Now i getting this error.
InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream

Caused by: java.lang.IllegalStateException: InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream
at org.springframework.batch.item.excel.poi.PoiItemReader.openExcelFile(PoiItemReader.java:82) ~[spring-batch-excel-0.5.0-SNAPSHOT.jar:?]
at org.springframework.batch.item.excel.AbstractExcelItemReader.doOpen(AbstractExcelItemReader.java:111) ~[spring-batch-excel-0.5.0-SNAPSHOT.jar:?]
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:144) ~[spring-batch-infrastructure-3.0.5.RELEASE.jar:3.0.5.RELEASE].

Any please help me.

Body:
I know this is an old issue , but i faced this issue, yet for those who have the same issue like me, i commented out this code of block and it worked

if (!workbookStream.markSupported() && !(workbookStream instanceof PushbackInputStream)) {
        throw new IllegalStateException("InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream");
    }

to understand why please refer to this code :
https://github.com/spring-projects/spring-batch-extensions/issues/34