问:
Rendering from method after Ajax post request in Google App Engine
I'm using Ajax $.post() to post the content of a form to my controller in google app engine.  The form basically is trying to find lat/lng using html5 geolocation and user input.

```<code>        <form method="post" id="simple-form" action="/search">
        <div>
            <input type="text" placeholder="Keyword" name="searchQuery"  id="searchQuery">
            <input type="button" id="simple-submit-button">
        </div> </form>
</code>```

Trying to find geolocation

```<code>$('#simple-submit-button').click(function () {
     navigator.geolocation.getCurrentPosition(onSuccess, onError);
})

function onSuccess(position) {
    document.getElementById('Latitude').value = position.coords.latitude;
    document.getElementById('Longitude').value = position.coords.longitude;
    var x = document.getElementById('Latitude').value;
    if (x != undefined || x != null) {
        submitform();
    }
}
</code>```

Using jquery $.post() to post the content to a method and render another page.

```<code>function submitform() {
    var where = $("#simple-firm").attr("action");
    var fi = $("#Latitude").val();
    var fj = $("#Longitude").val();
    var gk = $("#searchQuery").val();
    var what = {Latitude: fi, Longitude: fj, searchQuery: gk};
    $.post(where, what, handleResponse, "json");
}
</code>```

Following is my router.py

```<code>from webapp2 import WSGIApplication
from webapp2 import Route

app = WSGIApplication([
    Route('/search', handler='app.serp.Search'),
}
</code>```

and my method

```<code>class Search():
def get(self):
    self.redirect('/')

def post(self):
    query_name = self.request.get('searchQuery')
    lat = float(self.request.get('Latitude'))
    lng = float(self.request.get('Longitude'))
    print query_name,lat, lng
    #self.response.out.write('<html><body>You wrote:```')
    self.render('serp/serp.html')
```

Although I can see in my terminal that the values of query_name, lat, lng from the are being printed,  but neither the self.render nor self.response is displayed.  I basically want to render another page called serp.html. What is going wrong here. How to fix it.

答:
First, read this webapp2 documentation on rendering templates. Templates are basically just html files where you can inject your own variables in to the html before serving the page (or you can just serve the html as-is).

Judging by that documentation, you probably want to do this:

```<code>import os
import webapp2
from google.appengine.ext.webapp import template

# don't forget to extend webapp2.RequestHandler
class Search(webapp2.RequestHandler):
    def get(self):
        self.redirect('/')

    def post(self):
        query_name = self.request.get('searchQuery')
        lat = float(self.request.get('Latitude'))
        lng = float(self.request.get('Longitude'))
        print query_name,lat, lng

        template_values = {
            'query_name': query_name,
            'lat': lat,
            'lng': lng
        }
        path = os.path.join(os.path.dirname(__file__), 'serp/serp.html')
        self.response.out.write(template.render(path, template_values))
</code>```

However, your question is a bit strange to me. You are returning an html page to an AJAX post request? Typically, you either do:

A normal HTTP Post (not AJAX, synchronous, basically posting a normal form) and the response will be a new webpage (your html) file

An AJAX post, where your jquery/javascript handles the response, and the response is in XML or JSON, not html.

You are doing some hybrid of the two where AJAX is receiving a new html page, which you could still make work just fine, but it's kind of weird. You might find it easier to respond with json or xml, and use jquery/AJAX to handle the json response or xml by setting the dataType of the post request. Your call.

Body:
I'm using Ajax $.post() to post the content of a form to my controller in google app engine.  The form basically is trying to find lat/lng using html5 geolocation and user input.

        <form method="post" id="simple-form" action="/search">

            <input type="text" placeholder="Keyword" name="searchQuery"  id="searchQuery">
            <input type="button" id="simple-submit-button">

 </form>

Trying to find geolocation

$('#simple-submit-button').click(function () {
     navigator.geolocation.getCurrentPosition(onSuccess, onError);
})

function onSuccess(position) {
    document.getElementById('Latitude').value = position.coords.latitude;
    document.getElementById('Longitude').value = position.coords.longitude;
    var x = document.getElementById('Latitude').value;
    if (x != undefined || x != null) {
        submitform();
    }
}

Using jquery $.post() to post the content to a method and render another page.

function submitform() {
    var where = $("#simple-firm").attr("action");
    var fi = $("#Latitude").val();
    var fj = $("#Longitude").val();
    var gk = $("#searchQuery").val();
    var what = {Latitude: fi, Longitude: fj, searchQuery: gk};
    $.post(where, what, handleResponse, "json");
}

Following is my router.py

from webapp2 import WSGIApplication
from webapp2 import Route

app = WSGIApplication([
    Route('/search', handler='app.serp.Search'),
}

and my method

class Search():
def get(self):
    self.redirect('/')

def post(self):
    query_name = self.request.get('searchQuery')
    lat = float(self.request.get('Latitude'))
    lng = float(self.request.get('Longitude'))
    print query_name,lat, lng
    #self.response.out.write('You wrote:
')
    self.render('serp/serp.html')

Although I can see in my terminal that the values of query_name, lat, lng from the are being printed,  but neither the self.render nor self.response is displayed.  I basically want to render another page called serp.html. What is going wrong here. How to fix it.

Body:
First, read this webapp2 documentation on rendering templates. Templates are basically just html files where you can inject your own variables in to the html before serving the page (or you can just serve the html as-is).

Judging by that documentation, you probably want to do this:

import os
import webapp2
from google.appengine.ext.webapp import template

# don't forget to extend webapp2.RequestHandler
class Search(webapp2.RequestHandler):
    def get(self):
        self.redirect('/')

    def post(self):
        query_name = self.request.get('searchQuery')
        lat = float(self.request.get('Latitude'))
        lng = float(self.request.get('Longitude'))
        print query_name,lat, lng

        template_values = {
            'query_name': query_name,
            'lat': lat,
            'lng': lng
        }
        path = os.path.join(os.path.dirname(__file__), 'serp/serp.html')
        self.response.out.write(template.render(path, template_values))

However, your question is a bit strange to me. You are returning an html page to an AJAX post request? Typically, you either do:

A normal HTTP Post (not AJAX, synchronous, basically posting a normal form) and the response will be a new webpage (your html) file

An AJAX post, where your jquery/javascript handles the response, and the response is in XML or JSON, not html.

You are doing some hybrid of the two where AJAX is receiving a new html page, which you could still make work just fine, but it's kind of weird. You might find it easier to respond with json or xml, and use jquery/AJAX to handle the json response or xml by setting the dataType of the post request. Your call.


来源: stackexchange

问:
Chrome extension - select2 library working into console but not in content.js
Hello i'm working on a google chrome extension and workaround with https://select2.github.io .

Here is my manifest:

```<code>{
    "manifest_version": 2,

    "name": "Extension Test",
    "description": "Test extension",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": ["https://www.mywebsite.com/*"],
            "js": ["jquery-1.11.3.js", "content.js"]
        }
    ],
    "background": {
        "scripts": ["jquery-1.11.3.js","background.js"]
    },
    "permissions": [
        "activeTab",
        "webNavigation",
        "*://*/*"
    ]
}
</code>```

Here is what i run directly into console:

```<code>$('#myselect2').select2('open');
</code>```

Then the same code into content js is not working and firing the following error:

```<code>content.js:151 Uncaught TypeError: $(...).select2 is not a function
</code>```

Is it possible to open select menu from extension to content of website and if so how ?

答:
Try Replacing with </p>

```<code>{
    "manifest_version": 2,

    "name": "Extension Test",
    "description": "Test extension",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": ["https://www.mywebsite.com/*"],
            "js": ["jquery-1.11.3.js", "content.js"]
        }
    ],
    "background": {
        "scripts": ["jquery-1.11.3.js","background.js"]
    },
    "permissions": [
        "activeTab",
        "webNavigation",
        "*://*/*"
    ]
}
</code>```

<p>you are missing a '"' in the matches property. </p>

ContentLicense: CC BY-SA 3.0

Body:
Hello i'm working on a google chrome extension and workaround with https://select2.github.io .

Here is my manifest:

{
    "manifest_version": 2,

    "name": "Extension Test",
    "description": "Test extension",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": ["https://www.mywebsite.com/*"],
            "js": ["jquery-1.11.3.js", "content.js"]
        }
    ],
    "background": {
        "scripts": ["jquery-1.11.3.js","background.js"]
    },
    "permissions": [
        "activeTab",
        "webNavigation",
        "*://*/*"
    ]
}

Here is what i run directly into console:

$('#myselect2').select2('open');

Then the same code into content js is not working and firing the following error:

content.js:151 Uncaught TypeError: $(...).select2 is not a function

Is it possible to open select menu from extension to content of website and if so how ?

Body:
Try Replacing with

{
    "manifest_version": 2,

    "name": "Extension Test",
    "description": "Test extension",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": ["https://www.mywebsite.com/*"],
            "js": ["jquery-1.11.3.js", "content.js"]
        }
    ],
    "background": {
        "scripts": ["jquery-1.11.3.js","background.js"]
    },
    "permissions": [
        "activeTab",
        "webNavigation",
        "*://*/*"
    ]
}

you are missing a '"' in the matches property.


问:
Access to private methods in private class
How can I have access to a private method in a private class?

My code:

```<code>public class OuterClass {

    private InnerClass ic;

    public OuterClass(){ //Constructor
        this.ic = new InnerClass();
    }

    public InnerClass getInnerClass(){
        return this.ic;
    }

    private class InnerClass {
        private VeryInnerClass vic;

        private void InnerClass(){
            this.vic = new VeryInnerClass();
        }

        private void method(Object item){
            //Job
        }

        private class VeryInnerClass {
            private Object item;

            private void VeryInnerClass(){
                //Constructor
            }

        }//End VeryInnerClass

    }//End InnerClass

}//End OuterClass
</code>```

This is the main code:

```<code>public class Main {

    public static void main(String[] args) {

        OuterClass oc = new OuterClass();
        Object item = new Object();

        oc.getInnerClass().method(item);

    }

}
</code>```

The error is that the type OuterClass.InnerClass is not visible, but I used a getInnerClass() method, so I don't know how to have access to method(Object item).

答:
No, you can't.

The private modifier specifies that the member can only be accessed in its own class

So, if you want to access to private methods, then you should define them with the public, protected or no modifier depending what is more appropriate in that case.

See more in this doc

Body:
How can I have access to a private method in a private class?

My code:

public class OuterClass {

    private InnerClass ic;

    public OuterClass(){ //Constructor
        this.ic = new InnerClass();
    }

    public InnerClass getInnerClass(){
        return this.ic;
    }

    private class InnerClass {
        private VeryInnerClass vic;

        private void InnerClass(){
            this.vic = new VeryInnerClass();
        }

        private void method(Object item){
            //Job
        }

        private class VeryInnerClass {
            private Object item;

            private void VeryInnerClass(){
                //Constructor
            }

        }//End VeryInnerClass

    }//End InnerClass

}//End OuterClass

This is the main code:

public class Main {

    public static void main(String[] args) {

        OuterClass oc = new OuterClass();
        Object item = new Object();

        oc.getInnerClass().method(item);

    }

}

The error is that the type OuterClass.InnerClass is not visible, but I used a getInnerClass() method, so I don't know how to have access to method(Object item).


问:
Do while loop runs more than once with flag set?
I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.

EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.

```<code>voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);

