问:
high order component throws an invalid react element error (reactjs)
So I've been reading about HOCs lately and decided to use them in my application to pass down authorisation logic to the child components.

I'm trying to render a <Route /> component through the HOC but it logs the error:

Uncaught Error: AuthRoute(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Here's the code for the HOC:

```<code>const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;
};
</code>```

And then I'm using this HOC as an alias of <Route /> component like this:

```<code><BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>
</code>```

EDIT:

But this approach works fine:

```<code>const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>
</code>```

答:
In the first case you are returning a class instance

```<code>const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;  // returning the class object here and not an instance
};
</code>```

So if your wish to use it you would need to write

```<code><BrowserRouter>
  <Route path="/account" component={AuthRoute(PrivateComponent)} />
</BrowserRouter>
</code>```

where AuthRoute(PrivateComponent) is a class object and Route creates an instance out of it internally

However in the second case, its not an HOC, but a functional component that returns a valid React Element,

```<code>const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);
</code>```

and hence

using <AuthRoute path="/account" component={PrivateComponent} /> , you called a component instance whereby props path and component are received by the functional component.

Body:
So I've been reading about HOCs lately and decided to use them in my application to pass down authorisation logic to the child components.

I'm trying to render a <Route /> component through the HOC but it logs the error:

Uncaught Error: AuthRoute(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Here's the code for the HOC:

const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;
};

And then I'm using this HOC as an alias of <Route /> component like this:

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>

EDIT:

But this approach works fine:

const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>

Body:
In the first case you are returning a class instance

const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;  // returning the class object here and not an instance
};

So if your wish to use it you would need to write

<BrowserRouter>
  <Route path="/account" component={AuthRoute(PrivateComponent)} />
</BrowserRouter>

where AuthRoute(PrivateComponent) is a class object and Route creates an instance out of it internally

However in the second case, its not an HOC, but a functional component that returns a valid React Element,

const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);

and hence

using <AuthRoute path="/account" component={PrivateComponent} /> , you called a component instance whereby props path and component are received by the functional component.


来源: stackexchange

问:
Replacing missing value with mean of 2 nearest rows in R
I have a datatable with missing value, and I want to replace it with the average of 2 nearest row.

```<code>library(data.table)
A <- data.table(id = c(1:10),
                Value = c(1:3,NA,5:10))

> A
    id Value
 1:  1     1
 2:  2     2
 3:  3     3
 4:  4    NA
 5:  5     5
 6:  6     6
 7:  7     7
 8:  8     8
 9:  9     9
10: 10    10
</code>```

For example, I want the NA to be replaced by the mean of row3 and row5, which is 4.

答:
I have made a function that work with more than one continuous NA in your data table.

```<code>library(data.table)
A <- data.table(id = c(1:11),
            Value = c(1,5:6,NA,10:12,NA,NA,NA,6))

library(dplyr)
# Finding the maximum length of a stretch of contiguous NA's in the column
a<- max(diff(which(!is.na(A$Value)))-1)

# Repeating the for loop "a" times and breaking when all NA's have been filled
repeat{
for(i in 1:a){
A$Value[which(A$Value%in%NA)] <- ((lag(A$Value, 1)+lead(A$Value, i))/2)[which(A$Value%in%NA)]
}
if(any(is.na(A$Value)) ==FALSE) { break }
}
</code>```

For every NA in the vector, the function inside the for loop calculates the mean of the value previous to NA and the next available one.

This is definitely not the most elegant or efficient solution as there is a lot of repetition but i believe it works with more than one NA in the manner you desire.

ContentLicense: CC BY-SA 3.0

Body:
I have a datatable with missing value, and I want to replace it with the average of 2 nearest row.

library(data.table)
A <- data.table(id = c(1:10),
                Value = c(1:3,NA,5:10))

> A
    id Value
 1:  1     1
 2:  2     2
 3:  3     3
 4:  4    NA
 5:  5     5
 6:  6     6
 7:  7     7
 8:  8     8
 9:  9     9
10: 10    10

For example, I want the NA to be replaced by the mean of row3 and row5, which is 4.

Body:
I have made a function that work with more than one continuous NA in your data table.

library(data.table)
A <- data.table(id = c(1:11),
            Value = c(1,5:6,NA,10:12,NA,NA,NA,6))

library(dplyr)
# Finding the maximum length of a stretch of contiguous NA's in the column
a<- max(diff(which(!is.na(A$Value)))-1)

# Repeating the for loop "a" times and breaking when all NA's have been filled
repeat{
for(i in 1:a){
A$Value[which(A$Value%in%NA)] <- ((lag(A$Value, 1)+lead(A$Value, i))/2)[which(A$Value%in%NA)]
}
if(any(is.na(A$Value)) ==FALSE) { break }
}

For every NA in the vector, the function inside the for loop calculates the mean of the value previous to NA and the next available one.

This is definitely not the most elegant or efficient solution as there is a lot of repetition but i believe it works with more than one NA in the manner you desire.


问:
Bind Spinner<Integer> to existing IntegerProperty
I am trying to bind the value of a Spinner to an integer property.
This answer is not satisfactory, because I do not want to create a new IntegerProperty, but instead bind the spinner's value to an existing one.

I tried to create a new IntegerProperty as shown in that answer, and then bind it to the existing one. However, this example code does not work:

```<code>import javafx.application.Application;
import javafx.beans.property.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane pane = new StackPane();

        IntegerProperty controlled = new SimpleIntegerProperty(); // I don't want to change this.

        final Spinner<Integer> spinner = new Spinner<>(0, 10, 5, 1);

        ObjectProperty<Integer> bridgeObject = new SimpleObjectProperty<>();
        IntegerProperty bridgeInteger = IntegerProperty.integerProperty(bridgeObject); // "Returns a IntegerProperty that wraps a Property and is bidirectionally bound to it."

        SpinnerValueFactory<Integer> valueFactory = spinner.getValueFactory(); // not null
        ObjectProperty<Integer> integerObjectProperty = valueFactory.valueProperty(); // not null
        integerObjectProperty.bindBidirectional(bridgeObject); // Throws NullPointerException, but not while debugging?!

        bridgeInteger.bindBidirectional(controlled);

        pane.getChildren().add(spinner);

        primaryStage.setScene(new Scene(pane, 300, 275));
        primaryStage.show();
    }
}
</code>```

Questions:

Is there a better way to bind to an existing IntegerProperty than to create two intermediate "bridge" Properties?

If not, why does my example code throw a NullPointerException? I checked with assertions that integerObjectProperty is not null. Oddly, the exception is not thrown if the code is debugged line by line (Why?). The author of the other question claimed he had done something like this successfully, but didn't respond to another user's request to post the code.

答:
Your null pointer exception is probably due to bridgeObject.get() being null when you do the binding.

All you need is

```<code>@Override
public void start(Stage primaryStage) throws Exception {
    StackPane pane = new StackPane();

    IntegerProperty controlled = new SimpleIntegerProperty(); // I don't want to change this.

    final Spinner<Integer> spinner = new Spinner<>(0, 10, 5, 1);

    spinner.getValueFactory().valueProperty().bindBidirectional(controlled.asObject());

    pane.getChildren().add(spinner);

    primaryStage.setScene(new Scene(pane, 300, 275));
    primaryStage.show();
}
</code>```

Body:
I am trying to bind the value of a Spinner to an integer property.
This answer is not satisfactory, because I do not want to create a new IntegerProperty, but instead bind the spinner's value to an existing one.

I tried to create a new IntegerProperty as shown in that answer, and then bind it to the existing one. However, this example code does not work:

import javafx.application.Application;
import javafx.beans.property.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane pane = new StackPane();

        IntegerProperty controlled = new SimpleIntegerProperty(); // I don't want to change this.

        final Spinner<Integer> spinner = new Spinner<>(0, 10, 5, 1);

        ObjectProperty<Integer> bridgeObject = new SimpleObjectProperty<>();
        IntegerProperty bridgeInteger = IntegerProperty.integerProperty(bridgeObject); // "Returns a IntegerProperty that wraps a Property and is bidirectionally bound to it."

        SpinnerValueFactory<Integer> valueFactory = spinner.getValueFactory(); // not null
        ObjectProperty<Integer> integerObjectProperty = valueFactory.valueProperty(); // not null
        integerObjectProperty.bindBidirectional(bridgeObject); // Throws NullPointerException, but not while debugging?!

        bridgeInteger.bindBidirectional(controlled);

        pane.getChildren().add(spinner);

        primaryStage.setScene(new Scene(pane, 300, 275));
        primaryStage.show();
    }
}

Questions:

Is there a better way to bind to an existing IntegerProperty than to create two intermediate "bridge" Properties?

If not, why does my example code throw a NullPointerException? I checked with assertions that integerObjectProperty is not null. Oddly, the exception is not thrown if the code is debugged line by line (Why?). The author of the other question claimed he had done something like this successfully, but didn't respond to another user's request to post the code.

Body:
Your null pointer exception is probably due to bridgeObject.get() being null when you do the binding.

All you need is

@Override
public void start(Stage primaryStage) throws Exception {
    StackPane pane = new StackPane();

    IntegerProperty controlled = new SimpleIntegerProperty(); // I don't want to change this.

    final Spinner<Integer> spinner = new Spinner<>(0, 10, 5, 1);

    spinner.getValueFactory().valueProperty().bindBidirectional(controlled.asObject());

    pane.getChildren().add(spinner);

    primaryStage.setScene(new Scene(pane, 300, 275));
    primaryStage.show();
}