//Calibration routine
do {
  if ((voltage >= 1) && (voltage <= 10)) {
    //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    digitalWrite(calibrationLED, LOW);
    delay(1000);
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    Serial.println("Calibrated");
    delay(5000);
    voltageInitial = analogRead(A0);
    //stores the initial voltage to a separate variable, does not change over the course of the crimp
    Serial.println("Initial Voltage: ");
    Serial.println(voltageInitial);
    flag = 1;
  }
} while (flag == 0);
</code>```

答: This is an infinite loop actually until the value of the voltage comes between 1 to 10. so flag=1 should be out of the if condition. Otherwise you can add a break after if condition is finished. It will execute exactly once after the condition.

Body:
I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.

EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.

voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);

//Calibration routine
do {
  if ((voltage >= 1) && (voltage <= 10)) {
    //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    digitalWrite(calibrationLED, LOW);
    delay(1000);
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    Serial.println("Calibrated");
    delay(5000);
    voltageInitial = analogRead(A0);
    //stores the initial voltage to a separate variable, does not change over the course of the crimp
    Serial.println("Initial Voltage: ");
    Serial.println(voltageInitial);
    flag = 1;
  }
} while (flag == 0);


问:
Deleting lucene document by id
How can I delete single document from Lucene index?
There's no method deleteDocument(int docId) and I can't find a query that selects just one document based on docId...

using Lucene 4.10.3
Thanks

答:
While merging multiple shards into one big core, I accidentally merged two time the same core, resulting in group of documents having the same value for the id field. To solve the problem, I used this code to delete documents by their positional id:</p>

```<code>public class IndexCleaner {

  public static void main(String[] args) {
    try (Directory dir = FSDirectory.open(new File(args[0]));
        IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(Version.LUCENE_4_10_4, null));
        IndexReader reader = DirectoryReader.open(writer, false);) {
      int numDocs = reader.numDocs();
      Set<String> items = new HashSet<>(numDocs);
      for (int i = numDocs - 1; i >= 0; i--) {
        String id = reader.document(i).get("id");
        if (items.contains(id)) {
          writer.tryDeleteDocument(reader, i);
          System.out.println("Document with id \"" + id + "\" marked for deletion");
        }
        else {
          items.add(id);
        }
      }

      writer.commit();
    }
    catch (Throwable e) {
      e.printStackTrace();
    }
  }
}
</code>```

Title: Deleting lucene document by id

Body:
While merging multiple shards into one big core, I accidentally merged two time the same core, resulting in group of documents having the same value for the id field. To solve the problem, I used this code to delete documents by their positional id:

public class IndexCleaner {

  public static void main(String[] args) {
    try (Directory dir = FSDirectory.open(new File(args[0]));
        IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(Version.LUCENE_4_10_4, null));
        IndexReader reader = DirectoryReader.open(writer, false);) {
      int numDocs = reader.numDocs();
      Set<String> items = new HashSet<>(numDocs);
      for (int i = numDocs - 1; i >= 0; i--) {
        String id = reader.document(i).get("id");
        if (items.contains(id)) {
          writer.tryDeleteDocument(reader, i);
          System.out.println("Document with id \"" + id + "\" marked for deletion");
        }
        else {
          items.add(id);
        }
      }

      writer.commit();
    }
    catch (Throwable e) {
      e.printStackTrace();
    }
  }
}


问:
XML Validation error : EntityRef: expecting ';'
I am using PHP's SimpleXML to process an XML file, and get this error:

```<code>Message: simplexml_load_string(): Entity: line 9: parser error : EntityRef: expecting ';'
</code>```

A quick Google search reveals that this is generally caused by an un-escaped & - there's a dozen questions with that answer here on Stack Overflow.  However, here's line 9 of the file:

```<code><p>In-kingdom commentary on the following items can be found on the November LoP. https://oscar.sca.org/kingdom/kingloi.php?kingdom=9&loi=4191</p>
</code>```

As you can see, the & is escaped.  A text search on the file reveals no other instances of &.

What am I missing?

Please note:  I have no ability to edit the XML file - I must take it as it comes and only fix things in my code.  I currently open the XML with the following code:

```<code>    $rawstring = file_get_contents($filename);
    $safestring = html_entity_decode($rawstring, 0, 'ISO-8859-1');
    $xmlstring = simplexml_load_string($safestring);
</code>```

(the html_entity_decode is necessary as the file uses Latin-1 encoding and simplexml expects UTF-8)

Help appreciated.

答:
html_entity_decode() is not intended for what you appear to think it is intended for and is actually exactly what is causing your problem. As the name suggests: it decodes html entities, like &, into their actual representation; in the case of & => &.

If you want to convert the character encoding of the original $rawstring to ISO-8859-1 or UTF-8 you should use something like iconv() or mb_convert_encoding().

Here's an example that should work:

```<code>$rawstring = file_get_contents($filename);
$safestring = mb_convert_encoding($rawstring, 'ISO-8859-1' /*, $optionalOriginalEncoding */);
$xmlstring = simplexml_load_string($safestring);
</code>```

See the list of supported encodings, as well.

However, since the original $rawstring is Latin-1, conversion to ISO-8859-1 is pointless, since Latin-1 is ISO-8859-1. You may need to convert to UTF-8, but I'm fairly certain that that's not even necessary either.

Body:
I am using PHP's SimpleXML to process an XML file, and get this error:

Message: simplexml_load_string(): Entity: line 9: parser error : EntityRef: expecting ';'

A quick Google search reveals that this is generally caused by an un-escaped & - there's a dozen questions with that answer here on Stack Overflow.  However, here's line 9 of the file:

In-kingdom commentary on the following items can be found on the November LoP. https://oscar.sca.org/kingdom/kingloi.php?kingdom=9&loi=4191

As you can see, the & is escaped.  A text search on the file reveals no other instances of &.

What am I missing?

Please note:  I have no ability to edit the XML file - I must take it as it comes and only fix things in my code.  I currently open the XML with the following code:

    $rawstring = file_get_contents($filename);
    $safestring = html_entity_decode($rawstring, 0, 'ISO-8859-1');
    $xmlstring = simplexml_load_string($safestring);

(the html_entity_decode is necessary as the file uses Latin-1 encoding and simplexml expects UTF-8)

Help appreciated.

Body:
html_entity_decode() is not intended for what you appear to think it is intended for and is actually exactly what is causing your problem. As the name suggests: it decodes html entities, like &amp;, into their actual representation; in the case of &amp; => &.

If you want to convert the character encoding of the original $rawstring to ISO-8859-1 or UTF-8 you should use something like iconv() or mb_convert_encoding().

Here's an example that should work:

$rawstring = file_get_contents($filename);
$safestring = mb_convert_encoding($rawstring, 'ISO-8859-1' /*, $optionalOriginalEncoding */);
$xmlstring = simplexml_load_string($safestring);

See the list of supported encodings, as well.

However, since the original $rawstring is Latin-1, conversion to ISO-8859-1 is pointless, since Latin-1 is ISO-8859-1. You may need to convert to UTF-8, but I'm fairly certain that that's not even necessary either.


问:
How to add support for 10.5 inch iPad Pro
I've just downloaded the latest Xcode 8.3.3 update from the MAS. I was wondering how to add support for the new 10.5-inch iPad Pro?

I'm using storyboards with auto-layout, a launch screen storyboard and all app icon sizes are added to the xcassets.

答:
I believe that the auto-layout launch screen story board should be all that is needed. However, I have found that if I build an application under Xcode 8.3.3, the UIScreen.mainScreen.bounds returns 736 x 1024. If I build the same application under Xcode 9 and the iOS 11 SDK beta, UIScreen.mainScreen.bounds returns 834 x 1112.

UPDATE:

As others have mentioned, when an app is built with Xcode 8.3.3/iOS 10.3 and is running on the iPad Pro 10.5 simulator, the UIRequiresFullScreen key in the app info.list determines whether or not the app is scaled to 768 x 1024. If UIRequiresFullScreen = YES, the app is scaled. If UIRequiresFullScreen = NO, the app is full resolution (834 x 1112).

However, if the app is built with Xcode 9/iOS 11 beta 1, it always runs at the full native resolution regardless of the UIRequiresFullScreen key setting. Some developers believe that this is intentional behavior and not a bug. Others believe it is simply an artifact of running the iOS 10 app under the iOS 11 simulator. We probably won't know for sure until developers receive the new hardware.


问:
Array of objects in Javascript
I'm new to learning Javascript. at this stage, I want to use/decalre/initialize an array of objects.

Here is my code to initialise an object :

```<code>function player(name){
    this.name = name;

    this.getName = function(){
        alert(this.name);
    }
}
</code>```

and here is where I need to use the array of players(objects)

```<code>function hallOfFame(nbrPlayers){
    var arrayOfPlayers = []

}
</code>```

Can anyone help me please how to create this array of objects. Thank you in advance :)

答:
```<code>//making array of books
var books = [];
    var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
    books.push(new_book);
    new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
    books.push(new_book);
    console.log(books[0].id);
    console.log(books[0].name);
    console.log(books[0].category);
    console.log(books[0].price);

// also we have array of albums
var albums = []
    var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
    albums.push(new_album);
    new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
    albums.push(new_album);
//Now, content[0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);

console.log(my_albums[0].name);
console.log(my_albums[1].name);
</code>```

This Example Works with me:
Expected output

Title: Array of objects in Javascript

Body:
I'm new to learning Javascript. at this stage, I want to use/decalre/initialize an array of objects.

Here is my code to initialise an object :

function player(name){
    this.name = name;

    this.getName = function(){
        alert(this.name);
    }
}

and here is where I need to use the array of players(objects)

function hallOfFame(nbrPlayers){
    var arrayOfPlayers = []

}

Can anyone help me please how to create this array of objects. Thank you in advance :)

Body:
//making array of books
var books = [];
    var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
    books.push(new_book);
    new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
    books.push(new_book);
    console.log(books[0].id);
    console.log(books[0].name);
    console.log(books[0].category);
    console.log(books[0].price);

// also we have array of albums
var albums = []
    var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
    albums.push(new_album);
    new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
    albums.push(new_album);
//Now, content[0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);

console.log(my_albums[0].name);
console.log(my_albums[1].name);

This Example Works with me:
Expected output


问:
Understanding VBScript
I have a VBScript that I`m converting to PHP, I hae some part that I don`t understand and don`t know the output of ... Also if possible, provide me with a similar method in HTML/PHP

```<code>TextBox1.Value = 1#
txtTurnoverIncl = TextBox1
Format(CDbl(txtTurnoverExcl.Text) * _
                             CDbl(txtRoyalty.Text) / 100, "#,##0.00")
If txtTurnoverExcl.Text <> "" Then
Format(Round(.Text * 14 / 114, 2), "#,##0.00")
TextBox1 = Now()
TextBox3 = Date
TextBox4 = Format(MyDate, "dddd")
</code>```

And this function:

```<code>Private Function SumCashUp() As Double
    Dim i As Long
    Dim tmp As Double
    For i = 10 To 12
        With Me.Controls("TextBox" & i)
            If IsNumeric(.Text) Then
                tmp = tmp + CDbl(.Text)
            End If
        End With
    Next i
    SumCashUp = tmp
End Function
</code>```

I guess thats all.

答:
first of all it would be better to analyze what the whole thing is doing (semantically) rather than looking at sequences of code. So the remainder of this post is a bit speculative ....

There are a couple of textboxes displayed on the screen

TextBox1 ... initialized with value 1(double), later containing current time (now()) (imho a sin in itself - brrrr - hope there is good business logic explanation for this)

TextBox3 ... initialized with the current date

TextBox4 ... initialized with "something we don't know" - hopefully a date (MyDate), and formated as Weekday ("dddd")

TextBox10 - TextBox12 ... seem to be used to calculate a variable SumCashUp

we have some more variables which may be textboxes as well (as sometimes we see a .Text added in the code)

txtTurnoverIncl

txtTurnoverExcl

txtRoyalty

SumCashUp

and a code fragment that calculates a 14% margin from a Gross (*14/114), rounds and formats the result ... and we have no clue about where this result is used. We can speculate that it may be another form field (because of .Text) - maybe txtRoyalty - but we don't know.

Basically all the code fragments are about putting values into textboxes displayed on the screen and/or using the values of that text boxes to compute something (like the SumCashUp or a 14% GM).

So I guess the path to the solution must be

get the source layout of textboxes

understand the business logic

create a HTML page containing a form with similar objects (textboxes, a submit button, etc.)

write PHP code that implements the business logic - most probably as a reaction to a POST event triggered by a Submit button

You already received a couple of code fragments, but one needs to put this into a greater context, otherwise the code blocks won't help.

ContentLicense: CC BY-SA 2.5

Title: Understanding VBScript

Body:
I have a VBScript that I`m converting to PHP, I hae some part that I don`t understand and don`t know the output of ... Also if possible, provide me with a similar method in HTML/PHP

TextBox1.Value = 1#
txtTurnoverIncl = TextBox1
Format(CDbl(txtTurnoverExcl.Text) * _
                             CDbl(txtRoyalty.Text) / 100, "#,##0.00")
If txtTurnoverExcl.Text <> "" Then
Format(Round(.Text * 14 / 114, 2), "#,##0.00")
TextBox1 = Now()
TextBox3 = Date
TextBox4 = Format(MyDate, "dddd")

And this function:

Private Function SumCashUp() As Double
    Dim i As Long
    Dim tmp As Double
    For i = 10 To 12
        With Me.Controls("TextBox" & i)
            If IsNumeric(.Text) Then
                tmp = tmp + CDbl(.Text)
            End If
        End With
    Next i
    SumCashUp = tmp
End Function

I guess thats all.


问:
SPARK individual upgrade to 2.1.0 in Ambari HDP 2.5.0
I want to upgrade my SPark component to 2.1.0 from its default 2.0.x.2.5 in Ambari.

I am using HDP 2.5.0 with Ambari 2.4.2.

Appreciate any idea to achieve this.

答:
Newer versions of Ambari (maybe 3.0) probably will support per-component upgrade/multiple component versions

See https://issues.apache.org/jira/browse/AMBARI-12556 for details.


问:
Is there an elegant way to extract individual words from variable names into an array?
Basically I want to do this:

I get a string "myVariableName" and turn it into: ["my", "variable", "name"]

I tried doing this using regex, but I get a lot of undefineds in my ending array it seems. The two possible cases for variable names are camel-case and upper snake-case in this situation.

```<code>const matchVariableNames =  /(\b[a-z]+)|([A-Z][a-z]+)|(\b[A-Z]+)|(_[A-Z]+)/g;
const variableName = 'myVariable';
let words = [];
let regexMatches;

while (regexMatches = matchVariableNames.exec(variableName)) {
  regexMatches.forEach((match) => {
    words.push(match);
  });
};
</code>```

outputs:

```<code>["my", "my", undefined, undefined, undefined, "Variable", undefined, "Variable", undefined, undefined]
undefined
</code>```

答:
You could use a positive lookahead with uppercase letters. Then map only lower case letters.

var string = 'myVariableName',
    array = string.split(/(?=[A-Z])/).map(a => a.toLowerCase());

console.log(array);```

Body:
Basically I want to do this:

I get a string "myVariableName" and turn it into: ["my", "variable", "name"]

I tried doing this using regex, but I get a lot of undefineds in my ending array it seems. The two possible cases for variable names are camel-case and upper snake-case in this situation.

const matchVariableNames =  /(\b[a-z]+)|([A-Z][a-z]+)|(\b[A-Z]+)|(_[A-Z]+)/g;
const variableName = 'myVariable';
let words = [];
let regexMatches;

while (regexMatches = matchVariableNames.exec(variableName)) {
  regexMatches.forEach((match) => {
    words.push(match);
  });
};

outputs:

["my", "my", undefined, undefined, undefined, "Variable", undefined, "Variable", undefined, undefined]
undefined