问:
Espresso tests failing after unrelated changes
I had my espresso tests running. And unfortunately after some random changes all of my tests are failing. And I have never seen this error message at all:

Error message:-

```<code>java.lang.NoSuchMethodError: No interface method trackUsage(Ljava/lang/String;)V in class Landroid/support/test/internal/runner/tracker/UsageTracker; or its super classes (declaration of 'android.support.test.internal.runner.tracker.UsageTracker' appears in /data/app/mu.organyze.test-1/base.apk)
</code>```

Here's my dependency:-

```<code>dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        compile 'com.android.support:appcompat-v7:26.1.0'
        compile 'com.android.support.constraint:constraint-layout:1.0.2'
        compile 'com.google.firebase:firebase-auth:10.0.1'
        compile 'com.google.firebase:firebase-database:10.0.1'
        testCompile 'junit:junit:4.12'

        testCompile 'com.android.support.test:rules:1.0.1'
        testCompile 'com.google.dexmaker:dexmaker:1.2'
        testCompile 'org.mockito:mockito-core:2.12.0'
        testCompile 'org.mockito:mockito-android:2.12.0'

        androidTestCompile 'com.android.support:support-annotations:26.1.0'
        androidTestCompile 'com.android.support.test:runner:1.0.1'
        androidTestCompile 'com.android.support.test:rules:1.0.1'
        androidTestCompile 'org.mockito:mockito-core:2.12.0'
        androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
        androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2'

        androidTestUtil 'com.android.support.test:orchestrator:1.0.1'
        androidTestCompile 'org.hamcrest:hamcrest-integration:1.3'
    }
</code>```

答:
Just add this to dependencies:-

com.android.support.test.espresso:espresso-core:3.0.0

Body:
I had my espresso tests running. And unfortunately after some random changes all of my tests are failing. And I have never seen this error message at all:

Error message:-

java.lang.NoSuchMethodError: No interface method trackUsage(Ljava/lang/String;)V in class Landroid/support/test/internal/runner/tracker/UsageTracker; or its super classes (declaration of 'android.support.test.internal.runner.tracker.UsageTracker' appears in /data/app/mu.organyze.test-1/base.apk)

Here's my dependency:-

dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

        compile 'com.android.support:appcompat-v7:26.1.0'
        compile 'com.android.support.constraint:constraint-layout:1.0.2'
        compile 'com.google.firebase:firebase-auth:10.0.1'
        compile 'com.google.firebase:firebase-database:10.0.1'
        testCompile 'junit:junit:4.12'

        testCompile 'com.android.support.test:rules:1.0.1'
        testCompile 'com.google.dexmaker:dexmaker:1.2'
        testCompile 'org.mockito:mockito-core:2.12.0'
        testCompile 'org.mockito:mockito-android:2.12.0'

        androidTestCompile 'com.android.support:support-annotations:26.1.0'
        androidTestCompile 'com.android.support.test:runner:1.0.1'
        androidTestCompile 'com.android.support.test:rules:1.0.1'
        androidTestCompile 'org.mockito:mockito-core:2.12.0'
        androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
        androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2'

        androidTestUtil 'com.android.support.test:orchestrator:1.0.1'
        androidTestCompile 'org.hamcrest:hamcrest-integration:1.3'
    }


问:
Can I make a local module with the Swift Package manager?
I know the Swift package manager can compile code from github as a module for my project, but can I tell the package manager to compile code that is stored locally on my computer instead?

The idea is I have some code that I want to separate off from the rest of my project, so I keep it in a folder and the Swift compiler will build it so that that code can be imported like any other module.

答:
With the Swift 4 version tools, there's different means to do this-- where you don't have to provide a tagged version:

```<code>.package(url: "<path to repo>", .branch("master")),
</code>```

See also: https://github.com/apple/swift-package-manager/blob/master/Documentation/PackageDescriptionV4.md

Body:
With the Swift 4 version tools, there's different means to do this-- where you don't have to provide a tagged version:

.package(url: "<path to repo>", .branch("master")),

See also: https://github.com/apple/swift-package-manager/blob/master/Documentation/PackageDescriptionV4.md


问:
How do I speed up Meson build when many targets use the same C++ sources
I have a new meson project with 58 targets.  Many of them use the same *.cc files, and meson builds each *.cc file once for each target, which is much slower than autotools.  Also, the compile flags should be the same between targets, so in theory meson should be able to re-use the objects.

Is building many targets well-supported in meson?  Is there a standard solution for situations like this?  I could try to organize all of the sources in my project into shared libraries, but then I would have to decide how to group them, and with autotools I don't have to decide that.  I haven't managed to find documentation on this.

-BenRI

P.S. Here is a minimal example:

-------- file: app1.cc -------

```<code>int f(int x ,int y) {return x;}
int main() { return f(0,1);}
</code>```

------ file: meson.build -----

```<code>project('app12','cpp')
executable('app1',['app1.cc'])
executable('app2',['app1.cc'])
</code>```

---------- command -----------

```<code>% meson . meson
% cd meson
% meson configure -Dwarning_level=3
% ninja
</code>```

You should see a warning for unused parameter 'y' occur twice.
The file compile_commands.json also has two entries for app1.cc .

答:
Having the same source compiled with the same compile flags again and
again is just waste of CPU power because it will generate the same
binary file unless you have unreproducible build tricks like date and
time.

If what you meant was to build common code for all targets, you can
just use static_library to build your code and reuse it from all of
your target binary.

Move your f() in lib.cc and use the following meson.build.

```<code>project('app12','cpp')
mylib = static_library('mylib', 'lib.cc')
executable('app1', 'app1.cc', link_with : mylib)
executable('app2', 'app1.cc', link_with : mylib)
</code>```

Body:
I have a new meson project with 58 targets.  Many of them use the same *.cc files, and meson builds each *.cc file once for each target, which is much slower than autotools.  Also, the compile flags should be the same between targets, so in theory meson should be able to re-use the objects.

Is building many targets well-supported in meson?  Is there a standard solution for situations like this?  I could try to organize all of the sources in my project into shared libraries, but then I would have to decide how to group them, and with autotools I don't have to decide that.  I haven't managed to find documentation on this.

-BenRI

P.S. Here is a minimal example:

-------- file: app1.cc -------

int f(int x ,int y) {return x;}
int main() { return f(0,1);}

------ file: meson.build -----

project('app12','cpp')
executable('app1',['app1.cc'])
executable('app2',['app1.cc'])

---------- command -----------

% meson . meson
% cd meson
% meson configure -Dwarning_level=3
% ninja

You should see a warning for unused parameter 'y' occur twice.
The file compile_commands.json also has two entries for app1.cc .

Body:
Having the same source compiled with the same compile flags again and
again is just waste of CPU power because it will generate the same
binary file unless you have unreproducible build tricks like date and
time.

If what you meant was to build common code for all targets, you can
just use static_library to build your code and reuse it from all of
your target binary.

Move your f() in lib.cc and use the following meson.build.

project('app12','cpp')
mylib = static_library('mylib', 'lib.cc')
executable('app1', 'app1.cc', link_with : mylib)
executable('app2', 'app1.cc', link_with : mylib)

ContentLicense: CC BY-SA 4.0


问:
How to align the button at right side?
May i know how do i align the Button just beside these three Textviews? Instead of just below the Textviews.
This is the XML file.

    </p>

```<code>    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:orientation="vertical" android:id="@+id/linearlayout1"
        android:background="#000000">

            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/textview1"
                android:layout_alignParentLeft="true" android:text="Textview1" />

            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="Textview2"
                android:layout_alignParentLeft="true" android:id="@+id/Textview2" />

            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:layout_alignParentLeft="true"
                android:text="Textview3" android:id="@+id/Textview3" />

        <RelativeLayout android:id="@+id/relativeLayout2"
            android:layout_width="wrap_content" android:layout_height="wrap_content">
            <Button android:id="@+id/button" android:layout_width="70px"
                android:layout_height="38px" android:text="Button"
                />
        </RelativeLayout>
    </LinearLayout>
</RelativeLayout>
</code>```

答:
You can also use:</p>

```<code>android:layout_gravity="end"
</code>```

Title: How to align the button at right side?

Body:
May i know how do i align the Button just beside these three Textviews? Instead of just below the Textviews.
This is the XML file.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:orientation="vertical" android:id="@+id/linearlayout1"
        android:background="#000000">

            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/textview1"
                android:layout_alignParentLeft="true" android:text="Textview1" />

            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="Textview2"
                android:layout_alignParentLeft="true" android:id="@+id/Textview2" />

            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:layout_alignParentLeft="true"
                android:text="Textview3" android:id="@+id/Textview3" />

        <RelativeLayout android:id="@+id/relativeLayout2"
            android:layout_width="wrap_content" android:layout_height="wrap_content">
            <Button android:id="@+id/button" android:layout_width="70px"
                android:layout_height="38px" android:text="Button"
                />
        </RelativeLayout>
    </LinearLayout>
</RelativeLayout>

Body:
You can also use:

android:layout_gravity="end"


问:
Setting vertex weight with Dijkstra's shortest path algorithm
New to java.

What I am trying to make is a directed graph that represents a city. Most of the vertices are just streets but some are tourist sites which have weights (since one has to stay there for some time). I am working with Dijkstra's shortest path algorithm and has made some edition for adding the vertices' weights into it.