问:
Stripe.NET add bank account using token to Stripe Managed Account
I've searched through Jayme Davis' documentation, and I cannot find how to add a bank account using a token to a Stripe Managed Account.  The only way it appears to add a bank account in the documentation, is by using the CustomerBankAccount object, which requires a CustomerID as a parameter, and does not work with an AccountID (i.e. Managed Account ID).  I essentially would like to make this request (from Stipe's website) using Stripe.NET and C# code.  Any help would be greatly appreciated!  Thank you in advance!</p>

```<code>curl https://api.stripe.com/v1/accounts/acct_1032D82eZvKYlo2C/external_accounts \
   -u sk_test_xxxxxxxxxxxxxxxxxxxxxx: \
   -d external_account=btok_xxxxxxxxxxxxxxxxxxx
</code>```

答:
You can use the ExternalBankAccount property for this and see an example in the test here

```<code>var params = new StripeAccountUpdateOptions();
params.ExternalBankAccount = new StripeAccountBankAccountOptions
{
    TokenId = _token.Id
}

var accountService = new StripeAccountService();
StripeAccount response = accountService.Update("acct_XXX", params);
</code>```

Body:
I've searched through Jayme Davis' documentation, and I cannot find how to add a bank account using a token to a Stripe Managed Account.  The only way it appears to add a bank account in the documentation, is by using the CustomerBankAccount object, which requires a CustomerID as a parameter, and does not work with an AccountID (i.e. Managed Account ID).  I essentially would like to make this request (from Stipe's website) using Stripe.NET and C# code.  Any help would be greatly appreciated!  Thank you in advance!

curl https://api.stripe.com/v1/accounts/acct_1032D82eZvKYlo2C/external_accounts \
   -u sk_test_xxxxxxxxxxxxxxxxxxxxxx: \
   -d external_account=btok_xxxxxxxxxxxxxxxxxxx

Body:
You can use the ExternalBankAccount property for this and see an example in the test here

var params = new StripeAccountUpdateOptions();
params.ExternalBankAccount = new StripeAccountBankAccountOptions
{
    TokenId = _token.Id
}

var accountService = new StripeAccountService();
StripeAccount response = accountService.Update("acct_XXX", params);


问:
Access-VBA check if a cell in an opened excel workbook is empty before copying the row
this is my first time asking a question here.

I have run into an issue at work where I need to copy certain rows from one workbook to another. The copying part I believe I may have solved but my issue is with something extremely simple.

To determine which rows to copy I have to look at 4 dates within the first workbook, the one check with them I am having trouble with is checking if the cell is empty of not. As every time I run my code a mismatch error 13 occurs at the check.

```<code>    Dim XX As Excel.Application    ----secondary workbook
    Dim ws1 As Object
    Dim ws As Object

    Set XX = New Excel.Application
    XX.DisplayAlerts = False

    Set ws1 = XX.Workbooks.Add
    ws1.Activate
    Set ws = ws1.ActiveSheet

    Set xl = New Excel.Application   ----primary workbook
    xl.DisplayAlerts = False

    Set wb = xl.Workbooks.Open(FilePath)

For i = 2 To wb.Sheets("SHEET1").Range("Q65536").End(xlUp).Row  --- i have the code looping through all rows of the primary workbook

        Date1 = wb.Sheets("SHEET1").Cells(i, 12).Text
        Date2= wb.Sheets("SHEET1").Cells(i, 14).Text
        Date3= wb.Sheets("SHEET1").Cells(i, 13)
        Date4 = wb.Sheets("SHEET1").Cells(i, 15)    -----  everything up to here has no errors

        If ((CDate(Date1) < Date) & (IsEmpty(Date3))) Then ---- error is always here, at Date3

            wb.Rows(i).Copy ws.Rows(ws.Cells(ws.Rows.Count, 2).End(xlUp).Row + 1)

        end if
</code>```

wb is the primary workbook I am taking data from (hopefully) and ws is the workbook I am copying into.

I know the error is specifically at the empty check in the if statement because I have taken it out and left only the less than check and the code as progressed as intended. I just cannot figure out how to fix it.

I have declared the date variables for everything from string, integer, date, and variant. And have tried importing the cell values as a range and cells, with .text or .value or nothing. Then within the if statement I have tried IsEmpty, Isnull, = "", = 0, = null, added in CDate. I have literally tried everything thing in every possible combination I can think of.

答:
You could try:

```<code> Date3 = trim(wb.Sheets("SHEET1").Cells(i, 13))
 ....IsNull(Date3)
</code>```

The idea here is to trim whitespace first then check for null values.

Hope this helps :)

Body:
this is my first time asking a question here.

I have run into an issue at work where I need to copy certain rows from one workbook to another. The copying part I believe I may have solved but my issue is with something extremely simple.

To determine which rows to copy I have to look at 4 dates within the first workbook, the one check with them I am having trouble with is checking if the cell is empty of not. As every time I run my code a mismatch error 13 occurs at the check.

    Dim XX As Excel.Application    ----secondary workbook
    Dim ws1 As Object
    Dim ws As Object

    Set XX = New Excel.Application
    XX.DisplayAlerts = False

    Set ws1 = XX.Workbooks.Add
    ws1.Activate
    Set ws = ws1.ActiveSheet

    Set xl = New Excel.Application   ----primary workbook
    xl.DisplayAlerts = False

    Set wb = xl.Workbooks.Open(FilePath)

For i = 2 To wb.Sheets("SHEET1").Range("Q65536").End(xlUp).Row  --- i have the code looping through all rows of the primary workbook

        Date1 = wb.Sheets("SHEET1").Cells(i, 12).Text
        Date2= wb.Sheets("SHEET1").Cells(i, 14).Text
        Date3= wb.Sheets("SHEET1").Cells(i, 13)
        Date4 = wb.Sheets("SHEET1").Cells(i, 15)    -----  everything up to here has no errors

        If ((CDate(Date1) < Date) & (IsEmpty(Date3))) Then ---- error is always here, at Date3

            wb.Rows(i).Copy ws.Rows(ws.Cells(ws.Rows.Count, 2).End(xlUp).Row + 1)

        end if

wb is the primary workbook I am taking data from (hopefully) and ws is the workbook I am copying into.

I know the error is specifically at the empty check in the if statement because I have taken it out and left only the less than check and the code as progressed as intended. I just cannot figure out how to fix it.

I have declared the date variables for everything from string, integer, date, and variant. And have tried importing the cell values as a range and cells, with .text or .value or nothing. Then within the if statement I have tried IsEmpty, Isnull, = "", = 0, = null, added in CDate. I have literally tried everything thing in every possible combination I can think of.

Body:
You could try:

 Date3 = trim(wb.Sheets("SHEET1").Cells(i, 13))
 ....IsNull(Date3)

The idea here is to trim whitespace first then check for null values.

Hope this helps :)


问:
Selenium-IDE href value without clicking
I am quite new to the Selenium. I tried to search for similar questions/issues, but did not find.
I need to create Test Case in Selenium IDE. Test case goes to a web page https://demo.centreon.com. It logs nicely in. But then I want the Selenium to check that the Down hosts count is for example 0.

The code when checking the elements is:

How should I configure it to Selenium IDE to show me error when the count is something else than 0?

答:
In selenium you're going to want to utilize an assert. For your example it might be best select the URL and to assert the final URL e.g. main.php?p=20202&o=down&search=0 or whatever your case might be. More on that here: http://www.seleniumhq.org/docs/02_selenium_ide.jsp#assertion-or-verification

The downside is that using Selenium IDE can be limiting and eventually you're going to want to use a language binding e.g. python, java, ruby, etc. try using Selenium IDE to export the test in a language and experiment.


问:
Locking a MySQL database so only one person at once can run a query?
I am having a few issues when people are trying to access a MySQL database and they are trying to update tables with the same information.

I have a webpage written using PHP. In this webpage is a query to check if certain data has been entered into the database. If the data hasn't, then i proceed to insert it. The trouble is that if two people try at the same time, the check might say the data has not been entered yet but when the insert takes place it has been by the other person.

What is the best way to handle this scenario? Can i lock the database to only process my queries first then anothers?

答:
You could check if data has been changed before you edit something. In that case if someone has edited data while other person is doing his edit, he will be informed about it.

Kind of like stackoverflow handles commenting.

OwnerDisplayName: Gary Willoughby

LastEditorDisplayName: Jason S

OwnerDisplayName: Maiku Mori


问:
How to have event only when parent is clicked but not when children (two levels down)
I'm doing a side menu, that hides and reveals a submenu when the parent li element is clicked, and I'm almost done. The problem is that if the li child (two levels down) is clicked it hides the submenu as well.

The parent should be the only one able to trigger the event.

Here you have a simplified version of the Html, CSS and JavaScript (jQuery):

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}</code>```

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

```

Do you know how to fix this behavior?

答:
Easiest solution is move your closing
 tag where it should be, after it's  element:

$( document ).ready( function () {
  $( ".has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}</code>```

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

```

Body:
I'm doing a side menu, that hides and reveals a submenu when the parent li element is clicked, and I'm almost done. The problem is that if the li child (two levels down) is clicked it hides the submenu as well.

The parent should be the only one able to trigger the event.

Here you have a simplified version of the Html, CSS and JavaScript (jQuery):

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});

.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

Do you know how to fix this behavior?

Body:
Easiest solution is move your closing </li> tag where it should be, after it's <a> element:

$( document ).ready( function () {
  $( ".has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});

.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
    <li class="has-submenu">
      <a href="#">Overview </a>
    </li>
      <ul id="submenu" class="nav hide">
        <li class="active">
          <a href="#">Overview </a>
        </li>
        <li>
          <a href="#">Account Settings </a>
        </li>
        <li>
          <a href="#">Tasks </a>
        </li>
        <li>
          <a href="#">
            Help </a>
        </li>
      </ul>
    <li>
      <a href="#">Account Settings </a>
    </li>
    <li>
      <a href="#">Tasks </a>
    </li>
    <li>
      <a href="#">Help </a>
    </li>
  </ul>


问:
Spring MVC Spring Security and Error Handling
I'm using ResponseEntityExceptionHandler for global handling the error and almost working normal, except I want to handle wrong request with spring. By any logic overriding handleNoSuchRequestHandlingMethod should handle this, but insted of handling always get

HTTP Status 404 -

type Status report

message

description The requested resource is not
  available.

Apache
  Tomcat/7.0.37

I just got this when enable debuging in console:

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI

just to clarify by handling I mean I'm returning JSON.

any idea how to handle this?

答:
throwExceptionIfNoHandlerFound take into account only if no handlers for request found.

In case of default-servlet-handler was configured, DefaultServletHttpRequestHandler will handle request. So, if this solution doesn't work, remove it and have a look (debug) this place of DispatcherServlet.


问:
Get EJB object inside rar deployed inside jboss
I have an activemq broker deployed within my jboss server.
activemq is deployed as a rar file placed in jboss standalone/deployment repository.
An other project is also deployed within my jboss as an ear file.

This last is exposing some ejb objects in my jboss.
I tried to get an ejb from a jar file that I put into my activemq rar file. A class placed within the jar is called when I connect a client to the broker.

This is how I tried to get ejb within jar file:

```<code>  Context ctx;
  Properties jndiProps = new Properties();
  jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
  jndiProps.put("jboss.naming.client.ejb.context", true);
  ctx = new InitialContext(jndiProps);
  Ctx.lookup("ejb:Hemis/HemisCoreClient//"+ "HardwareDataManagement" + "!" + "com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement");
</code>```

Log from jboss when ejb is exposed:

11:50:17,538 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-4) JNDI bindings for session bean named HardwareDataManagement in deployment unit subdeployment "HemisCoreClient.jar" of deployment "Hemis.ear" are as follows:

java:global/Hemis/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:app/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:module/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:jboss/exported/Hemis/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:global/Hemis/HemisCoreClient/HardwareDataManagement
  java:app/HemisCoreClient/HardwareDataManagement
  java:module/HardwareDataManagement*

The log error when I try to connect client to the broker:

17:26:15,555 ERROR [stderr] (qtp1869699331-251) javax.naming.NameNotFoundException; remaining name 'java:Hemis/HemisCoreClient//HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement'
17:26:15,556 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.jndi.local.localContextRoot.lookup(localContextRoot.java:490)
17:26:15,557 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.jndi.local.localContextRoot.lookup(localContextRoot.java:536)
17:26:15,557 ERROR [stderr] (qtp1869699331-251) at javax.naming.InitialContext.lookup(InitialContext.java:411)
17:26:15,558 ERROR [stderr] (qtp1869699331-251) at authentification.TokenAuthentificationBroker.addConnection(TokenAuthentificationBroker.java:46)
17:26:15,558 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.MutableBrokerFilter.addConnection(MutableBrokerFilter.java:97)
17:26:15,558 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.TransportConnection.processAddConnection(TransportConnection.java:733)
17:26:15,559 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.jmx.ManagedTransportConnection.processAddConnection(ManagedTransportConnection.java:79)
17:26:15,559 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.command.ConnectionInfo.visit(ConnectionInfo.java:139)
17:26:15,560 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.TransportConnection.service(TransportConnection.java:292)
17:26:15,561 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.TransportConnection$1.onCommand(TransportConnection.java:149)
17:26:15,562 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.TransportSupport.doConsume(TransportSupport.java:83)
17:26:15,562 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.ws.MQTTSocket.sendToActiveMQ(MQTTSocket.java:112)
17:26:15,563 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.mqtt.MQTTProtocolConverter.sendToActiveMQ(MQTTProtocolConverter.java:133)
17:26:15,564 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.mqtt.MQTTProtocolConverter.onMQTTConnect(MQTTProtocolConverter.java:235)
17:26:15,564 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.mqtt.MQTTProtocolConverter.onMQTTCommand(MQTTProtocolConverter.java:157)
17:26:15,566 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.ws.MQTTSocket.onMessage(MQTTSocket.java:59)
17:26:15,566 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.websocket.WebSocketConnectionRFC6455$WSFrameHandler.onFrame(WebSocketConnectionRFC6455.java:860)
17:26:15,567 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.websocket.WebSocketParserRFC6455.parseNext(WebSocketParserRFC6455.java:349)
17:26:15,568 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.websocket.WebSocketConnectionRFC6455.handle(WebSocketConnectionRFC6455.java:225)
17:26:15,568 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
17:26:15,569 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
17:26:15,571 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
17:26:15,571 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
17:26:15,572 ERROR [stderr] (qtp1869699331-251) at java.lang.Thread.run(Thread.java:745)

When I try this code from a class inside the ear which is exposing EJB, it work and I can get EJB object. Do I think that the problem is that I try to get ejb from jar included in rar deployed in my jboss.
Could someone help me with this?

答:
It should not be necessary to perform a remote lookup like that.

The following should work:

```<code> Context ctx = new InitialContext();
 ... = ctx.lookup("java:global/Hemis/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement");
</code>```

Objects in the java:global/... namespace are accessible from within any module deployed on the server instance.

Body:
I have an activemq broker deployed within my jboss server.
activemq is deployed as a rar file placed in jboss standalone/deployment repository.
An other project is also deployed within my jboss as an ear file.

This last is exposing some ejb objects in my jboss.
I tried to get an ejb from a jar file that I put into my activemq rar file. A class placed within the jar is called when I connect a client to the broker.

This is how I tried to get ejb within jar file:

  Context ctx;
  Properties jndiProps = new Properties();
  jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
  jndiProps.put("jboss.naming.client.ejb.context", true);
  ctx = new InitialContext(jndiProps);
  Ctx.lookup("ejb:Hemis/HemisCoreClient//"+ "HardwareDataManagement" + "!" + "com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement");

Log from jboss when ejb is exposed:

11:50:17,538 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-4) JNDI bindings for session bean named HardwareDataManagement in deployment unit subdeployment "HemisCoreClient.jar" of deployment "Hemis.ear" are as follows:

java:global/Hemis/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:app/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:module/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:jboss/exported/Hemis/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement
  java:global/Hemis/HemisCoreClient/HardwareDataManagement
  java:app/HemisCoreClient/HardwareDataManagement
  java:module/HardwareDataManagement*

The log error when I try to connect client to the broker:

17:26:15,555 ERROR [stderr] (qtp1869699331-251) javax.naming.NameNotFoundException; remaining name 'java:Hemis/HemisCoreClient//HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement'
17:26:15,556 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.jndi.local.localContextRoot.lookup(localContextRoot.java:490)
17:26:15,557 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.jndi.local.localContextRoot.lookup(localContextRoot.java:536)
17:26:15,557 ERROR [stderr] (qtp1869699331-251) at javax.naming.InitialContext.lookup(InitialContext.java:411)
17:26:15,558 ERROR [stderr] (qtp1869699331-251) at authentification.TokenAuthentificationBroker.addConnection(TokenAuthentificationBroker.java:46)
17:26:15,558 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.MutableBrokerFilter.addConnection(MutableBrokerFilter.java:97)
17:26:15,558 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.TransportConnection.processAddConnection(TransportConnection.java:733)
17:26:15,559 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.jmx.ManagedTransportConnection.processAddConnection(ManagedTransportConnection.java:79)
17:26:15,559 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.command.ConnectionInfo.visit(ConnectionInfo.java:139)
17:26:15,560 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.TransportConnection.service(TransportConnection.java:292)
17:26:15,561 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.broker.TransportConnection$1.onCommand(TransportConnection.java:149)
17:26:15,562 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.TransportSupport.doConsume(TransportSupport.java:83)
17:26:15,562 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.ws.MQTTSocket.sendToActiveMQ(MQTTSocket.java:112)
17:26:15,563 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.mqtt.MQTTProtocolConverter.sendToActiveMQ(MQTTProtocolConverter.java:133)
17:26:15,564 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.mqtt.MQTTProtocolConverter.onMQTTConnect(MQTTProtocolConverter.java:235)
17:26:15,564 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.mqtt.MQTTProtocolConverter.onMQTTCommand(MQTTProtocolConverter.java:157)
17:26:15,566 ERROR [stderr] (qtp1869699331-251) at org.apache.activemq.transport.ws.MQTTSocket.onMessage(MQTTSocket.java:59)
17:26:15,566 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.websocket.WebSocketConnectionRFC6455$WSFrameHandler.onFrame(WebSocketConnectionRFC6455.java:860)
17:26:15,567 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.websocket.WebSocketParserRFC6455.parseNext(WebSocketParserRFC6455.java:349)
17:26:15,568 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.websocket.WebSocketConnectionRFC6455.handle(WebSocketConnectionRFC6455.java:225)
17:26:15,568 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
17:26:15,569 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
17:26:15,571 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
17:26:15,571 ERROR [stderr] (qtp1869699331-251) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
17:26:15,572 ERROR [stderr] (qtp1869699331-251) at java.lang.Thread.run(Thread.java:745)

When I try this code from a class inside the ear which is exposing EJB, it work and I can get EJB object. Do I think that the problem is that I try to get ejb from jar included in rar deployed in my jboss.
Could someone help me with this?

Body:
It should not be necessary to perform a remote lookup like that.

The following should work:

 Context ctx = new InitialContext();
 ... = ctx.lookup("java:global/Hemis/HemisCoreClient/HardwareDataManagement!com.ubiant.hemis.client.ejb.interf.I_HardwareDataManagement");

Objects in the java:global/... namespace are accessible from within any module deployed on the server instance.


问:
Unable to import module from package
I recently installed Elm's List.Extra package.

I am attempting to import the List.Extra module from the package with the following:

```<code>module Tests.TestAPI exposing (..)

import List.Extra as ListHelper exposing (..)
</code>```

However, I receive the following error:

I cannot find module 'List.Extra'.

Module 'Tests.TestAPI' is trying to import it.

Potential problems could be:   * Misspelled the module name   * Need
  to add a source directory or new dependency to elm-package.json

The List.Extra module looks like the following:

```<code>module List.Extra
    exposing
        ( last,
          ...
        )
</code>```

Any suggestions on what I need to do to successfully import this module?

答: I resolved it by restarting my IDE (Visual Studio Code)</p>

Title: Unable to import module from package

Body:
I recently installed Elm's List.Extra package.

I am attempting to import the List.Extra module from the package with the following:

module Tests.TestAPI exposing (..)

import List.Extra as ListHelper exposing (..)

However, I receive the following error:

I cannot find module 'List.Extra'.

Module 'Tests.TestAPI' is trying to import it.

Potential problems could be:   * Misspelled the module name   * Need
  to add a source directory or new dependency to elm-package.json

The List.Extra module looks like the following:

module List.Extra
    exposing
        ( last,
          ...
        )

Any suggestions on what I need to do to successfully import this module?


问:
How to add audio in desktop capture in chrome extension
I have added audio to chrome extension on screen cast of desktop. But audio is not in good quality. As, I record screen of the tab. I got good quality video and audio. How can I get good quality audio in desktop recording. Here is what I am using </p>

```<code> chrome.desktopCapture.chooseDesktopMedia(['screen', 'window', 'audio'], function (streamId) {
        if (streamId) {
              var obj = {
               audio: {
                mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: streamId
                    }
               },
               video: {
                optional: [],
                   mandatory: {
                      chromeMediaSource: 'desktop',
                      chromeMediaSourceId: streamId,
                      maxWidth: 2560,
                      maxHeight: 1440
                   }
               }
            };

            countdownRun(function () {
                window.navigator.mediaDevices.getUserMedia(obj).then(function(stream) {
    $streamVideo = stream;
    $timeStart = Date.now();
    var audio = stream.getAudioTracks()[0];
    var video = stream.getVideoTracks()[0];
    alert(JSON.stringify(audio))
    alert(JSON.stringify(video))
    if (micSound) {
        window.navigator.webkitGetUserMedia({audio: true}, function (s) {
            $streamAudio = s;
            audio = s.getAudioTracks()[0];
            captureUseNacl(audio, video);
        }, function (e) {
            chrome.tabs.create({url: 'mic.html'});
        })
    } else {
        captureUseNacl(audio, video);

        (function () {
            var v = document.createElement('video');
            document.body.appendChild(v);
            v.setAttribute('autoplay', '');
            v.addEventListener('canplay', function () {
                console.log('play video');
            }, false);
            v.src = window.URL.createObjectURL(stream);
            $streamElement = v;
        })()
    }
}).catch(function(err) {
alert(err)
    alert(JSON.stringify(err));
});;
            })
        }
    });
</code>```

答:
You can do this by removing document.createElement and createObject part. It nothing but adding nose to the recording. If you check on the readystate of audio it is end. It should be live. Again, add maxFrameRate to video section to synchronize audio and video. Here is your code

```<code>chrome.desktopCapture.chooseDesktopMedia(['screen', 'window', 'audio'], function (streamId) {
        if (streamId) {

              var obj = {
               audio: {
                mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: streamId
                    }
               },
               video: {
                optional: [],
                   mandatory: {
                      chromeMediaSource: 'desktop',
                      chromeMediaSourceId: streamId,
                      maxWidth: 2560,
                      maxHeight: 1440,
                      maxFrameRate:30
                   }
               }
            };

            countdownRun(function () {
                navigator.mediaDevices.getUserMedia(obj).then(function(stream) {
    $streamVideo = stream;
    $timeStart = Date.now();
    var audio = stream.getAudioTracks()[0];
    var video = stream.getVideoTracks()[0];
    console.log(stream);
    if (micSound) {
        window.navigator.webkitGetUserMedia({audio: true}, function (s) {
            $streamAudio = s;
            audio = s.getAudioTracks()[0];
            captureUseNacl(audio, video);
        }, function (e) {
            chrome.tabs.create({url: 'mic.html'});
        })
    } else {
        captureUseNacl(audio, video);
    }
}).catch(function(err) {
 console.log(err)
});
            })
        }
    });
</code>```

Body:
I have added audio to chrome extension on screen cast of desktop. But audio is not in good quality. As, I record screen of the tab. I got good quality video and audio. How can I get good quality audio in desktop recording. Here is what I am using

 chrome.desktopCapture.chooseDesktopMedia(['screen', 'window', 'audio'], function (streamId) {
        if (streamId) {
              var obj = {
               audio: {
                mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: streamId
                    }
               },
               video: {
                optional: [],
                   mandatory: {
                      chromeMediaSource: 'desktop',
                      chromeMediaSourceId: streamId,
                      maxWidth: 2560,
                      maxHeight: 1440
                   }
               }
            };

            countdownRun(function () {
                window.navigator.mediaDevices.getUserMedia(obj).then(function(stream) {
    $streamVideo = stream;
    $timeStart = Date.now();
    var audio = stream.getAudioTracks()[0];
    var video = stream.getVideoTracks()[0];
    alert(JSON.stringify(audio))
    alert(JSON.stringify(video))
    if (micSound) {
        window.navigator.webkitGetUserMedia({audio: true}, function (s) {
            $streamAudio = s;
            audio = s.getAudioTracks()[0];
            captureUseNacl(audio, video);
        }, function (e) {
            chrome.tabs.create({url: 'mic.html'});
        })
    } else {
        captureUseNacl(audio, video);

        (function () {
            var v = document.createElement('video');
            document.body.appendChild(v);
            v.setAttribute('autoplay', '');
            v.addEventListener('canplay', function () {
                console.log('play video');
            }, false);
            v.src = window.URL.createObjectURL(stream);
            $streamElement = v;
        })()
    }
}).catch(function(err) {
alert(err)
    alert(JSON.stringify(err));
});;
            })
        }
    });

Body:
You can do this by removing document.createElement and createObject part. It nothing but adding nose to the recording. If you check on the readystate of audio it is end. It should be live. Again, add maxFrameRate to video section to synchronize audio and video. Here is your code

chrome.desktopCapture.chooseDesktopMedia(['screen', 'window', 'audio'], function (streamId) {
        if (streamId) {

              var obj = {
               audio: {
                mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: streamId
                    }
               },
               video: {
                optional: [],
                   mandatory: {
                      chromeMediaSource: 'desktop',
                      chromeMediaSourceId: streamId,
                      maxWidth: 2560,
                      maxHeight: 1440,
                      maxFrameRate:30
                   }
               }
            };

            countdownRun(function () {
                navigator.mediaDevices.getUserMedia(obj).then(function(stream) {
    $streamVideo = stream;
    $timeStart = Date.now();
    var audio = stream.getAudioTracks()[0];
    var video = stream.getVideoTracks()[0];
    console.log(stream);
    if (micSound) {
        window.navigator.webkitGetUserMedia({audio: true}, function (s) {
            $streamAudio = s;
            audio = s.getAudioTracks()[0];
            captureUseNacl(audio, video);
        }, function (e) {
            chrome.tabs.create({url: 'mic.html'});
        })
    } else {
        captureUseNacl(audio, video);
    }
}).catch(function(err) {
 console.log(err)
});
            })
        }
    });


问:
Xamarin WebAPI call from PCL
I am trying to develop a Xamarin.Forms or Xamarin.iOS/Xamarin.Droid native app which can make a Web API call to my server. I get the error saying HttpRequestException thrown. Once I searched for a solution, it says that it is because it can't reach the socket, but I am unable to install it to a PCL project. So I check the solution for this and they said to use a proxy to reach the service.

Here is my problem. I have tried making a Proxy in the PCL to connect to a service in the .Droid or .iOS projects so they can use the sockets, (although I don't think the service should be in the app project itself because duplicate code). But the proxy class is not able to reference the the service because it is not in the project.

This is my RestService class.

```<code>public class RestService : IRestService
{
    private const string BASE_URI = "http://xxx.xxx.xxx.xxx/";
    private HttpClient Client;
    private string Controller;

    /**
     * Controller is the middle route, for example user or account etc.
     */
    public RestService(string controller)
    {
        Controller = controller;
        Client = new HttpClient();
    }

    /**
     * uri in this case is "userId?id=1".
     */
    public async Task<string> GET(string uri)
    {
        try
        {
            Client.BaseAddress = new Uri(BASE_URI);
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var fullUri = String.Format("api/{0}/{1}", Controller, uri);
            var response = Client.GetAsync(fullUri);
            string content = await response.Result.Content.ReadAsStringAsync();
            return content;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
</code>```

I cannot find any good tutorials online on how to get this to work and any help in this regards would be much appreciated.

答:
You are mixing async/await and blocking calls .Result

```<code>public async Task<string> GET(string uri) {
    //...other code removed for brevity

    var response = Client.GetAsync(fullUri).Result;

    //...other code removed for brevity
}
</code>```

which is causing a deadlock resulting in you not being able to get to socket.

When using async/await you need to go async all the way and avoid blocking calls like .Result and .Wait().

```<code>public async Task<string> GET(string uri) {
    try {
        Client.BaseAddress = new Uri(BASE_URI);
        Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var fullUri = String.Format("api/{0}/{1}", Controller, uri);
        var response = await Client.GetAsync(fullUri);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    } catch (Exception e) {
        return null;
    }
}
</code>```

Title: Xamarin WebAPI call from PCL

Body:
I am trying to develop a Xamarin.Forms or Xamarin.iOS/Xamarin.Droid native app which can make a Web API call to my server. I get the error saying HttpRequestException thrown. Once I searched for a solution, it says that it is because it can't reach the socket, but I am unable to install it to a PCL project. So I check the solution for this and they said to use a proxy to reach the service.

Here is my problem. I have tried making a Proxy in the PCL to connect to a service in the .Droid or .iOS projects so they can use the sockets, (although I don't think the service should be in the app project itself because duplicate code). But the proxy class is not able to reference the the service because it is not in the project.

This is my RestService class.

public class RestService : IRestService
{
    private const string BASE_URI = "http://xxx.xxx.xxx.xxx/";
    private HttpClient Client;
    private string Controller;

    /**
     * Controller is the middle route, for example user or account etc.
     */
    public RestService(string controller)
    {
        Controller = controller;
        Client = new HttpClient();
    }

    /**
     * uri in this case is "userId?id=1".
     */
    public async Task<string> GET(string uri)
    {
        try
        {
            Client.BaseAddress = new Uri(BASE_URI);
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var fullUri = String.Format("api/{0}/{1}", Controller, uri);
            var response = Client.GetAsync(fullUri);
            string content = await response.Result.Content.ReadAsStringAsync();
            return content;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}

I cannot find any good tutorials online on how to get this to work and any help in this regards would be much appreciated.

Body:
You are mixing async/await and blocking calls .Result

public async Task<string> GET(string uri) {
    //...other code removed for brevity

    var response = Client.GetAsync(fullUri).Result;

    //...other code removed for brevity
}

which is causing a deadlock resulting in you not being able to get to socket.

When using async/await you need to go async all the way and avoid blocking calls like .Result and .Wait().

public async Task<string> GET(string uri) {
    try {
        Client.BaseAddress = new Uri(BASE_URI);
        Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var fullUri = String.Format("api/{0}/{1}", Controller, uri);
        var response = await Client.GetAsync(fullUri);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    } catch (Exception e) {
        return null;
    }
}


问:
Using a created extension method
Here's the method I created:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}
</code>```

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

```<code>@Html.MyMenu //doesn't appears to be in the available method selection.
</code>```

What's the reason why I can't call this method like that? Thanks for the help.

答:
You shouldn't need the @, Html should do just fine (though @Html should work as well). You'd need to actually invoke the method, though:

```<code>Html.MyMenu()
</code>```

And if you haven't got a program like ReSharper that'll suggest this for you, you need to include a reference to that namespace

```<code><%@ Import Namespace="MvcApplication1.HelperMethods" %>
</code>```

OwnerDisplayName: delete

Title: Using a created extension method

Body:
Here's the method I created:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

@Html.MyMenu //doesn't appears to be in the available method selection.

What's the reason why I can't call this method like that? Thanks for the help.

Body:
You shouldn't need the @, Html should do just fine (though @Html should work as well). You'd need to actually invoke the method, though:

Html.MyMenu()

And if you haven't got a program like ReSharper that'll suggest this for you, you need to include a reference to that namespace

<%@ Import Namespace="MvcApplication1.HelperMethods" %>


问:
JBoss 6 EAP - override HTTP response status code in a SOAP service that sends empty response back from 202 to 200
We have a SOAP web service that we are migrating from JBoss EAP 5.1 to 6.4.7 and one of the webservices returns absolutely nothing but 200 (in JBoss 5). When we migrated to 6 it still works and returns nothing but returns a 202 instead and that is going to break clients. We have no control over clients. I tried a SOAPHandler at the close method but it does nothing as it is not even called as my guess is that since there is no SOAP message going back there is nothing that triggers the handler.

I also tried to access the context directly in the web method and modif  but it did nothing.

MessageContext ctx = wsContext.getMessageContext();
HttpServletResponse response = (HttpServletResponse) ctx.get(MessageContext.SERVLET_RESPONSE);
response.setStatus(HttpServletResponse.SC_OK);

I couldn't find anything in the manual.

Any direction is very much appreciated.

Here is how the port and its implementation look like:

Here is how the port and its implementation head look like:

```<code>@WebService(name = "ForecastServicePortType", targetNamespace = "http://www.company.com/forecastservice/wsdl")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface ForecastServicePortType {

    /**
     *
     * @param parameters
     * @throws RemoteException
     */
    @WebMethod(action = "http://www.company.com/forecast/sendForecast")
    public void  sendForecast(
        @WebParam(name = "SendForecast", targetNamespace = "http://www.company.com/forecastservice", partName = "parameters")
        SendForecastType parameters) throws RemoteException;

}

@WebService(name = "ForecastServicePortTypeImpl", serviceName = "ForecastServicePortType", endpointInterface = "com.company.forecastservice.wsdl.ForecastServicePortType", wsdlLocation = "/WEB-INF/wsdl/ForecastServicePortType.wsdl")
@HandlerChain(file = "/META-INF/handlers.xml")
public class ForecastServicePortTypeImpl implements ForecastServicePortType {
...

}
</code>```

答:
In case anybody will find this useful. Here is the solution;

Apache CXF by default uses async requests and even if the annotation @OneWay is missing it still behaves as it if was there.

So in order to disable that an interceptor needs to be created like below:

```<code>import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;

import java.util.Arrays;

public class DisableOneWayInterceptor extends AbstractSoapInterceptor {
    private static final Log LOG = LogFactory.getLog(DisableOneWayInterceptor.class);

    public DisableOneWayInterceptor(){
        super(Phase.PRE_LOGICAL);
        addBefore(Arrays.asList(org.apache.cxf.interceptor.OneWayProcessorInterceptor.class.getName()));
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        if(LOG.isDebugEnabled())
        LOG.debug("OneWay behavior disabled");

        soapMessage.getExchange().setOneWay(false);
    }
}
</code>```

And called in WebService class (annotated with @WebService) as below:

```<code>@org.apache.cxf.interceptor.InInterceptors (interceptors = {"com.mycompany.interceptors.DisableOneWayInterceptor" })
</code>```

Body:
We have a SOAP web service that we are migrating from JBoss EAP 5.1 to 6.4.7 and one of the webservices returns absolutely nothing but 200 (in JBoss 5). When we migrated to 6 it still works and returns nothing but returns a 202 instead and that is going to break clients. We have no control over clients. I tried a SOAPHandler at the close method but it does nothing as it is not even called as my guess is that since there is no SOAP message going back there is nothing that triggers the handler.

I also tried to access the context directly in the web method and modif  but it did nothing.

MessageContext ctx = wsContext.getMessageContext();
HttpServletResponse response = (HttpServletResponse) ctx.get(MessageContext.SERVLET_RESPONSE);
response.setStatus(HttpServletResponse.SC_OK);

I couldn't find anything in the manual.

Any direction is very much appreciated.

Here is how the port and its implementation look like:

Here is how the port and its implementation head look like:

@WebService(name = "ForecastServicePortType", targetNamespace = "http://www.company.com/forecastservice/wsdl")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface ForecastServicePortType {

    /**
     *
     * @param parameters
     * @throws RemoteException
     */
    @WebMethod(action = "http://www.company.com/forecast/sendForecast")
    public void  sendForecast(
        @WebParam(name = "SendForecast", targetNamespace = "http://www.company.com/forecastservice", partName = "parameters")
        SendForecastType parameters) throws RemoteException;

}

@WebService(name = "ForecastServicePortTypeImpl", serviceName = "ForecastServicePortType", endpointInterface = "com.company.forecastservice.wsdl.ForecastServicePortType", wsdlLocation = "/WEB-INF/wsdl/ForecastServicePortType.wsdl")
@HandlerChain(file = "/META-INF/handlers.xml")
public class ForecastServicePortTypeImpl implements ForecastServicePortType {
...

}

Body:
In case anybody will find this useful. Here is the solution;

Apache CXF by default uses async requests and even if the annotation @OneWay is missing it still behaves as it if was there.

So in order to disable that an interceptor needs to be created like below:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;

import java.util.Arrays;

public class DisableOneWayInterceptor extends AbstractSoapInterceptor {
    private static final Log LOG = LogFactory.getLog(DisableOneWayInterceptor.class);

    public DisableOneWayInterceptor(){
        super(Phase.PRE_LOGICAL);
        addBefore(Arrays.asList(org.apache.cxf.interceptor.OneWayProcessorInterceptor.class.getName()));
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        if(LOG.isDebugEnabled())
        LOG.debug("OneWay behavior disabled");

        soapMessage.getExchange().setOneWay(false);
    }
}

And called in WebService class (annotated with @WebService) as below:

@org.apache.cxf.interceptor.InInterceptors (interceptors = {"com.mycompany.interceptors.DisableOneWayInterceptor" })


问:
Location of docker images downloaded by Docker (1.9.1) on Mac OS X
Where are the docker images located once they are downloaded from docker hub in Mac OSX. For example if I run a command like:

```<code>docker run hello-world
</code>```

the image is downloaded and the container is run but where is that image located on my system?

Note: Where are Docker images stored on the host machine? This question has answers related to linux machine, mainly. The answers for Mac OS X are considering that boot2docker is being used alongside docker installation, which is not the case for me.

答:
The Disk image location can also be seen (as mentioned in the docs) by selecting Preferences->Advanced menu from the Docker toolbar icon (works in Docker-CE v17):

Preferences->Advanced">

Update: As mentioned by @udondan Docker now has a separate 'Disk' tab in Preferences where it shows the disk image location:

Preferences->Disk">

Body:
Where are the docker images located once they are downloaded from docker hub in Mac OSX. For example if I run a command like:

docker run hello-world

the image is downloaded and the container is run but where is that image located on my system?

Note: Where are Docker images stored on the host machine? This question has answers related to linux machine, mainly. The answers for Mac OS X are considering that boot2docker is being used alongside docker installation, which is not the case for me.

Body:
The Disk image location can also be seen (as mentioned in the docs) by selecting Preferences->Advanced menu from the Docker toolbar icon (works in Docker-CE v17):

Update: As mentioned by @udondan Docker now has a separate 'Disk' tab in Preferences where it shows the disk image location:

ContentLicense: CC BY-SA 4.0


Title: Python: drop duplicated index in pandas dataframe

Body:
I have the date as below and the Date as Index. I want to remove the duplicated Date

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2016-05-13   AAD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2016-05-16   AAD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000
2016-05-18   AAD  5.200000  5.250000  5.200000  5.250000  5.250000    3000

The output I needed

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2016-05-13   AAD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2016-05-16   AAD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000
2016-05-18   AAD  5.200000  5.250000  5.200000  5.250000  5.250000    3000

I try by using df.drop_duplicates() and the output delete extra lines after the duplicated date.

          Stock      Open      High       Low     Close Adj Close  Volume
Date
2016-05-13   AAD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2016-05-16   AAD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2016-05-17   AAD  5.210000  5.260000  5.210000  5.260000  5.260000    2000

Body:
Let's use the information Jezrael provided.

Input Dataframe:

print(df)
           Stock  Open  High   Low  Close  Adj Close  Volume
2016-05-13   AAD  5.23  5.26  5.20   5.26       5.26    5000
2016-05-16   AAD  5.22  5.26  5.22   5.26       5.26    6000
2016-05-17   AAD  5.21  5.26  5.21   5.26       5.26    2000
2016-05-17   AAD  5.21  5.26  5.21   5.26       5.26    2000
2016-05-18   AAD  5.20  5.25  5.20   5.25       5.25    3000

df1 = df[~df.index.duplicated(keep='last')]
print(df1)

Output:

           Stock  Open  High   Low  Close  Adj Close  Volume
2016-05-13   AAD  5.23  5.26  5.20   5.26       5.26    5000
2016-05-16   AAD  5.22  5.26  5.22   5.26       5.26    6000
2016-05-17   AAD  5.21  5.26  5.21   5.26       5.26    2000
2016-05-18   AAD  5.20  5.25  5.20   5.25       5.25    3000


问:
CSS two divs next to each other (w/o line break)
I want to put 2
s next to each other. How can I do this?
Both should be 50% width. Can someone help correct my code?

This is the code:

```<code>    <hr class="hr--small">
    <div class="grid">

    <div class="grid__item text-left">
      <p class="site-footer__links">{{ 'layout.footer.copyright' | t }} ©
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved
      </p>
    </div>

    <div class="grid__item text-right">
      <p class="site-footer__links">
        <a href="http://www.w3schools.com/html/">Privacy Policy</a> •
        <a href="http://www.w3schools.com/html/">Terms & Conditions</a>
      </p>
    </div>
</code>```

At the moment they appear correctly left & right, but with line break. Just want them to appear on the same line.

答:
I'm not sure what grid-framework you are using, but I'm sure that text-left and text-right are helper-classes that provide a text-align property.

A solution for your problem is to make the divs float, like I demonstrated in this Jsfiddle: https://jsfiddle.net/hptv52gv/.

Body:
I want to put 2
s next to each other. How can I do this?
Both should be 50% width. Can someone help correct my code?

This is the code:

{{ 'layout.footer.copyright' | t }} ©
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved

        Privacy Policy •
        Terms & Conditions

At the moment they appear correctly left & right, but with line break. Just want them to appear on the same line.


问:
Knitr: do not comment out not evaluated code
I recently noticed a change in the use of the chunk option eval.

Take the following chunk:

```<code><<Chunk1, eval = -2>>=
x <- rnorm(1)
Sys.sleep(5)
print(x)
@
</code>```

A few compilations of my document ago this would result in the source code to be shown as it is in the created document but with the second line being ignored during evaluation. The result in the document would look like:

Now there seems to have been a change and the second line is still not evaluated, BUT it is commented out in the source code. I found the prior behavior pretty neat. Now I could as well just directly comment out the second line if I wanted to show it commented out and not evaluated.

Is there a way to get the previous behavior back?

答:
As of knitr commit https://github.com/yihui/knitr/commit/78e4d5d003129a4d7efbec7b178e9a98222d777b

there doesn't seem to be a way to prevent this short of writing your own hook or forking and modifying.  The 'offending' code is: https://github.com/yihui/knitr/blob/master/R/block.R#L160

One could put in an issue asking to add the ability to control whether or not to comment out the unevaluated code.

Body:
I recently noticed a change in the use of the chunk option eval.

Take the following chunk:

<<Chunk1, eval = -2>>=
x <- rnorm(1)
Sys.sleep(5)
print(x)
@

A few compilations of my document ago this would result in the source code to be shown as it is in the created document but with the second line being ignored during evaluation. The result in the document would look like:

Now there seems to have been a change and the second line is still not evaluated, BUT it is commented out in the source code. I found the prior behavior pretty neat. Now I could as well just directly comment out the second line if I wanted to show it commented out and not evaluated.

Is there a way to get the previous behavior back?


问:
Group rows by minimum value
The problem is that I have some tables to build and some values are under an specific threshold. For example:

```<code>    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
D   27  11  5
E   3   6   1
F   8   2   9
G   1   3   2
</code>```

What I desire is to keep the rows where the values contain at least one value is equal or greater than 10 and merge the rows where the values are less than 10 to create a row named "Other (<10)":

1 - Part of the table with rows with at least one cell containing one value greater than 10 (Row C; value 18):

```<code>    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
</code>```

2 - Part of the table where any value is greater than 10.

```<code>E   3   6   1
F   8   2   9
G   1   3   2
</code>```

The final table would have the last row with the sum of the columns from E, F, and G, including the "Other(>10)" row name. Like this:

```<code>            S1  S2  S3
A           700 367 751
B           354 103 143
C           18  7   6
D           27  11  5
Other(<10)  12  11  12
</code>```

Title: Group rows by minimum value

Body:
The problem is that I have some tables to build and some values are under an specific threshold. For example:

    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
D   27  11  5
E   3   6   1
F   8   2   9
G   1   3   2

What I desire is to keep the rows where the values contain at least one value is equal or greater than 10 and merge the rows where the values are less than 10 to create a row named "Other (<10)":

1 - Part of the table with rows with at least one cell containing one value greater than 10 (Row C; value 18):

    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6

2 - Part of the table where any value is greater than 10.

E   3   6   1
F   8   2   9
G   1   3   2

The final table would have the last row with the sum of the columns from E, F, and G, including the "Other(>10)" row name. Like this:

            S1  S2  S3
A           700 367 751
B           354 103 143
C           18  7   6
D           27  11  5
Other(<10)  12  11  12

Body:
If you are interested in R solution:

filtered.df <-   rbind( df[ apply(df, 1, function(x){any(x>=10)}), ],
               colSums( df[ apply(df, 1, function(x){all(x< 10)}), ]))

And this would be the output:

> filtered.df

#      [,1] [,2] [,3]
# [1,]  700  367  751
# [2,]  354  103  143
# [3,]   18    7    6
# [4,]   27   11    5
# [5,]   12   11   12

Data:

df <- structure(c(700, 354, 18, 27, 3, 8, 1, 367, 103, 7, 11, 6, 2, 3, 751, 143, 6, 5, 1, 9, 2), .Dim = c(7L, 3L))

Update: Including column and row names:

As OP asked, for the column-names and row-names this would be the data:

 df <- structure(c(700, 354, 18, 27, 3, 8, 1, 367, 103, 7, 11, 6, 2, 3, 751, 143, 6, 5, 1, 9, 2), .Dim = c(7L, 3L), .Dimnames = list(    c("A", "B", "C", "D", "E", "F", "G"), c("s1", "s2", "s3")))

And then using the same solution above we'll get:

> filtered.df

#    s1  s2  s3
# A 700 367 751
# B 354 103 143
# C  18   7   6
# D  27  11   5
#    12  11  12


问:
WordPress: post_type->rewrite['slug'] returns post_type, not the slug
In my application I need to create a widget in admin dashboard which will display a section of all post_types associated with the number of posts each of them has.

To accomplish the above I added the following code block in my functions.php file:

```<code>add_action('wp_dashboard_setup', 'tp_post_counts_reference');

    function tp_post_counts_reference() {
        global $wp_meta_boxes;
        wp_add_dashboard_widget('custom_help_widget', 'Posts in all post types', 'custom_dashboard_help');
    }

    function custom_dashboard_help() {
        $types = get_post_types();
        foreach( $types as $type )
        {
            if($type != 'travelog' && $type != 'package_tour' && $type != 'hotel-info') continue;
            $typeobj = get_post_type_object( $type );

            echo '<a href="/' . $typeobj->rewrite['slug'] . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts( $type )->publish . '<br />';
        }
    }
</code>```

But $typeobj->rewrite['slug'] is actually outputting the post_type rather than its corresponding slug.

For example:
I have the following custom post types

Travelog (name: Travelog, post_type: travelog, slug: travelogs)

Hotel Info (name: Hotel Info, post_type: hotel-info, slug: hotels)

The actual output for

```<code>'<a href="/' . $typeobj->rewrite['slug'] . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts( $type )->publish
</code>```

are

```<code><a href="/travelog">Travelog</a>: 6
</code>```

and

```<code><a href="/hotel-info">Hotel</a>: 11
</code>```

when I expect them to output:

```<code><a href="/travelogs">Travelog</a>: 6
</code>```

and

```<code><a href="/hotels">Hotel</a>: 11
</code>```

Please tell me what I did wrong :(

NB: My WP version is 4.7.5

答:
Rather than trying to manually build your post type URL, I would recommend that you instead leverage the built-in WordPress function get_post_type_archive_link.

That would look like this:

```<code>function custom_dashboard_help() {
    $types = get_post_types();

    // Alternate method for testing if custom type.
    $custom_types = array( 'travelog', 'package_tour', 'hotel-info' );
    foreach( $types as $type ) {
        // If not a custom post type, don't render the link
        if( ! in_array( $type, $custom_types ) ) {
            continue;
        }

        $typeobj = get_post_type_object( $type );

        // Use get_post_type_archive_link function to get URL
        echo '<a href="' . get_post_type_archive_link( $type ) . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts( $type )->publish . '<br />';
    }
}
</code>```

Body:
In my application I need to create a widget in admin dashboard which will display a section of all post_types associated with the number of posts each of them has.

To accomplish the above I added the following code block in my functions.php file:

add_action('wp_dashboard_setup', 'tp_post_counts_reference');

    function tp_post_counts_reference() {
        global $wp_meta_boxes;
        wp_add_dashboard_widget('custom_help_widget', 'Posts in all post types', 'custom_dashboard_help');
    }

    function custom_dashboard_help() {
        $types = get_post_types();
        foreach( $types as $type )
        {
            if($type != 'travelog' && $type != 'package_tour' && $type != 'hotel-info') continue;
            $typeobj = get_post_type_object( $type );

            echo 'rewrite['slug'] . '">' . $typeobj->labels->name . ': ' . wp_count_posts( $type )->publish . '
';
        }
    }

But $typeobj->rewrite['slug'] is actually outputting the post_type rather than its corresponding slug.

For example:
I have the following custom post types

Travelog (name: Travelog, post_type: travelog, slug: travelogs)

Hotel Info (name: Hotel Info, post_type: hotel-info, slug: hotels)

The actual output for

'rewrite['slug'] . '">' . $typeobj->labels->name . ': ' . wp_count_posts( $type )->publish

are

Travelog: 6

and

Hotel: 11

when I expect them to output:

Travelog: 6

and

Hotel: 11

Please tell me what I did wrong :(

NB: My WP version is 4.7.5

Body:
Rather than trying to manually build your post type URL, I would recommend that you instead leverage the built-in WordPress function get_post_type_archive_link.

That would look like this:

function custom_dashboard_help() {
    $types = get_post_types();

    // Alternate method for testing if custom type.
    $custom_types = array( 'travelog', 'package_tour', 'hotel-info' );
    foreach( $types as $type ) {
        // If not a custom post type, don't render the link
        if( ! in_array( $type, $custom_types ) ) {
            continue;
        }

        $typeobj = get_post_type_object( $type );

        // Use get_post_type_archive_link function to get URL
        echo '<a href="' . get_post_type_archive_link( $type ) . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts( $type )->publish . '<br />';
    }
}