However, the problem occurs that when I set a vertex as a tour site and give it a weight, the vertex does not seem to have a weight at all when it is first visited. The weight then showed up when the vertex is visited the second time. I don't know where the problem has been, but I would guess it is somewhere that I am not directly editing the original variables.

The print out lines are marked below between * *. One is in calculateShortest(), another in calculateMin().

```<code>public class Graph
{
    protected HashMap<Integer, GraphNode> ntable = new HashMap<Integer, GraphNode>();
    //a hashmap of every node's edge treemap, in which edges are sorted according to weight of each
    protected HashMap<Integer, TreeMap<Integer, GraphEdge>> etable = new HashMap<Integer, TreeMap<Integer,GraphEdge>>();
}

public class GraphNode
{
    private int val;
    private boolean site;
    private boolean hotel;
    private int time;
    private int distance = Integer.MAX_VALUE;
    private LinkedList<GraphNode> shortest = new LinkedList<GraphNode>();
}

public class GraphEdge implements Comparable<GraphEdge>
{
    private int nd1;
    private int nd2;
    private int weight;
}

public class Path
{
    protected LinkedList<GraphNode> path = new LinkedList<GraphNode>();
    Graph g = new Graph();
    GraphNode start = new GraphNode(0);
    protected HashSet<GraphNode> settled = new HashSet<GraphNode>();
    protected HashSet<GraphNode> unsettled = new HashSet<GraphNode>();

    public Graph calculateShortest(int start)
    {
        g.ntable.get(start).setDist(0);
        unsettled.add(g.ntable.get(start));
        while (unsettled.size() != 0)
        {
            GraphNode current = getLowestCostNode(unsettled);
            unsettled.remove(current);
            TreeMap<Integer, GraphEdge> adjacentE = g.etable.get(current.getVal());
            *
           //printing out below shows vertex has no weight
            System.out.println("Curr: "+ current.getVal() + " " + current.getSiteTime());
            *
            for (GraphEdge edge: adjacentE.values())
            {
                GraphNode adjacent = g.ntable.get(edge.getEnd());
                int cost = edge.getWeight() + current.getSiteTime();
                if (!settled.contains(adjacent))
                {
                    calculateMin(adjacent, cost, current);
                    unsettled.add(adjacent);
                }
            }
            settled.add(current);
        }
    return g;
}

    public GraphNode getLowestCostNode(HashSet<GraphNode> unsettled)
    {
        GraphNode lowestDistNd = null;
        int lowestDist = Integer.MAX_VALUE;
        for (GraphNode nd : unsettled)
        {
            int nodeDist = nd.getDist();
            if (nodeDist < lowestDist)
            {
                lowestDist = nodeDist;
                lowestDistNd = nd;
            }
        }
        return lowestDistNd;
    }

    public void calculateMin(GraphNode evaNd, int cost, GraphNode startNd)
    {
        int startDist = startNd.getDist();
        if (startDist + cost < evaNd.getDist())
        {
            evaNd.setDist(startDist + cost);
            LinkedList<GraphNode> shortest = new LinkedList<GraphNode>(startNd.getShortest());
            shortest.add(startNd);
            evaNd.setShortest(shortest);
            *
            //print out if the node's distance is changed
            System.out.println("Change " + evaNd.getVal() + " " + evaNd.getDist());
            *
        }
    }
}
</code>```

Output of the line printing that shows problem (does not include main method output):

```<code>Curr: 1 0
Change: 2 10
Change: 3 15
Curr: 2 0
Change: 4 22
Change: 6 25
Curr: 3 0
Change: 5 25
Curr: 4 0 //1st time visiting shows no weight
Change: 6 23
Change: 5 24
Curr: 6 0
Curr: 5 0
Curr: 1 0
Curr: 2 0
Curr: 3 0
Curr: 4 30 //2nd time visiting shows weight
Curr: 6 0
Curr: 5 0
</code>```

For every vertex, getDist() return the distance from the source vertex to itself, and getCost() return the distance plus the weight of the vertex.

My main method is below. The addNodeEdge() have been tested to work well. I am using an example(see photo below) from Dijkstra Algorithm in Java and ABCDEF is 123456 in my case. In addition to the graph, I am trying to make D (which is vertex 4) as a site with a weight of 30.
Visualization of the graph

```<code>public static void main (String [] args){
    Path p = new Path();
    p.g.addNodeEdge(1, 2, 10);
    p.g.addNodeEdge(1, 3, 15);
    p.g.addNodeEdge(2, 4, 12);
    p.g.addNodeEdge(2, 6, 15);
    p.g.addNodeEdge(3, 5, 10);
    p.g.addNodeEdge(4, 6, 1);
    p.g.addNodeEdge(4, 5, 2);
    p.g.addNodeEdge(6, 5, 5);
    p.calculateShortest(1);
    System.out.println(p.g.ntable.get(5).getDist());//print out 24

    p.settled.clear();
    p.unsettled.clear();
    p.g.ntable.get(4).setSite(30);
    p.calculateShortest(1);
    System.out.println(p.g.ntable.get(5).getDist());//still print out 24
}
</code>```

I would expect the shortest path to E (vertex 5) 30 and to F (vertex 6) 25 because the path through D (vertex 4) with a weight of 30 is too large. However, what I have got here after I changed D's weight is exactly the same before I added weight to D. Like I explained above, I think the problem is with D's weight changing... Any help would be great appreciated.

答:
Even though you are clearing out the settled and unsettled HashSets, the variable that keeps track of the shortest path found to a node thus far is the GraphNode instance variable distance. The distance for node 5 isn't reset from the value of 24 after running calculateShortest the first time, and will of course remain the same after calling the method after setting node 4's site time to 30.

One possible solution is to change the beginning of calculateShortest() to reset all of the node distances:

```<code>public Graph calculateShortest(int start) {
    for (GraphNode n : g.ntable.values()) {
        n.setDist(Integer.MAX_VALUE);
    }
    g.ntable.get(start).setDist(0);
    ...
</code>```

Also, it took some time to figure this one out, mainly because the code you posted is formatted pretty poorly. Next time please avoid posting nested classes and also include all potentially relevant implementation details that aren't trivial getters/setters (such as addNodeEdge). You never know where that pesky bug might be hiding!

Body:
New to java.

What I am trying to make is a directed graph that represents a city. Most of the vertices are just streets but some are tourist sites which have weights (since one has to stay there for some time). I am working with Dijkstra's shortest path algorithm and has made some edition for adding the vertices' weights into it.

However, the problem occurs that when I set a vertex as a tour site and give it a weight, the vertex does not seem to have a weight at all when it is first visited. The weight then showed up when the vertex is visited the second time. I don't know where the problem has been, but I would guess it is somewhere that I am not directly editing the original variables.

The print out lines are marked below between * *. One is in calculateShortest(), another in calculateMin().

public class Graph
{
    protected HashMap<Integer, GraphNode> ntable = new HashMap<Integer, GraphNode>();
    //a hashmap of every node's edge treemap, in which edges are sorted according to weight of each
    protected HashMap<Integer, TreeMap<Integer, GraphEdge>> etable = new HashMap<Integer, TreeMap<Integer,GraphEdge>>();
}

public class GraphNode
{
    private int val;
    private boolean site;
    private boolean hotel;
    private int time;
    private int distance = Integer.MAX_VALUE;
    private LinkedList<GraphNode> shortest = new LinkedList<GraphNode>();
}

public class GraphEdge implements Comparable<GraphEdge>
{
    private int nd1;
    private int nd2;
    private int weight;
}

public class Path
{
    protected LinkedList<GraphNode> path = new LinkedList<GraphNode>();
    Graph g = new Graph();
    GraphNode start = new GraphNode(0);
    protected HashSet<GraphNode> settled = new HashSet<GraphNode>();
    protected HashSet<GraphNode> unsettled = new HashSet<GraphNode>();

    public Graph calculateShortest(int start)
    {
        g.ntable.get(start).setDist(0);
        unsettled.add(g.ntable.get(start));
        while (unsettled.size() != 0)
        {
            GraphNode current = getLowestCostNode(unsettled);
            unsettled.remove(current);
            TreeMap<Integer, GraphEdge> adjacentE = g.etable.get(current.getVal());
            *
           //printing out below shows vertex has no weight
            System.out.println("Curr: "+ current.getVal() + " " + current.getSiteTime());
            *
            for (GraphEdge edge: adjacentE.values())
            {
                GraphNode adjacent = g.ntable.get(edge.getEnd());
                int cost = edge.getWeight() + current.getSiteTime();
                if (!settled.contains(adjacent))
                {
                    calculateMin(adjacent, cost, current);
                    unsettled.add(adjacent);
                }
            }
            settled.add(current);
        }
    return g;
}

    public GraphNode getLowestCostNode(HashSet<GraphNode> unsettled)
    {
        GraphNode lowestDistNd = null;
        int lowestDist = Integer.MAX_VALUE;
        for (GraphNode nd : unsettled)
        {
            int nodeDist = nd.getDist();
            if (nodeDist < lowestDist)
            {
                lowestDist = nodeDist;
                lowestDistNd = nd;
            }
        }
        return lowestDistNd;
    }

    public void calculateMin(GraphNode evaNd, int cost, GraphNode startNd)
    {
        int startDist = startNd.getDist();
        if (startDist + cost < evaNd.getDist())
        {
            evaNd.setDist(startDist + cost);
            LinkedList<GraphNode> shortest = new LinkedList<GraphNode>(startNd.getShortest());
            shortest.add(startNd);
            evaNd.setShortest(shortest);
            *
            //print out if the node's distance is changed
            System.out.println("Change " + evaNd.getVal() + " " + evaNd.getDist());
            *
        }
    }
}

Output of the line printing that shows problem (does not include main method output):

Curr: 1 0
Change: 2 10
Change: 3 15
Curr: 2 0
Change: 4 22
Change: 6 25
Curr: 3 0
Change: 5 25
Curr: 4 0 //1st time visiting shows no weight
Change: 6 23
Change: 5 24
Curr: 6 0
Curr: 5 0
Curr: 1 0
Curr: 2 0
Curr: 3 0
Curr: 4 30 //2nd time visiting shows weight
Curr: 6 0
Curr: 5 0

For every vertex, getDist() return the distance from the source vertex to itself, and getCost() return the distance plus the weight of the vertex.

My main method is below. The addNodeEdge() have been tested to work well. I am using an example(see photo below) from Dijkstra Algorithm in Java and ABCDEF is 123456 in my case. In addition to the graph, I am trying to make D (which is vertex 4) as a site with a weight of 30.
Visualization of the graph

public static void main (String [] args){
    Path p = new Path();
    p.g.addNodeEdge(1, 2, 10);
    p.g.addNodeEdge(1, 3, 15);
    p.g.addNodeEdge(2, 4, 12);
    p.g.addNodeEdge(2, 6, 15);
    p.g.addNodeEdge(3, 5, 10);
    p.g.addNodeEdge(4, 6, 1);
    p.g.addNodeEdge(4, 5, 2);
    p.g.addNodeEdge(6, 5, 5);
    p.calculateShortest(1);
    System.out.println(p.g.ntable.get(5).getDist());//print out 24

    p.settled.clear();
    p.unsettled.clear();
    p.g.ntable.get(4).setSite(30);
    p.calculateShortest(1);
    System.out.println(p.g.ntable.get(5).getDist());//still print out 24
}

I would expect the shortest path to E (vertex 5) 30 and to F (vertex 6) 25 because the path through D (vertex 4) with a weight of 30 is too large. However, what I have got here after I changed D's weight is exactly the same before I added weight to D. Like I explained above, I think the problem is with D's weight changing... Any help would be great appreciated.

Body:
Even though you are clearing out the settled and unsettled HashSets, the variable that keeps track of the shortest path found to a node thus far is the GraphNode instance variable distance. The distance for node 5 isn't reset from the value of 24 after running calculateShortest the first time, and will of course remain the same after calling the method after setting node 4's site time to 30.

One possible solution is to change the beginning of calculateShortest() to reset all of the node distances:

public Graph calculateShortest(int start) {
    for (GraphNode n : g.ntable.values()) {
        n.setDist(Integer.MAX_VALUE);
    }
    g.ntable.get(start).setDist(0);
    ...

Also, it took some time to figure this one out, mainly because the code you posted is formatted pretty poorly. Next time please avoid posting nested classes and also include all potentially relevant implementation details that aren't trivial getters/setters (such as addNodeEdge). You never know where that pesky bug might be hiding!


问:
How to update Xcode Command Line Tools?
I am trying to update Command line tools on my mac osx.

```<code>~  softwareupdate --list
Software Update Tool
Copyright 2002-2015 Apple Inc.

Finding available software
Software Update found the following new or updated software:

   * Command Line Tools (macOS El Capitan version 10.11) for Xcode-8.2
    Command Line Tools (macOS El Capitan version 10.11) for Xcode (8.2), 150374K [recommended]
   * iTunesX-12.5.5
    iTunes (12.5.5), 263476K [recommended]
</code>```

But when I run the update command, I get this error:

```<code>softwareupdate -i Command Line Tools (macOS El Capitan version 10.11) for Xcode-8.2
zsh: number expected
</code>```

This doesn't work either:

```<code>softwareupdate -i Command Line Tools
Software Update Tool
Copyright 2002-2015 Apple Inc.

Command: No such update
Line: No such update
Tools: No such update
No updates are available.
</code>```

What specific string should I specify after sofwareupdate -i command?

答:
I'm going to answer a slightly different question here, because this question came up when I searched for a solution to my problem. Hopefully it'll help someone (and it'll surely help me next time I run into the same issue).

I wanted to upgrade the command line tools from version 8 to 9. The App Store didn't suggest this upgrade, and neither did softwareupdate --list.

```<code>xcode-select --install
</code>```

installed the new version of the tools. But clang --version still gave 8.0.0 as the version number. xcode-select -r and rebooting didn't solve this issue.

xcode-select -p returned /Applications/Xcode.app/Contents/Developer, and clang --version reported an installation directory under there. I thought I'd start over again.

```<code>sudo rm -rf /Applications/Xcode.app
</code>```

deleted version 8 of the tools. But xcode-select --install said the command line tools were already installed.

```<code>sudo xcode-select -r
</code>```

Now, sudo xcode-select -p returns /Library/Developer/CommandLineTools/.

It seems that the problem was that the new version of the tools are installed to a different directory, and xcode-select -r is not clever enough to find the latest version.

Title: How to update Xcode Command Line Tools?

Body:
I am trying to update Command line tools on my mac osx.

~  softwareupdate --list
Software Update Tool
Copyright 2002-2015 Apple Inc.

Finding available software
Software Update found the following new or updated software:

   * Command Line Tools (macOS El Capitan version 10.11) for Xcode-8.2
    Command Line Tools (macOS El Capitan version 10.11) for Xcode (8.2), 150374K [recommended]
   * iTunesX-12.5.5
    iTunes (12.5.5), 263476K [recommended]

But when I run the update command, I get this error:

softwareupdate -i Command Line Tools (macOS El Capitan version 10.11) for Xcode-8.2
zsh: number expected

This doesn't work either:

softwareupdate -i Command Line Tools
Software Update Tool
Copyright 2002-2015 Apple Inc.

Command: No such update
Line: No such update
Tools: No such update
No updates are available.

What specific string should I specify after sofwareupdate -i command?

Body:
I'm going to answer a slightly different question here, because this question came up when I searched for a solution to my problem. Hopefully it'll help someone (and it'll surely help me next time I run into the same issue).

I wanted to upgrade the command line tools from version 8 to 9. The App Store didn't suggest this upgrade, and neither did softwareupdate --list.

xcode-select --install

installed the new version of the tools. But clang --version still gave 8.0.0 as the version number. xcode-select -r and rebooting didn't solve this issue.

xcode-select -p returned /Applications/Xcode.app/Contents/Developer, and clang --version reported an installation directory under there. I thought I'd start over again.

sudo rm -rf /Applications/Xcode.app

deleted version 8 of the tools. But xcode-select --install said the command line tools were already installed.

sudo xcode-select -r

Now, sudo xcode-select -p returns /Library/Developer/CommandLineTools/.

It seems that the problem was that the new version of the tools are installed to a different directory, and xcode-select -r is not clever enough to find the latest version.


问:
RAML Code understanding
I have below requirement for designing simple RAML. I’m newbie in RAML coding so would like to know if my code is according to requirement or not

Requirement:

Has at least 1 endpoint with a GET and POST method.

Includes description attribute of the API

Includes description attribute of the method

The GET request takes a query parameter of "mulesoft"

Define the response with an object that contains least a string and
integer  data type

Includes an example for a 200 response code that matches the
definition’s response object from above

My code:

```<code>#%RAML 1.0
title: Coding_Champions
version: 1.0.development
baseUri: http://localhost:8004/api
description: This API displays and adds Organisation with details

types:
  Org:
    type: object
    properties:
      name: string
      address: string
      pincode: integer
/details:
  displayName: Company Details
  description: Coding challenge which takes query parameter of "mulesoft"

  get:
    description: Retrieve a list of all the Orgs
    queryParameters:
      mulesoft:
       description: Specify the Org name that you want to retrieve
       type:    boolean
       required: true
    responses:
      200:
        body:
          application/json:
            type: Org
            examples:
              MuleSoft:
                name: MuleSoft
                address: 77 Geary Street, Suite 400
                pincode: 94108
  post:
      description: Add a Org to list
      body:
        application/json:
            type: Org
            examples:
              Cognizant:
                name: Cognizant
                address: DLF
                pincode: 9771
      responses:
        201:
          body:
            application/json:
              example: |
                {
                "message":"New Org updated but not really"
                }
</code>```

I’m more of concerned with one of point in the requirement

```<code>"The GET request takes a query parameter of “mulesoft”
</code>```

Does it mean I should give mulesoft as parameter dynamically in my url, If yes then other than mulesoft is passed as parameter then it should throw an error ?

(or)

Does it mean i need to hard code “mulesoft” in my RAML code as I have done now ?

Can you please clear me on this ?

答:
Does it mean I need to hard code “mulesoft” in my RAML code as I have
  done now ?

Yes.You should define that in RAML as you are doing right now.Since its required parameter,its presence could be validated in implementation.

Title: RAML Code understanding

Body:
I have below requirement for designing simple RAML. I’m newbie in RAML coding so would like to know if my code is according to requirement or not

Requirement:

Has at least 1 endpoint with a GET and POST method.

Includes description attribute of the API

Includes description attribute of the method

The GET request takes a query parameter of "mulesoft"

Define the response with an object that contains least a string and
integer  data type

Includes an example for a 200 response code that matches the
definition’s response object from above

My code:

#%RAML 1.0
title: Coding_Champions
version: 1.0.development
baseUri: http://localhost:8004/api
description: This API displays and adds Organisation with details

types:
  Org:
    type: object
    properties:
      name: string
      address: string
      pincode: integer
/details:
  displayName: Company Details
  description: Coding challenge which takes query parameter of "mulesoft"

  get:
    description: Retrieve a list of all the Orgs
    queryParameters:
      mulesoft:
       description: Specify the Org name that you want to retrieve
       type:    boolean
       required: true
    responses:
      200:
        body:
          application/json:
            type: Org
            examples:
              MuleSoft:
                name: MuleSoft
                address: 77 Geary Street, Suite 400
                pincode: 94108
  post:
      description: Add a Org to list
      body:
        application/json:
            type: Org
            examples:
              Cognizant:
                name: Cognizant
                address: DLF
                pincode: 9771
      responses:
        201:
          body:
            application/json:
              example: |
                {
                "message":"New Org updated but not really"
                }

I’m more of concerned with one of point in the requirement

"The GET request takes a query parameter of “mulesoft”

Does it mean I should give mulesoft as parameter dynamically in my url, If yes then other than mulesoft is passed as parameter then it should throw an error ?

(or)

Does it mean i need to hard code “mulesoft” in my RAML code as I have done now ?

Can you please clear me on this ?


问:
Disable gzip compression in request to GeoCoder web site
I have a example application written in Delphi using /N Software's SOAP component. This application communicates with the GeoCoder site (see geocoder.us) to get latitude and longitude from a provided address. Works ok.

Wrote a very simple WCF client to basically do the same thing but it does not work. I used Fiddler2 to see what is happening.

The Delphi application gets back basic text. My WCF application gets back content that is gzip compressed. This must be the default as I did not set this. When the response comes back there is no means to decompress the data.

I see many many web pages going into detail about setting gzip compression but nothing about disabling this.

The question is how can I get my WCF client to request from the GeoCoder site, a response in plain text (I know that compression is good etc) but in this instance I just want to see this working.

The sites WSDL is at http://rpc.geocoder.us/dist/eg/clients/GeoCoder.wsdl

My source code (its very elementary as I learning this stuff)

```<code>   using System;
   using System.Collections.Generic;
   using System.ComponentModel;
   using System.Data;
   using System.Drawing;
   using System.Linq;
   using System.Text;
   using System.Windows.Forms;
   using System.ServiceModel;
   using GeoCodeTest.ServiceReference1;

   namespace GeoCodeTest
   {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private GeocoderResult[] LocationResult = null;
            private GeoCode_PortTypeClient proxy = null;

            private void btnGo_Click(object sender, EventArgs e)
            {
                LocationResult = proxy.geocode(txtLocation.Text); // always returns a null !!!
                geocoderResultBindingSource.DataSource = LocationResult;
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                proxy = new GeoCode_PortTypeClient("GeoCode_Port");
            }
        }
   }
</code>```

This is the app.config file that was generated.

```<code> <?xml version="1.0" encoding="utf-8" ?>
   <configuration>
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="GeoCode_Binding" closeTimeout="00:01:00" openTimeout="00:01:00"
                        receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
                        bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                        useDefaultWebProxy="true">
                        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                        <security mode="None">
                            <transport clientCredentialType="None" proxyCredentialType="None"
                                realm="" />
                            <message clientCredentialType="UserName" algorithmSuite="Default" />
                        </security>
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="http://rpc.geocoder.us/service/soap/" binding="basicHttpBinding"
                    bindingConfiguration="GeoCode_Binding" contract="ServiceReference1.GeoCode_PortType"
                    name="GeoCode_Port" />
            </client>
        </system.serviceModel>
   </configuration>
</code>```

Is there something I can add/remove/change to the app.config so that a WCF client request will ask for plain text like the Delphi application?

答:
I had a quick look at this, and it is NOT the compression that is causing the issue. As already mentioned, WCF clients (v4) can decompress the data fine. In fact, if you modify the outgoing request message header and remove the "gzip, deflate" from the Accept-Encoding header the response comes back already uncompressed, however the data is still not present in the return object. There seems to be an issue with the way the client has generated its datacontract I think.

If I have some more time, I will have a closer look but it may take sometime to find out where the exact mismatch(s) occur.

ContentLicense: CC BY-SA 2.5

Body:
I have a example application written in Delphi using /N Software's SOAP component. This application communicates with the GeoCoder site (see geocoder.us) to get latitude and longitude from a provided address. Works ok.

Wrote a very simple WCF client to basically do the same thing but it does not work. I used Fiddler2 to see what is happening.

The Delphi application gets back basic text. My WCF application gets back content that is gzip compressed. This must be the default as I did not set this. When the response comes back there is no means to decompress the data.

I see many many web pages going into detail about setting gzip compression but nothing about disabling this.

The question is how can I get my WCF client to request from the GeoCoder site, a response in plain text (I know that compression is good etc) but in this instance I just want to see this working.

The sites WSDL is at http://rpc.geocoder.us/dist/eg/clients/GeoCoder.wsdl

My source code (its very elementary as I learning this stuff)

   using System;
   using System.Collections.Generic;
   using System.ComponentModel;
   using System.Data;
   using System.Drawing;
   using System.Linq;
   using System.Text;
   using System.Windows.Forms;
   using System.ServiceModel;
   using GeoCodeTest.ServiceReference1;

   namespace GeoCodeTest
   {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private GeocoderResult[] LocationResult = null;
            private GeoCode_PortTypeClient proxy = null;

            private void btnGo_Click(object sender, EventArgs e)
            {
                LocationResult = proxy.geocode(txtLocation.Text); // always returns a null !!!
                geocoderResultBindingSource.DataSource = LocationResult;
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                proxy = new GeoCode_PortTypeClient("GeoCode_Port");
            }
        }
   }

This is the app.config file that was generated.

 <?xml version="1.0" encoding="utf-8" ?>
   <configuration>
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="GeoCode_Binding" closeTimeout="00:01:00" openTimeout="00:01:00"
                        receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
                        bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                        useDefaultWebProxy="true">
                        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                        <security mode="None">
                            <transport clientCredentialType="None" proxyCredentialType="None"
                                realm="" />
                            <message clientCredentialType="UserName" algorithmSuite="Default" />
                        </security>
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="http://rpc.geocoder.us/service/soap/" binding="basicHttpBinding"
                    bindingConfiguration="GeoCode_Binding" contract="ServiceReference1.GeoCode_PortType"
                    name="GeoCode_Port" />
            </client>
        </system.serviceModel>
   </configuration>

Is there something I can add/remove/change to the app.config so that a WCF client request will ask for plain text like the Delphi application?


问:
DOM manipulation - Center H1 element using javascript
How can I center my h1 using javascript?

h1 is
Instrument track Recommendations
, I tried below and it does not work.

```<code>var centeredH1 = document.getElementsByTagName("h1");
centeredH1.style.textAlign = "center";`
</code>```

I know it would work with an ID using document.getElementById("h1id"); if I had one but I don't have an ID to work with.

答:
DEMO

JAVASCRIPT

```<code>var h1s = document.getElementsByTagName("h1");
h1s[0].style.textAlign="center";
</code>```

HTML

```<code><h1>
THIS IS TO BE CENTERED
</h1>
</code>```

You need to access first element from array returned by javascript getElementsByTagName

Body:
How can I center my h1 using javascript?

h1 is
Instrument track Recommendations
, I tried below and it does not work.

var centeredH1 = document.getElementsByTagName("h1");
centeredH1.style.textAlign = "center";`

I know it would work with an ID using document.getElementById("h1id"); if I had one but I don't have an ID to work with.

Body:
DEMO

JAVASCRIPT

var h1s = document.getElementsByTagName("h1");
h1s[0].style.textAlign="center";

HTML

<h1>
THIS IS TO BE CENTERED
</h1>

You need to access first element from array returned by javascript getElementsByTagName


问:
Iterating javascript object synchronously
I have an object like so:

```<code>let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}
</code>```

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

```<code>  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }
</code>```

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

```<code>let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}
</code>```

答:
The following will do what you ask, it returns an array of resolve values.

Do you want to stop processing if any one of them rejects? In case you need to make some changes, now it rejects if any of them reject and won't continue processing they keys in your object (object named myObject):

var myObject = {
  'one': ["one"],
  'two': ["two"]
};
var doStuff = arr =>
  console.log("starting:", arr[0]) ||
  Promise.resolve(arr[0]);

var [promise,result] =
  Object.keys(myObject)
    .reduce(
      ([promise,results], key) =>
        [
          promise
          .then(
            resolve =>
              doStuff(myObject[key])
          )
          .then(
            resolve => results.push(resolve)&&resolve
          )
          .then(
            resolve => console.log("done:", resolve)
          )
          ,results
        ]
      , [Promise.resolve(), []]
    )
promise.then(
  _ => {
    console.log("done all",result)
  }
);```
</div>
</div>
</p>

<p>The answer ayushgp uses recursion, here is a working example that doesn't need changes to doSomething:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = {
  'one': ["one"],
  'two': ["two"]
};
var doStuff = arr =>
  console.log("starting:",arr[0]) ||
  Promise.resolve(arr[0])

var process = (arr,processFn) => {
  const rec = (arr,processFn,promise,results) =>
    arr.length === 0
      ? promise.then(_=>results)
      : promise
        .then(_ => processFn(arr[0][1]))
        .then(result=>results.push(result)&&console.log("resolved:",result))
        .then(_ => rec(arr.slice(1),processFn,promise,results));
  return rec(arr,processFn,Promise.resolve(),[]);
};
process(
  Object.keys(myObject).map(key=>[key,myObject[key]]),
  doStuff
)
.then(
  results => console.log("done all, results:",results)
);</code>```

Body:
I have an object like so:

let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}

Body:
The following will do what you ask, it returns an array of resolve values.

Do you want to stop processing if any one of them rejects? In case you need to make some changes, now it rejects if any of them reject and won't continue processing they keys in your object (object named myObject):

var myObject = {
  'one': ["one"],
  'two': ["two"]
};
var doStuff = arr =>
  console.log("starting:", arr[0]) ||
  Promise.resolve(arr[0]);

var [promise,result] =
  Object.keys(myObject)
    .reduce(
      ([promise,results], key) =>
        [
          promise
          .then(
            resolve =>
              doStuff(myObject[key])
          )
          .then(
            resolve => results.push(resolve)&&resolve
          )
          .then(
            resolve => console.log("done:", resolve)
          )
          ,results
        ]
      , [Promise.resolve(), []]
    )
promise.then(
  _ => {
    console.log("done all",result)
  }
);

The answer ayushgp uses recursion, here is a working example that doesn't need changes to doSomething:

var myObject = {
  'one': ["one"],
  'two': ["two"]
};
var doStuff = arr =>
  console.log("starting:",arr[0]) ||
  Promise.resolve(arr[0])

var process = (arr,processFn) => {
  const rec = (arr,processFn,promise,results) =>
    arr.length === 0
      ? promise.then(_=>results)
      : promise
        .then(_ => processFn(arr[0][1]))
        .then(result=>results.push(result)&&console.log("resolved:",result))
        .then(_ => rec(arr.slice(1),processFn,promise,results));
  return rec(arr,processFn,Promise.resolve(),[]);
};
process(
  Object.keys(myObject).map(key=>[key,myObject[key]]),
  doStuff
)
.then(
  results => console.log("done all, results:",results)
);


问:
the -= operator not working properly, not incrementing when its supposed to be
The program is supposed to make heroes fight against each other and the winner and number of rounds that took them to fight against each other and won is displayed.
Like in this format;

```<code>Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.

The thing is, the program would print out like this :

Greek Heroes
Quarter Finals
Ancient Battle!  vs Hector : Winner is  in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 3 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 3 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 6 rounds.
Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 3 rounds.

However, what it should logically print out is :

Greek Heroes
Quarter Finals
Ancient Battle! vs Hector : Winner is in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 4 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 4 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 7 rounds.

Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 4 rounds.
</code>```

I am guessing it has something to do with -= operator logic and i can't seem to figure it out. Any help?

Hero.cpp

```<code>#include "Hero.h"
#include <iostream>
#include <cstring>
using namespace std;
namespace sict {

    Hero::Hero()
    {
        m_name[0] = '\0';
        m_health = 0;
        m_attack = 0;

    }

    Hero::Hero(char name[], int health, int attack)
    {

        if (m_name != nullptr || m_name != "") {
            strcpy(m_name, name);

        }
        else {
            m_name[0] = '\0';
        }

        m_attack = attack;
        m_health = health;

    }

    void Hero::operator-=(int attack) {
        if (attack > 0) {
            m_health -= attack;
        }
        if (attack > m_health) {
            m_health = 0;
        }
    }
    bool Hero::isAlive() const {
        if (m_health > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    int Hero::attackStrength() const {
        if (m_attack == 0) {
            return 0;
        }
        else {
            return m_attack;
        }
    }
    ostream& operator<<(ostream& os, const Hero& hero) {
        if (hero.m_name == '\0') {
            os << "No Hero";
        }
        else {
            os << hero.m_name;
        }
        return os;
    }
    const Hero& operator*(const Hero& first, const Hero& second) {
        cout << "Ancient Battle! ";
        cout << first;
        cout << " vs ";
        cout << second;
        cout << " : ";
        Hero A = first;
        Hero B = second;
        const Hero *winner = nullptr;
        int max_rounds = 0;
        while (A.isAlive() && B.isAlive() && max_rounds < 200) {
            max_rounds++;
            A -= B.attackStrength();
            B -= A.attackStrength();

        }

        bool draw;

        if (A.isAlive() && B.isAlive()) { draw = true; }
        else { draw = false; }

        if (draw) {
            winner = &first;
        }
        else if (A.isAlive())
        {
            winner = &first;
        }
        else {
            winner = &second;
        }
        cout << "Winner is ";
        cout << *winner;
        cout << " in " << max_rounds << " rounds. " << endl;
        return *winner;

    }
}
</code>```

Hero.h

```<code>#ifndef SICT_HERO_H_
#define SICT_HERO_H_
#include <iostream>
namespace sict {
    class Hero {
        char m_name[41];
        int m_health;
        int m_attack;
    public:
        Hero();
        Hero(char name[], int health, int attack);
        void operator-=(int attack);
        bool isAlive() const;
        int attackStrength() const;
        friend std::ostream& operator<<(std::ostream& os, const Hero& hero);
    };
    const Hero& operator*(const Hero& first, const Hero& second);
}
#endif
</code>```

Main.cpp

```<code>#include <iostream>
#include "Hero.h"

using namespace std;
using namespace sict;

int main() {

    cout << "Greek Heroes";
    Hero moneyhunger("", 40, 4);
    Hero hercules("Hercules", 32, 4);
    Hero theseus("Theseus", 14, 5);
    Hero oddyseus("Odysseus", 15, 3);
    Hero ajax("Ajax", 17, 5);
    Hero achilles("Achilles", 20, 6);
    Hero hector("Hector", 30, 5);
    Hero atalanta("Atalanta", 10, 3);
    Hero hippolyta("Hippolyta", 10, 2);

    cout << endl << "Quarter Finals" << endl;
    const Hero& greek_winner0 = moneyhunger * hector;
    const Hero& greek_winner1 = achilles * hector;
    const Hero& greek_winner2 = hercules * theseus;
    const Hero& greek_winner3 = oddyseus * ajax;
    const Hero& greek_winner4 = atalanta * hippolyta;

    cout << endl << "Semi Finals" << endl;
    const Hero& greek_winner_semifinal1 = greek_winner1  * greek_winner2;
    const Hero& greek_winner_semifinal2 = greek_winner3  * greek_winner4;

    cout << endl << "Finals" << endl;
    greek_winner_semifinal1 * greek_winner_semifinal2;
    system("pause");
    return 0;
}
</code>```

答:
You have the function

```<code>void Hero::operator-=(int attack) {
    if (attack > 0) {
        m_health -= attack;
    }
    if (attack > m_health) {
        m_health = 0;
    }
}
</code>```

This will sometimes reduce health more than once.

Suppose health is 15 and attack is 10. The first if-statement will reduce the health to 5. The second if-statement will then reduce it again to 0.

To avoid this you can do:

```<code>void Hero::operator-=(int attack) {
    if (attack > 0) {
        if (attack > m_health) {
            m_health = 0;
        } else {
            m_health -= attack;
        }
    }
}
</code>```

This will reduce health to 0 only when the attack is at least as large as the remaining health.

Body:
The program is supposed to make heroes fight against each other and the winner and number of rounds that took them to fight against each other and won is displayed.
Like in this format;

Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.

The thing is, the program would print out like this :

Greek Heroes
Quarter Finals
Ancient Battle!  vs Hector : Winner is  in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 3 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 3 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 6 rounds.
Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 3 rounds.

However, what it should logically print out is :

Greek Heroes
Quarter Finals
Ancient Battle! vs Hector : Winner is in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 4 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 4 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 7 rounds.

Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 4 rounds.

I am guessing it has something to do with -= operator logic and i can't seem to figure it out. Any help?

Hero.cpp

#include "Hero.h"
#include <iostream>
#include <cstring>
using namespace std;
namespace sict {

    Hero::Hero()
    {
        m_name[0] = '\0';
        m_health = 0;
        m_attack = 0;

    }

    Hero::Hero(char name[], int health, int attack)
    {

        if (m_name != nullptr || m_name != "") {
            strcpy(m_name, name);

        }
        else {
            m_name[0] = '\0';
        }

        m_attack = attack;
        m_health = health;

    }

    void Hero::operator-=(int attack) {
        if (attack > 0) {
            m_health -= attack;
        }
        if (attack > m_health) {
            m_health = 0;
        }
    }
    bool Hero::isAlive() const {
        if (m_health > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    int Hero::attackStrength() const {
        if (m_attack == 0) {
            return 0;
        }
        else {
            return m_attack;
        }
    }
    ostream& operator<<(ostream& os, const Hero& hero) {
        if (hero.m_name == '\0') {
            os << "No Hero";
        }
        else {
            os << hero.m_name;
        }
        return os;
    }
    const Hero& operator*(const Hero& first, const Hero& second) {
        cout << "Ancient Battle! ";
        cout << first;
        cout << " vs ";
        cout << second;
        cout << " : ";
        Hero A = first;
        Hero B = second;
        const Hero *winner = nullptr;
        int max_rounds = 0;
        while (A.isAlive() && B.isAlive() && max_rounds < 200) {
            max_rounds++;
            A -= B.attackStrength();
            B -= A.attackStrength();

        }

        bool draw;

        if (A.isAlive() && B.isAlive()) { draw = true; }
        else { draw = false; }

        if (draw) {
            winner = &first;
        }
        else if (A.isAlive())
        {
            winner = &first;
        }
        else {
            winner = &second;
        }
        cout << "Winner is ";
        cout << *winner;
        cout << " in " << max_rounds << " rounds. " << endl;
        return *winner;

    }
}

Hero.h

#ifndef SICT_HERO_H_
#define SICT_HERO_H_
#include <iostream>
namespace sict {
    class Hero {
        char m_name[41];
        int m_health;
        int m_attack;
    public:
        Hero();
        Hero(char name[], int health, int attack);
        void operator-=(int attack);
        bool isAlive() const;
        int attackStrength() const;
        friend std::ostream& operator<<(std::ostream& os, const Hero& hero);
    };
    const Hero& operator*(const Hero& first, const Hero& second);
}
#endif

Main.cpp

#include <iostream>
#include "Hero.h"

using namespace std;
using namespace sict;

int main() {

    cout << "Greek Heroes";
    Hero moneyhunger("", 40, 4);
    Hero hercules("Hercules", 32, 4);
    Hero theseus("Theseus", 14, 5);
    Hero oddyseus("Odysseus", 15, 3);
    Hero ajax("Ajax", 17, 5);
    Hero achilles("Achilles", 20, 6);
    Hero hector("Hector", 30, 5);
    Hero atalanta("Atalanta", 10, 3);
    Hero hippolyta("Hippolyta", 10, 2);

    cout << endl << "Quarter Finals" << endl;
    const Hero& greek_winner0 = moneyhunger * hector;
    const Hero& greek_winner1 = achilles * hector;
    const Hero& greek_winner2 = hercules * theseus;
    const Hero& greek_winner3 = oddyseus * ajax;
    const Hero& greek_winner4 = atalanta * hippolyta;

    cout << endl << "Semi Finals" << endl;
    const Hero& greek_winner_semifinal1 = greek_winner1  * greek_winner2;
    const Hero& greek_winner_semifinal2 = greek_winner3  * greek_winner4;

    cout << endl << "Finals" << endl;
    greek_winner_semifinal1 * greek_winner_semifinal2;
    system("pause");
    return 0;
}

Body:
You have the function

void Hero::operator-=(int attack) {
    if (attack > 0) {
        m_health -= attack;
    }
    if (attack > m_health) {
        m_health = 0;
    }
}

This will sometimes reduce health more than once.

Suppose health is 15 and attack is 10. The first if-statement will reduce the health to 5. The second if-statement will then reduce it again to 0.

To avoid this you can do:

void Hero::operator-=(int attack) {
    if (attack > 0) {
        if (attack > m_health) {
            m_health = 0;
        } else {
            m_health -= attack;
        }
    }
}

This will reduce health to 0 only when the attack is at least as large as the remaining health.


问:
Getting Resource as InputStream in Playframework
I have the following Problem in my Play-Application:
I placed a file called "logfileSearch.properties" in my conf folder. Then i wanted to get a inputStream with mentioned file in it.

```<code>@Inject
Provider<Application> app;

public CustomNodeList newSearch() throws IOException {
    Application application = app.get();
    ClassLoader classLoader = application.classloader();
    InputStream inputStream = classLoader.getResourceAsStream("logfileSearch.properties");
    .....
}
</code>```

With this Code i got a NullPointerException in the line:

```<code>Application application = app.get();
</code>```

If someone here is able to help me i would be very happy.

More Info:

Play version: 2.5.14

Scala version: 2.11.11

答:
you can use current class loader as described in Play documentation<br>
like: </p>

```<code>   this.getClass().getResourceAsStream("logfileSearch.properties");
</code>```

Body:
I have the following Problem in my Play-Application:
I placed a file called "logfileSearch.properties" in my conf folder. Then i wanted to get a inputStream with mentioned file in it.

@Inject
Provider<Application> app;

public CustomNodeList newSearch() throws IOException {
    Application application = app.get();
    ClassLoader classLoader = application.classloader();
    InputStream inputStream = classLoader.getResourceAsStream("logfileSearch.properties");
    .....
}

With this Code i got a NullPointerException in the line:

Application application = app.get();

If someone here is able to help me i would be very happy.

More Info:

Play version: 2.5.14

Scala version: 2.11.11

Body:
you can use current class loader as described in Play documentation

like:

   this.getClass().getResourceAsStream("logfileSearch.properties");


问:
List will not remove items, C#
I have a List (named actors) of "Actors", a custom class to be displayed in a ListBox (named listBoxActors) in C#. The user will be able to click an item to highlight and select it, after which they can press a button that Removes that Actor from the list. Here is my code for the button when it is pressed:

```<code>Actor current = (Actor) listBoxActors.SelectedItem;

actors.Remove(current);

listBoxActors.DataSource = null;
listBoxActors.DataSource = actors;
</code>```

However, even after pressing the button, the Actor still displays in the list box as if it had never been removed at all. Setting the DataSource to null and back to the actors list should refresh it (works fine for that purpose when I add actors), but the list remains the same. What should I add/remove? What am I doing wrong?

答:
You can simply use Remove function:

```<code>listBoxActors.Items.Remove(listBoxActors.SelectedItem);
</code>```

Hope it helps!!

Title: List will not remove items, C#

Body:
I have a List (named actors) of "Actors", a custom class to be displayed in a ListBox (named listBoxActors) in C#. The user will be able to click an item to highlight and select it, after which they can press a button that Removes that Actor from the list. Here is my code for the button when it is pressed:

Actor current = (Actor) listBoxActors.SelectedItem;

actors.Remove(current);

listBoxActors.DataSource = null;
listBoxActors.DataSource = actors;

However, even after pressing the button, the Actor still displays in the list box as if it had never been removed at all. Setting the DataSource to null and back to the actors list should refresh it (works fine for that purpose when I add actors), but the list remains the same. What should I add/remove? What am I doing wrong?

Body:
You can simply use Remove function:

listBoxActors.Items.Remove(listBoxActors.SelectedItem);

Hope it helps!!


问:
Android window doesn't resize/pan when softinput opened from WebView
My problem is following.

Application uses theme android:Theme.NoTitleBar.Fullscreen and there is only one Activity, all other views are Fragment

I have WebView inside ViewPager Fragment which is inside ScrollView

HTML content has input fields

I click input field which is on bottom of WebView

Soft input opens, but the Window is not resized/panned

I've tried setting android:windowSoftInputMode="adjustResize" or android:windowSoftInputMode="adjustPan" in my manifest for the Activity. Also tried setting one of those in java.

Normal EditText inside a ScrollView in my application does adjust pan properly so user can see where he/she is typing.

UPDATE:

If there is no working solution to get window adjust, is there a way to get WebView think it's content is like half screen height more bigger so user could at least scroll the input visible.

答:
Here is what we have done to make it work.
As it is by design, FLAG_FULLSCREEN activity won't allow adjusting the views when a keyboard is visible, we took an approach with custom Keyboard Notification Listener and OnTouch listener of Webview.

KeyboardHelper.java - to find out the keyboard visibility

Webview Full-Screen Activity Adjustment - To adjust the webview based on the notification and touch point.

Hope it helps!


问:
Vim and python: context-unaware autocompletion of language methods
I am writing a little python script to learn VIM basics (I'm a beginner with VIM).
I've configured VIM to work with omnicompletion, and it does.
For example, if I write str. then press ctr+x, ctr+o it suggests me all of the string methods.
However in my code I have something like this:

```<code>for line in inFile.readlines():
    something = line.rpartition(" ")[0]
</code>```

I'd like VIM to autocomplete the rpartition method name after typing line.rpart. I don't expect it to know line object type, but I'd like VIM to propose a context-unaware completion list based on python libraries acquaintance.
For example if with eclipse i try to complete

```<code>anObject.rpart
</code>```

it suggests me the rpartition method even if it has nothing to do with anObject!

Is it possible to get this to work with VIM?

Thanks.

My .vimrc file:

```<code>set showcmd
set textwidth=80
set expandtab
set smarttab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set number
set autoindent
filetype indent on
filetype plugin on
autocmd BufRead,BufNewFile *.py syntax on
autocmd BufRead,BufNewFile *.py set ai
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,with,try,except,finally,def,class
set modeline
syntax on
" Closes the Omni-Completion tip window when a selection is
" made
autocmd CursorMovedI * if pumvisible() == 0|pclose|endif
autocmd InsertLeave * if pumvisible() == 0|pclose|endif
</code>```

答:
You definitely should take a look at PySmell which can be installed for Vim easily. It generates a completion menu based on a static analysis for a given project. It also can generate completion suggestions based on tags it produces for external libraries like the Python Standard Library or Django Lib.

I was happy with Vims Python omnicimpletion, but since I switched to PySmell, I never looked back.

Body:
I am writing a little python script to learn VIM basics (I'm a beginner with VIM).
I've configured VIM to work with omnicompletion, and it does.
For example, if I write str. then press ctr+x, ctr+o it suggests me all of the string methods.
However in my code I have something like this:

for line in inFile.readlines():
    something = line.rpartition(" ")[0]

I'd like VIM to autocomplete the rpartition method name after typing line.rpart. I don't expect it to know line object type, but I'd like VIM to propose a context-unaware completion list based on python libraries acquaintance.
For example if with eclipse i try to complete

anObject.rpart

it suggests me the rpartition method even if it has nothing to do with anObject!

Is it possible to get this to work with VIM?

Thanks.

My .vimrc file:

set showcmd
set textwidth=80
set expandtab
set smarttab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set number
set autoindent
filetype indent on
filetype plugin on
autocmd BufRead,BufNewFile *.py syntax on
autocmd BufRead,BufNewFile *.py set ai
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,with,try,except,finally,def,class
set modeline
syntax on
" Closes the Omni-Completion tip window when a selection is
" made
autocmd CursorMovedI * if pumvisible() == 0|pclose|endif
autocmd InsertLeave * if pumvisible() == 0|pclose|endif


问:
Bluemix Ruby app health check configuration
We have a Sinatra app that is deployed to Bluemix through the Bluemix Ruby service.

However, the app is made unavailable after a while, and we suspect that the Bluemix health check is failing. We can see that there is periodic calls to the root (i.e the / route) from something we think is the Bluemix load balancer. However, our root route is protected with basic authentication.

How can we change the route that the load balancer calls for our application?

Is there any documentation for the health check feature?

答:
This doesn't appear to be possible yet. This recently updated documentation states, under "Staging an application", that:

To validate the app health, Diego supports the same PORT-based checks that were used for DEA. However, Diego is also designed to be able to have more generic options like URL-based health checks, which might be enabled in the future.

It also appears that the old DEA architecture didn't support url health checks either.


问:
How to prevent android SearchView Query toggling while text is typing
I got my view with SearchView component. The problem is every new symbol in the input field toggling Query action, so there are some http request are fire etc, so it starts to working slow.

I want it to run only after I click on search button on virtual keyboard (bellow button ).

Is there any properties for that in SearchView?

layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString" />

</LinearLayout>
</code>```

Or I should make something like custom binding which detects keyboard key click?

UPD:

Some code to make clear part of how search works:

View model

```<code>public class RemoteMusicSearchViewModel : MvxViewModel
    {
        private IMvxNavigationService _mvxNavigationService;
        private IRemoteMusicDataService _remoteMusicDataService;
        private int _currentPage;

        public RemoteMusicSearchViewModel(IMvxNavigationService mvxNavigationService,
            IRemoteMusicDataService remoteMusicDataService)
        {
            _mvxNavigationService = mvxNavigationService;
            _remoteMusicDataService = remoteMusicDataService;
        }

        public override void Start()
        {
            base.Start();

            _currentPage = 0;
        }

        private string _searchString;

        public string SearchString
        {
            get { return _searchString; }

            set
            {
                _searchString = value;
                RaisePropertyChanged(() => SearchString);
                PerformBasicSearch().ConfigureAwait(false);
            }
        }

        private ObservableCollection<DownloadableEntity> _foundItems;

        public ObservableCollection<DownloadableEntity> FoundItems
        {
            get { return _foundItems; }

            set
            {
                if (_currentPage > 0)
                {
                    _foundItems = new ObservableCollection<DownloadableEntity>(_foundItems.Concat(value));
                }
                else
                {
                    _foundItems = value;
                }

                RaisePropertyChanged(() => FoundItems);
            }
        }

        private async Task PerformBasicSearch(int page = 0)
        {
            string request = SearchString;
            string result = await _remoteMusicDataService.SearchByProperty(request, MusicSearchType.ByTracks, page).ConfigureAwait(false);
            var searchResult = MusicSearchResult.FromJson(result);

            await PrepareDataForOutput(searchResult).ConfigureAwait(false);
        }
    }
</code>```

full layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString"
        />

    <MvvmCross.Binding.Droid.Views.MvxListView
        android:id="@+id/searchlist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        local:MvxBind="ItemsSource FoundItems"
        local:MvxItemTemplate="@layout/listitem"/>

</LinearLayout>
</code>```

答:
I found the solution - I just created new binding for that:

```<code>public class SearchViewKeyPressEventsBinding : MvxAndroidTargetBinding
    {
        private readonly SearchView _searchView;
        private IMvxAsyncCommand _command;

        public SearchViewKeyPressEventsBinding(SearchView searchView) : base(searchView)
        {
            _searchView = searchView;
            _searchView.QueryTextSubmit += _searchView_KeyPress;
        }

        private void _searchView_KeyPress(object sender, SearchView.QueryTextSubmitEventArgs e)
        {
            try
            {
                if (_command != null)
                {
                    _command.ExecuteAsync();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public override Type TargetType
        {
            get { return typeof(IMvxAsyncCommand); }
        }

        protected override void SetValueImpl(object target, object value)
        {
            try
            {
                _command = (IMvxAsyncCommand)value;
            }
            catch (Exception e)
            {
                Log.Error("SOME BINDER FAIL\n\t" + e.Message + "\n", "SOME BINDER FAIL\n\t" + e.Message + "\n");
                throw;
            }
        }

        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                _searchView.QueryTextSubmit -= _searchView_KeyPress;
            }
            base.Dispose(isDisposing);
        }
    }
}
</code>```

Then registred it and it worked:

```<code>   registry.RegisterFactory(new MvxCustomBindingFactory<SearchView>("OnSearchSubmit", (sv) => new SearchViewKeyPressEventsBinding(sv)))
</code>```

In layout:

```<code><SearchView
        android:id="@+id/search10"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString; OnSearchSubmit OnSubmitPressCommand" />
</code>```

And don't forget to set up viewmodel's property:

```<code> public IMvxAsyncCommand OnSubmitPressCommand
        {
            get
            {
                return new MvxAsyncCommand(OnSearchSubmit);
            }
        }

  private async Task OnSearchSubmit()
        {
            //HideKeyboardOnSearchStart.Invoke(this, null);
            await PerformBasicSearch().ConfigureAwait(false);
        }
</code>```

Body:
I got my view with SearchView component. The problem is every new symbol in the input field toggling Query action, so there are some http request are fire etc, so it starts to working slow.

I want it to run only after I click on search button on virtual keyboard (bellow button ).

Is there any properties for that in SearchView?

layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString" />

</LinearLayout>

Or I should make something like custom binding which detects keyboard key click?

UPD:

Some code to make clear part of how search works:

View model

public class RemoteMusicSearchViewModel : MvxViewModel
    {
        private IMvxNavigationService _mvxNavigationService;
        private IRemoteMusicDataService _remoteMusicDataService;
        private int _currentPage;

        public RemoteMusicSearchViewModel(IMvxNavigationService mvxNavigationService,
            IRemoteMusicDataService remoteMusicDataService)
        {
            _mvxNavigationService = mvxNavigationService;
            _remoteMusicDataService = remoteMusicDataService;
        }

        public override void Start()
        {
            base.Start();

            _currentPage = 0;
        }

        private string _searchString;

        public string SearchString
        {
            get { return _searchString; }

            set
            {
                _searchString = value;
                RaisePropertyChanged(() => SearchString);
                PerformBasicSearch().ConfigureAwait(false);
            }
        }

        private ObservableCollection<DownloadableEntity> _foundItems;

        public ObservableCollection<DownloadableEntity> FoundItems
        {
            get { return _foundItems; }

            set
            {
                if (_currentPage > 0)
                {
                    _foundItems = new ObservableCollection<DownloadableEntity>(_foundItems.Concat(value));
                }
                else
                {
                    _foundItems = value;
                }

                RaisePropertyChanged(() => FoundItems);
            }
        }

        private async Task PerformBasicSearch(int page = 0)
        {
            string request = SearchString;
            string result = await _remoteMusicDataService.SearchByProperty(request, MusicSearchType.ByTracks, page).ConfigureAwait(false);
            var searchResult = MusicSearchResult.FromJson(result);

            await PrepareDataForOutput(searchResult).ConfigureAwait(false);
        }
    }

full layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString"
        />

    <MvvmCross.Binding.Droid.Views.MvxListView
        android:id="@+id/searchlist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        local:MvxBind="ItemsSource FoundItems"
        local:MvxItemTemplate="@layout/listitem"/>

</LinearLayout>

Body:
I found the solution - I just created new binding for that:

public class SearchViewKeyPressEventsBinding : MvxAndroidTargetBinding
    {
        private readonly SearchView _searchView;
        private IMvxAsyncCommand _command;

        public SearchViewKeyPressEventsBinding(SearchView searchView) : base(searchView)
        {
            _searchView = searchView;
            _searchView.QueryTextSubmit += _searchView_KeyPress;
        }

        private void _searchView_KeyPress(object sender, SearchView.QueryTextSubmitEventArgs e)
        {
            try
            {
                if (_command != null)
                {
                    _command.ExecuteAsync();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public override Type TargetType
        {
            get { return typeof(IMvxAsyncCommand); }
        }

        protected override void SetValueImpl(object target, object value)
        {
            try
            {
                _command = (IMvxAsyncCommand)value;
            }
            catch (Exception e)
            {
                Log.Error("SOME BINDER FAIL\n\t" + e.Message + "\n", "SOME BINDER FAIL\n\t" + e.Message + "\n");
                throw;
            }
        }

        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                _searchView.QueryTextSubmit -= _searchView_KeyPress;
            }
            base.Dispose(isDisposing);
        }
    }
}

Then registred it and it worked:

   registry.RegisterFactory(new MvxCustomBindingFactory<SearchView>("OnSearchSubmit", (sv) => new SearchViewKeyPressEventsBinding(sv)))

In layout:

<SearchView
        android:id="@+id/search10"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString; OnSearchSubmit OnSubmitPressCommand" />

And don't forget to set up viewmodel's property:

 public IMvxAsyncCommand OnSubmitPressCommand
        {
            get
            {
                return new MvxAsyncCommand(OnSearchSubmit);
            }
        }

  private async Task OnSearchSubmit()
        {
            //HideKeyboardOnSearchStart.Invoke(this, null);
            await PerformBasicSearch().ConfigureAwait(false);
        }