问:
Large text is going back of Imageview

```<code> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>
</code>```

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but

答:
I think you should use a horizontal oriented linearlayout
and set weight for your textview to fill the parent:</p>

```<code><LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />
       <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</LinearLayout>
</code>```

Title: Large text is going back of Imageview

Body:
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but

Body:
I think you should use a horizontal oriented linearlayout
and set weight for your textview to fill the parent:

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />
       <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</LinearLayout>


来源: stackexchange

问:
Memoization of member function of Kotlin data class
In the following Kotlin example, I'd like to "memoize" (cache the result of) the member function matches:

```<code>import java.util.regex.Pattern

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    //TODO memoize this
    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }
}

fun main(args: Array<String>) {
    val myData = MyDataClass()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}
</code>```

As far as I can see, Kotlin <= 1.1 doesn't support memoization. Of course, you can write your own memoization function or use a library like e.g. https://github.com/MarioAriasC/funKTionale

Using funKTionale, I don't have to write my own memoization function and came to this solution. Unfortunately it looks "boilerplatey":

```<code>import org.funktionale.memoization.memoize
import java.util.regex.Pattern

data class MyMemoizedDataClassV1(val name: String = "John Doe",
                                 val description: String = "Famous person") {

    private val memoizedMatches: (String, String, String) -> Boolean =
            { name: String, description: String, searchTerm: String ->
                println("Calculating...")
                name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                        || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
            }.memoize()

    fun matches(searchTerm: String): Boolean {
        return memoizedMatches(name, description, searchTerm)
    }
}

fun main(args: Array<String>) {
    val myData = MyMemoizedDataClassV1()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}
</code>```

I think of a nicer looking solution like

```<code>data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }.memoize() //TODO how?
}
</code>```

But, how to achieve this?

答:
a and b are val, so you can assign the result to a val

```<code>data class MyDataClass(val a: Int = 1,
                       val b: Int = 2) {
    val sum = a + b
}
</code>```

If the calculation is expensive, you can use lazy to delay calculation.

```<code>data class MyDataClass(val a: Int = 1,
                        val b: Int = 2) {
    val sum: Int by lazy {
        a + b
    }
}
</code>```

Edit: New answer for edited question

```<code>interface StringMatchable {
    fun matches(searchTerm: String): Boolean
}

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") : StringMatchable by
CacheStringMatchable({
    searchTerm ->
    name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
            || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
})

class CacheStringMatchable(private val function: (String) -> Boolean) : StringMatchable {
    private val map: MutableMap<String, Boolean> = mutableMapOf()
    override fun matches(searchTerm: String): Boolean {
        return map.computeIfAbsent(searchTerm, function)
    }
}
</code>```

To delegate a method, it is only possible by interface currently. So, it probably cannot be written in generic way (i.e. 1 cache class for all).

Edit2: If this is the only class need matches(), then here is a simpler answer

```<code>data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {
    private val map: MutableMap<String, Boolean> = mutableMapOf()
    fun matches(searchTerm: String): Boolean {
        return map.computeIfAbsent(searchTerm, {
            searchTerm ->
            name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                    || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
        })
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In the following Kotlin example, I'd like to "memoize" (cache the result of) the member function matches:

import java.util.regex.Pattern

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    //TODO memoize this
    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }
}

fun main(args: Array<String>) {
    val myData = MyDataClass()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}

As far as I can see, Kotlin <= 1.1 doesn't support memoization. Of course, you can write your own memoization function or use a library like e.g. https://github.com/MarioAriasC/funKTionale

Using funKTionale, I don't have to write my own memoization function and came to this solution. Unfortunately it looks "boilerplatey":

import org.funktionale.memoization.memoize
import java.util.regex.Pattern

data class MyMemoizedDataClassV1(val name: String = "John Doe",
                                 val description: String = "Famous person") {

    private val memoizedMatches: (String, String, String) -> Boolean =
            { name: String, description: String, searchTerm: String ->
                println("Calculating...")
                name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                        || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
            }.memoize()

    fun matches(searchTerm: String): Boolean {
        return memoizedMatches(name, description, searchTerm)
    }
}

fun main(args: Array<String>) {
    val myData = MyMemoizedDataClassV1()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}

I think of a nicer looking solution like

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }.memoize() //TODO how?
}

But, how to achieve this?

Body:
a and b are val, so you can assign the result to a val

data class MyDataClass(val a: Int = 1,
                       val b: Int = 2) {
    val sum = a + b
}

If the calculation is expensive, you can use lazy to delay calculation.

data class MyDataClass(val a: Int = 1,
                        val b: Int = 2) {
    val sum: Int by lazy {
        a + b
    }
}

Edit: New answer for edited question

interface StringMatchable {
    fun matches(searchTerm: String): Boolean
}

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") : StringMatchable by
CacheStringMatchable({
    searchTerm ->
    name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
            || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
})

class CacheStringMatchable(private val function: (String) -> Boolean) : StringMatchable {
    private val map: MutableMap<String, Boolean> = mutableMapOf()
    override fun matches(searchTerm: String): Boolean {
        return map.computeIfAbsent(searchTerm, function)
    }
}

To delegate a method, it is only possible by interface currently. So, it probably cannot be written in generic way (i.e. 1 cache class for all).

Edit2: If this is the only class need matches(), then here is a simpler answer

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {
    private val map: MutableMap<String, Boolean> = mutableMapOf()
    fun matches(searchTerm: String): Boolean {
        return map.computeIfAbsent(searchTerm, {
            searchTerm ->
            name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                    || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
        })
    }
}


问:
Disable keyboard individual letters pop-up
Does anybody know how to programmatically disable the keyboard individual letter pop-up?

(This blue pop-up when you click in a letter on the virtual keyboard of the device.)

答: In your phone, go to Settings --> Language and Input --> Select the keyboard type that you are using. (In my case it says Samsung keyboard). Select the settings icon next to it. There is an option called "Character preview". Disable it.</p>


问:
VSCode Private Extension Repository for teams
I'm writing highly specific private VSCode extensions for our dev team. I will be making constant changes to these extensions. From what I've read, the only way is to compile the extension as a .vsix file and send this file to each of the team.

This workflow is tedious and feels unnecessary.

I am looking for a more automatic and transparent solution, which more or less updates the private extension automatically.

Has this scenario been solved?

答: Not as of VSCode 1.14 but we are tracking the feature request here: https://github.com/Microsoft/vscode/issues/21839</p>


问:
How to push the json(object) to array in local storage angular js?
I am trying to do use the angular push function but it is not working.

i am storing form values into local storage every time it will be replacing the old object with new object...

I want to add strings (or objects) into an array.

Below is my HTML code:

```<code><form name="myForm" novalidate>
    <p> Username:<br>
        <input type="text" name="user" ng-model="user.user" required>
        <span ng-show="myForm.user.$pristine"/>
    </p>
        <p>Email:<br>
            <input type="email" name="email" ng-model="user.email" required>
            <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
                <span ng-show="myForm.email.$error.required">Email is required.</span>
                <span ng-show="myForm.email.$error.email">Invalid email address.</span>
            </span>
        </p>

            <p> PhoneNum:<br>
                <input type="number" name="PhoneNum" ng-model="user.PhoneNum" required>
                <span ng-show="myForm.PhoneNum.$pristine"></span>
            </p>
                <p>Address:<br>
                    <input type="text" name="address" ng-model="user.address" required>
                    <span ng-show="myForm.address.$pristine"></span>
                </p>
                    <p>Password:<br>
                        <input type="Password" name="pass" ng-model="user.pass" required>
                        <span ng-show="myForm.pass.$pristine"  />
                    </p>
                        <p>
                            <input type="submit" ng-click="addItem(user)" ng-disabled="myForm.$invalid">
                        </p>

</form>
```user = {{user | json}}```
<table>
{{userdata}}
    <tr>
        <td>user</td>
        <td>Email</td>
        <td>Phone</td>
        <td>Address</td>
        <td>Password</td>
    </tr>
    <tr ng-repeat="x in userArray">
        <td>{{x.user}}</td>
        <td>{{x.email}}</td>
        <td>{{x.PhoneNum}}</td>
        <td>{{x.address}}</td>
        <td>{{x.pass}}</td>
    </tr>
</table>
</code>```

Below is my js code:

```<code>var app = angular.module("myApp", ['ngRoute','ngStorage']);
app.controller("userCtrl",['$scope','$localStorage','$log',function($scope,$localStorage,$log){
    $scope.userArray=[];
    $scope.userdata=$localStorage.data;

    $scope.addItem=function(user){
        //var current=$localStorage.data;
        //$scope.userArray=userArray.concat(user);
        $log.log($scope.userArray);
        $scope.userArray.push(user);
        $localStorage.data=$scope.userArray;
        $scope.userdata=$localStorage.data;
    }

}]);
</code>```

答:
```<code>$scope.userArray = [];
    $scope.userdata = $localStorage.data;

    $scope.addItem = function(user) {
      $scope.userArray.push(user);
      $scope.user = {};
      $localStorage.data = $scope.userArray;
      $scope.userdata = $localStorage.data;
    }
</code>```

Body:
I am trying to do use the angular push function but it is not working.

i am storing form values into local storage every time it will be replacing the old object with new object...

I want to add strings (or objects) into an array.

Below is my HTML code:

<form name="myForm" novalidate>

 Username:

        <input type="text" name="user" ng-model="user.user" required>

Email:

            <input type="email" name="email" ng-model="user.email" required>

                Email is required.
                Invalid email address.

 PhoneNum:

                <input type="number" name="PhoneNum" ng-model="user.PhoneNum" required>

Address:

                    <input type="text" name="address" ng-model="user.address" required>

Password:

                        <input type="Password" name="pass" ng-model="user.pass" required>

                            <input type="submit" ng-click="addItem(user)" ng-disabled="myForm.$invalid">

</form>

user = {{user | json}}

{{userdata}}

        user
        Email
        Phone
        Address
        Password

        {{x.user}}
        {{x.email}}
        {{x.PhoneNum}}
        {{x.address}}
        {{x.pass}}

Below is my js code:

var app = angular.module("myApp", ['ngRoute','ngStorage']);
app.controller("userCtrl",['$scope','$localStorage','$log',function($scope,$localStorage,$log){
    $scope.userArray=[];
    $scope.userdata=$localStorage.data;

    $scope.addItem=function(user){
        //var current=$localStorage.data;
        //$scope.userArray=userArray.concat(user);
        $log.log($scope.userArray);
        $scope.userArray.push(user);
        $localStorage.data=$scope.userArray;
        $scope.userdata=$localStorage.data;
    }

}]);


问:
Unit Testing: How to verify and mock onCompleted for an Observable in RxJava within Android
I am trying to write some unit tests for an Android application that is using Retrofit 2, Mockito 1.10 and RXJava 1.0. I am not using a java version that supports lambdas!

My code uses Observables and I can do the following:

```<code>when(myAPI.Complete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.<GenericResponse>error(new Throwable("An error has occurred!")));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onError(any(Throwable.class));
</code>```

The above code works fine and allows me to throw an error and capture it within the test.

What I need to be able to do as well (of course) :) is to capture positive conditions. I feel like it's obvious but can't find the answer I need.

How can I capture onComplete and onNext cases ?

I know that the verification for onComplete would be...

verify(genericResponseSubscriber, times(1)).onCompleted();

But I can't see what my 'when' clause should be. I tried the following but that fails:

```<code>GenericResponse response = new GenericResponse();
response.setSuccess(true);

when(myAPI.orderComplete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.just(response));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onCompleted();
</code>```

The failure here is that subscriber.onStart() was instead called.

So, what I would like to know is, how I can mock and verify the 'onComplete' and 'onNext' calls, please and more importantly what I should have looked to be able to have resolved this myself rather than having to ask! :)

As always, any help is appreciated.

Edit..

My onError working test case..

```<code>    public void UseCaseOnError() throws Exception {

     String id = "5";

     order Order = new Order();

     SomeContainer myContainer = new SomeContainer(order);

     when(myRetroFitAPI.complete(anyString(), any(SomeContainer.class)))
</code>```

.thenReturn(Observable.error(new Throwable(“My error!")));

```<code>     Subscriber genericResponseSubscriber = mock(Subscriber.class);

     orderPresenter.doUseCase(id, myContainer, genericResponseSubscriber);

     verify(genericResponseSubscriber,times(1)).onError(any(Throwable.class));

}
</code>```

What I should really add is that, I feel there should be an equivalent for onError in terms of a positive state, i.e. onCompleted. If I do the same but with onCompleted instead, my verification fails as it detects onStart has been called instead which I am finding rather confusing.

I have tried using the ReplaySubject as such:

```<code>public void createOrderOnCompleteError() {
    orderOnCompleteSubject.onError(new Throwable("I am an error"));
}

public void createOrderOnCompleteSuccess() {
    orderOnCompleteSubject.onNext(new GenericResponse().setSuccess(true));
    orderOnCompleteSubject.onCompleted();
}
</code>```

The error mechanism works fine.. the completed mechanism does not...

答:
Instead of mocking the Subscriber, you should create a TestSubscriber for RxJava 1:

```<code>when(myAPI.Complete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.<GenericResponse>error(new Throwable("An error has occurred!")));

TestSubscriber genericResponseSubscriber = TestSubscriber.create();

myPresenter.myUseCase(id, container, genericResponseSubscriber);

// To check for an error
genericResponseSubscriber.assertError(Throwable.class)

// To check for completion
genericResponseSubscriber.assertCompleted()
</code>```

You might need to be a bit more specific about which error class you expect. Check out the TestSubscriber documention. There is tons of more stuff you can verify with this class.

Happy testing!

Body:
I am trying to write some unit tests for an Android application that is using Retrofit 2, Mockito 1.10 and RXJava 1.0. I am not using a java version that supports lambdas!

My code uses Observables and I can do the following:

when(myAPI.Complete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.<GenericResponse>error(new Throwable("An error has occurred!")));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onError(any(Throwable.class));

The above code works fine and allows me to throw an error and capture it within the test.

What I need to be able to do as well (of course) :) is to capture positive conditions. I feel like it's obvious but can't find the answer I need.

How can I capture onComplete and onNext cases ?

I know that the verification for onComplete would be...

verify(genericResponseSubscriber, times(1)).onCompleted();

But I can't see what my 'when' clause should be. I tried the following but that fails:

GenericResponse response = new GenericResponse();
response.setSuccess(true);

when(myAPI.orderComplete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.just(response));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onCompleted();

The failure here is that subscriber.onStart() was instead called.

So, what I would like to know is, how I can mock and verify the 'onComplete' and 'onNext' calls, please and more importantly what I should have looked to be able to have resolved this myself rather than having to ask! :)

As always, any help is appreciated.

Edit..

My onError working test case..

    public void UseCaseOnError() throws Exception {

     String id = "5";

     order Order = new Order();

     SomeContainer myContainer = new SomeContainer(order);

     when(myRetroFitAPI.complete(anyString(), any(SomeContainer.class)))

.thenReturn(Observable.error(new Throwable(“My error!")));

     Subscriber genericResponseSubscriber = mock(Subscriber.class);

     orderPresenter.doUseCase(id, myContainer, genericResponseSubscriber);

     verify(genericResponseSubscriber,times(1)).onError(any(Throwable.class));

}

What I should really add is that, I feel there should be an equivalent for onError in terms of a positive state, i.e. onCompleted. If I do the same but with onCompleted instead, my verification fails as it detects onStart has been called instead which I am finding rather confusing.

I have tried using the ReplaySubject as such:

public void createOrderOnCompleteError() {
    orderOnCompleteSubject.onError(new Throwable("I am an error"));
}

public void createOrderOnCompleteSuccess() {
    orderOnCompleteSubject.onNext(new GenericResponse().setSuccess(true));
    orderOnCompleteSubject.onCompleted();
}

The error mechanism works fine.. the completed mechanism does not...

Body:
Instead of mocking the Subscriber, you should create a TestSubscriber for RxJava 1:

when(myAPI.Complete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.<GenericResponse>error(new Throwable("An error has occurred!")));

TestSubscriber genericResponseSubscriber = TestSubscriber.create();

myPresenter.myUseCase(id, container, genericResponseSubscriber);

// To check for an error
genericResponseSubscriber.assertError(Throwable.class)

// To check for completion
genericResponseSubscriber.assertCompleted()

You might need to be a bit more specific about which error class you expect. Check out the TestSubscriber documention. There is tons of more stuff you can verify with this class.

Happy testing!


问:
Unable to start eclipse workspace by "Reload maven Project" Error
I Closed eclipse unfortunately when create and updating maven dependencies so after that unable to start the eclipse workspace and getting "Unable to load Maven Project" error

i could see below error log

```<code> !ENTRY org.eclipse.core.jobs 4 2 2016-03-06 00:18:32.977
 !MESSAGE An internal error occurred during: "reload maven project".
 !STACK 0
 java.lang.NullPointerException
  at       org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.configureExecutionRequest(ProjectRegistryManager.java:864)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.createExecutionContext(ProjectRegistryManager.java:962)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.execute(ProjectRegistryManager.java:956)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.readProjectWithDependencies(ProjectRegistryManager.java:811)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.create(ProjectRegistryManager.java:191)
at org.eclipse.m2e.core.internal.project.registry.MavenProjectManager.create(MavenProjectManager.java:80)
at org.eclipse.m2e.core.ui.internal.actions.SelectionUtil.getMavenProject(SelectionUtil.java:259)
at org.eclipse.m2e.editor.pom.MavenPomEditor.readMavenProject(MavenPomEditor.java:729)
at org.eclipse.m2e.editor.pom.MavenPomEditor$5.run(MavenPomEditor.java:1050)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
</code>```

Anyone help me to resolve this issue.

答: Delete .metadata folder under your workspace.</p>

Body:
I Closed eclipse unfortunately when create and updating maven dependencies so after that unable to start the eclipse workspace and getting "Unable to load Maven Project" error

i could see below error log

 !ENTRY org.eclipse.core.jobs 4 2 2016-03-06 00:18:32.977
 !MESSAGE An internal error occurred during: "reload maven project".
 !STACK 0
 java.lang.NullPointerException
  at       org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.configureExecutionRequest(ProjectRegistryManager.java:864)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.createExecutionContext(ProjectRegistryManager.java:962)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.execute(ProjectRegistryManager.java:956)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.readProjectWithDependencies(ProjectRegistryManager.java:811)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.create(ProjectRegistryManager.java:191)
at org.eclipse.m2e.core.internal.project.registry.MavenProjectManager.create(MavenProjectManager.java:80)
at org.eclipse.m2e.core.ui.internal.actions.SelectionUtil.getMavenProject(SelectionUtil.java:259)
at org.eclipse.m2e.editor.pom.MavenPomEditor.readMavenProject(MavenPomEditor.java:729)
at org.eclipse.m2e.editor.pom.MavenPomEditor$5.run(MavenPomEditor.java:1050)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

Anyone help me to resolve this issue.


问:
best practices for hibernate 3.6 and spring 3?
any good examples of integrating the latest versions of hibernate and spring? template pros and cons?</p>

答:
Are you looking more documentation than the one provided here from spring reference?

Here are the pros and cons of using a hibernate template: Spring hibernate template when to use and why?

ContentLicense: CC BY-SA 2.5


问:
echo with ajax does't work
I was following an tutorial, and i finish with this code:

```<code><script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
    $(function($){
      $("#compila").click(function(){
          var code = $(#codigo).html();

          $.post("myajax.php",{code:code},function(return){
            $(#result).html("<b>print </b>"+return);
          });
      });
    });

</script>

<?php
      $code = $_POST["code"];
      echo $code;

 ?>
</code>```

but this code doesn't work. I was using a text area, and i'm trying to send a string of the text area to a
 tag, and print with echo of the php. How i can fix this code?

答:
You're missing quotes around some of your identifiers:

```<code>var code = $(#codigo).html();
</code>```

should be

```<code>var code = $("#codigo").html();
</code>```

and

```<code>$(#result).html("<b>print </b>"+return);
</code>```

should be

```<code>$("#result").html("<b>print </b>"+return);
</code>```

If you use the developer console in your browser (F12 and go to the console tab) it should then tell you about these errors and give you the line number of where the errors occur.

As userr1T77 mentioned in his answer, you need to change the variable name from return to something else. return is a reserved keyword so can't be used as a variable, so your code should be something similar to

```<code>$.post("myajax.php",{code:code},function(return_data){
    $("#result").html("<b>print </b>"+return_data);
});
</code>```

Title: echo with ajax does't work

Body:
I was following an tutorial, and i finish with this code:

<?php
      $code = $_POST["code"];
      echo $code;

 ?>

but this code doesn't work. I was using a text area, and i'm trying to send a string of the text area to a
 tag, and print with echo of the php. How i can fix this code?

Body:
You're missing quotes around some of your identifiers:

var code = $(#codigo).html();

should be

var code = $("#codigo").html();

and

$(#result).html("<b>print </b>"+return);

should be

$("#result").html("<b>print </b>"+return);

If you use the developer console in your browser (F12 and go to the console tab) it should then tell you about these errors and give you the line number of where the errors occur.

As userr1T77 mentioned in his answer, you need to change the variable name from return to something else. return is a reserved keyword so can't be used as a variable, so your code should be something similar to

$.post("myajax.php",{code:code},function(return_data){
    $("#result").html("<b>print </b>"+return_data);
});


问:
How to reset the current axes to display either color or grayscale image on the same axes in MATLAB?
I have some grayscale images, which after some segmentation I converted a section to color for display purposes.
But I cannot display a color image on the axes after I display a grayscale image on the same axes.

Ex:

```<code>function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global imB
global imF
global finalSegment_LE
i=38;
%         imB = img2{i} ;% Background original image
tempSeg = finalSegment_LE{i};
tempSeg(finalSegment_LE{i} ==0) = min(finalSegment_LE{i}(:));
imF = tempSeg;
cla(handles.axes1,'reset');
[~,~] = imoverlay(imB,imF,[],[],'hsv',0.8,handles.axes1); % color image..

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% global imB
temp = imread('cameraman.tif');
cla(handles.axes1,'reset');
axes(handles.axes1);
imshow(temp,[]) % grayscale image...
</code>```

If I press pushbutton1 first I see a color image, but after I press pushbutton2, the axes become grayscale and even when I press the pushbutton1, It still displays a grayscale image instead of the color image.

Thanks,

Gopi

答:
% set colormap before displaying based on image type</p>

```<code>% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[img,cmap] = imread('peppers.png');
cla(handles.axes1,'reset');
colormap(handles.axes1,cmap);
axes(handles.axes1);
imshow(img,[]);

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% global imB
temp = imread('cameraman.tif');
cla(handles.axes1,'reset');
colormap(handles.axes1,gray);
axes(handles.axes1);
imshow(temp,[])
</code>```

Body:
I have some grayscale images, which after some segmentation I converted a section to color for display purposes.
But I cannot display a color image on the axes after I display a grayscale image on the same axes.

Ex:

function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global imB
global imF
global finalSegment_LE
i=38;
%         imB = img2{i} ;% Background original image
tempSeg = finalSegment_LE{i};
tempSeg(finalSegment_LE{i} ==0) = min(finalSegment_LE{i}(:));
imF = tempSeg;
cla(handles.axes1,'reset');
[~,~] = imoverlay(imB,imF,[],[],'hsv',0.8,handles.axes1); % color image..

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% global imB
temp = imread('cameraman.tif');
cla(handles.axes1,'reset');
axes(handles.axes1);
imshow(temp,[]) % grayscale image...

If I press pushbutton1 first I see a color image, but after I press pushbutton2, the axes become grayscale and even when I press the pushbutton1, It still displays a grayscale image instead of the color image.

Thanks,

Gopi

Body:
% set colormap before displaying based on image type

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[img,cmap] = imread('peppers.png');
cla(handles.axes1,'reset');
colormap(handles.axes1,cmap);
axes(handles.axes1);
imshow(img,[]);

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% global imB
temp = imread('cameraman.tif');
cla(handles.axes1,'reset');
colormap(handles.axes1,gray);
axes(handles.axes1);
imshow(temp,[])


问:
What's the most readable way to write nested functions in javascript?
Example this code I wrote doesn't seem as readable as it could be:</p>

```<code>function getShortMessages(messages) {
    return messages.filter((messages) => {
        return messages.message.length < 50
    }).map((object) => {
        return object.message
    })
}
</code>```

答:
function getShortMessages(messages) {
  return messages.filter(message => message.message.length < 50)
    .map(message => message.message)
}```

Body:
Example this code I wrote doesn't seem as readable as it could be:

function getShortMessages(messages) {
    return messages.filter((messages) => {
        return messages.message.length < 50
    }).map((object) => {
        return object.message
    })
}


问:
Trigger to log inserted/updated/deleted values SQL Server 2016
The application adds/updates/deletes rows to table X. Sample below.

```<code>|ID|Type*|Name |Value|Description
|1 |1    |Mike |100  |-
|2 |1    |John |50   |-
|3 |1    |Vince|10   |-
</code>```

*Column Type = 1 - this is data from application

Column Type = 2 - this will be log data

I need trigger to log inserted/updated/deleted values also in a table X.

For example when change in application row number 2 and 3:

```<code>|ID|Type|Name  |Value|Description
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
</code>```

The result on table X should be like this:

```<code>|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION
</code>```

When the application adds another row:

```<code>|ID|Type|Name  |Value|Description
|6 |1   |Paul  |200  |-
</code>```

The result on table X should be like this:

```<code>|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION
|6 |1   |Paul  |200  |-
|7 |2   |Paul  |200  |INSERT OPERATION
</code>```

...

答:
I think the most straightforward way to do this is via instead of triggers, and to use separate triggers for each operation. I think that these are correct:

```<code>create table X(ID int not null,Type int not null, Name varchar(11) not null,
               Value int not null, Description varchar(38) not null);
insert into X(ID,Type,Name,Value,Description) values
(1,1,'Mike' ,100,'-'),
(2,1,'John' ,50 ,'-'),
(3,1,'Vince',10 ,'-');
go
create table Numbers (n int not null);
insert into Numbers(n) values (1),(2),(3); --TODO - May need more in future
go
create trigger T_X_I on X instead of insert
as
    set nocount on;
    insert into X(ID,Type,Name,Value,Description)
    select i.ID,n.n,i.Name,i.Value,
       CASE WHEN n.n = 1 THEN i.Description ELSE 'INSERT' END
    from inserted i
        cross join
        Numbers n
    where n.n in (1,2);
go
create trigger T_X_U on X instead of update
as
    set nocount on;
    merge into X
    using (select * from inserted i cross join Numbers n where n.n in (1,2)) s
    on
        s.ID = X.ID and
        s.n = 1 and
        X.Type = 1
    when matched then update
       set Name = s.Name,Value = s.Value,Description = s.Description
    when not matched then
       insert (ID,Type,Name,Value,Description) values
              (s.ID,s.n,s.Name,s.Value,'UPDATE');
go
create trigger T_X_D on X instead of delete
as
    set nocount on;
    merge into X
    using (select * from deleted d cross join Numbers n where n.n in (1,2)) s
    on
        s.ID = X.ID and
        s.n = 1 and
        X.Type = 1
    when matched then delete
    when not matched then
      insert (ID,Type,Name,Value,Description) values
             (s.ID,s.n,s.Name,s.Value,'DELETE');
go
update X set
    Name = CASE WHEN ID=2 THEN 'Monica' ELSE 'Tom' END,
    Value = CASE WHEN ID=2 THEN 60 ELSE 5 END
where ID in (2,3)
go
insert into X (ID,Type,Name,Value,Description)
values (6,1,'Paul',200,'-')
go
select * from X
</code>```

Results:

```<code>ID          Type        Name        Value       Description
----------- ----------- ----------- ----------- --------------------------------------
1           1           Mike        100         -
2           1           Monica      60          -
3           1           Tom         5           -
2           2           Monica      60          UPDATE
3           2           Tom         5           UPDATE
6           1           Paul        200         -
6           2           Paul        200         INSERT
</code>```

If you already have a Numbers table or equivalent, feel free to replace that in the above queries.

Body:
The application adds/updates/deletes rows to table X. Sample below.

|ID|Type*|Name |Value|Description
|1 |1    |Mike |100  |-
|2 |1    |John |50   |-
|3 |1    |Vince|10   |-

*Column Type = 1 - this is data from application

Column Type = 2 - this will be log data

I need trigger to log inserted/updated/deleted values also in a table X.

For example when change in application row number 2 and 3:

|ID|Type|Name  |Value|Description
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-

The result on table X should be like this:

|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION

When the application adds another row:

|ID|Type|Name  |Value|Description
|6 |1   |Paul  |200  |-

The result on table X should be like this:

|ID|Type|Name  |Value|Description
|1 |1   |Mike  |100  |-
|2 |1   |Monica|60   |-
|3 |1   |Tom   |5    |-
|4 |2   |Monica|60   |UPDATE OPERATION
|5 |2   |Tom   |5    |UPDATE OPERATION
|6 |1   |Paul  |200  |-
|7 |2   |Paul  |200  |INSERT OPERATION

...

Body:
I think the most straightforward way to do this is via instead of triggers, and to use separate triggers for each operation. I think that these are correct:

create table X(ID int not null,Type int not null, Name varchar(11) not null,
               Value int not null, Description varchar(38) not null);
insert into X(ID,Type,Name,Value,Description) values
(1,1,'Mike' ,100,'-'),
(2,1,'John' ,50 ,'-'),
(3,1,'Vince',10 ,'-');
go
create table Numbers (n int not null);
insert into Numbers(n) values (1),(2),(3); --TODO - May need more in future
go
create trigger T_X_I on X instead of insert
as
    set nocount on;
    insert into X(ID,Type,Name,Value,Description)
    select i.ID,n.n,i.Name,i.Value,
       CASE WHEN n.n = 1 THEN i.Description ELSE 'INSERT' END
    from inserted i
        cross join
        Numbers n
    where n.n in (1,2);
go
create trigger T_X_U on X instead of update
as
    set nocount on;
    merge into X
    using (select * from inserted i cross join Numbers n where n.n in (1,2)) s
    on
        s.ID = X.ID and
        s.n = 1 and
        X.Type = 1
    when matched then update
       set Name = s.Name,Value = s.Value,Description = s.Description
    when not matched then
       insert (ID,Type,Name,Value,Description) values
              (s.ID,s.n,s.Name,s.Value,'UPDATE');
go
create trigger T_X_D on X instead of delete
as
    set nocount on;
    merge into X
    using (select * from deleted d cross join Numbers n where n.n in (1,2)) s
    on
        s.ID = X.ID and
        s.n = 1 and
        X.Type = 1
    when matched then delete
    when not matched then
      insert (ID,Type,Name,Value,Description) values
             (s.ID,s.n,s.Name,s.Value,'DELETE');
go
update X set
    Name = CASE WHEN ID=2 THEN 'Monica' ELSE 'Tom' END,
    Value = CASE WHEN ID=2 THEN 60 ELSE 5 END
where ID in (2,3)
go
insert into X (ID,Type,Name,Value,Description)
values (6,1,'Paul',200,'-')
go
select * from X

Results:

ID          Type        Name        Value       Description
----------- ----------- ----------- ----------- --------------------------------------
1           1           Mike        100         -
2           1           Monica      60          -
3           1           Tom         5           -
2           2           Monica      60          UPDATE
3           2           Tom         5           UPDATE
6           1           Paul        200         -
6           2           Paul        200         INSERT

If you already have a Numbers table or equivalent, feel free to replace that in the above queries.


问:
Java - print sequence of numbers using two threads with inter thread communication
I want to print number in the below format. This should be taken care by two thread t1,t2. Can anyone help to enhance the below code which I have written?

```<code>First t1 should print 0-4
Then t2 should print 5-9
Then again t1 should print 10-14
Then t2 should print 15-19
</code>```

0
1
2
3
4

5
6
7
8
9

10
11
12
13
14

```<code>class PrintNumber implements Runnable{
    String name;

    public void run(){
            print();
    }

    synchronized public void print(){
            for(int i=0;i< 5;i++){
                System.out.println(i+" -- "+Thread.currentThread());
            }
    }

    public static void main(String[] args){
        Runnable r = new PrintNumber();
        Thread t1 = new Thread(r,"t1");
        Thread t2 = new Thread(r,"t2");
        t1.start();
        t2.start();
    }
}
</code>```

答:
Instead of using the low-level wait() and notify() you can use two Sempaphores.
Each Runnable has a Semaphore it waits for and one it uses to notify the next one.

```<code>import java.util.concurrent.Semaphore;

class PrintNumber implements Runnable{

    static volatile int nextStartIdx;

    private Semaphore waitForSemaphore;

    private Semaphore next;

    public PrintNumber(Semaphore waitFor, Semaphore next) {
        this.waitForSemaphore = waitFor;
        this.next = next;
    }

    public void run(){
        while (true) {
            print();
        }

    }

    public void print() {
        try {
            waitForSemaphore.acquire();
            int start = nextStartIdx;

            for(int i=0;i< 5;i++){
                System.out.println(String.format("%d -- %s", i + start, Thread.currentThread().getName()));
            }

            nextStartIdx += 5;
            next.release();

        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args){

        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(0);
        Thread t1 = new Thread(new PrintNumber(a,b),"t1");
        Thread t2 = new Thread(new PrintNumber(b,a),"t2");
        t1.start();
        t2.start();
    }
}
</code>```

Body:
I want to print number in the below format. This should be taken care by two thread t1,t2. Can anyone help to enhance the below code which I have written?

First t1 should print 0-4
Then t2 should print 5-9
Then again t1 should print 10-14
Then t2 should print 15-19

0
1
2
3
4

5
6
7
8
9

10
11
12
13
14

class PrintNumber implements Runnable{
    String name;

    public void run(){
            print();
    }

    synchronized public void print(){
            for(int i=0;i< 5;i++){
                System.out.println(i+" -- "+Thread.currentThread());
            }
    }

    public static void main(String[] args){
        Runnable r = new PrintNumber();
        Thread t1 = new Thread(r,"t1");
        Thread t2 = new Thread(r,"t2");
        t1.start();
        t2.start();
    }
}

Body:
Instead of using the low-level wait() and notify() you can use two Sempaphores.
Each Runnable has a Semaphore it waits for and one it uses to notify the next one.

import java.util.concurrent.Semaphore;

class PrintNumber implements Runnable{

    static volatile int nextStartIdx;

    private Semaphore waitForSemaphore;

    private Semaphore next;

    public PrintNumber(Semaphore waitFor, Semaphore next) {
        this.waitForSemaphore = waitFor;
        this.next = next;
    }

    public void run(){
        while (true) {
            print();
        }

    }

    public void print() {
        try {
            waitForSemaphore.acquire();
            int start = nextStartIdx;

            for(int i=0;i< 5;i++){
                System.out.println(String.format("%d -- %s", i + start, Thread.currentThread().getName()));
            }

            nextStartIdx += 5;
            next.release();

        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args){

        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(0);
        Thread t1 = new Thread(new PrintNumber(a,b),"t1");
        Thread t2 = new Thread(new PrintNumber(b,a),"t2");
        t1.start();
        t2.start();
    }
}


问:
'didSelectRowAt' is not being called
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

```<code>class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}
</code>```

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?

答: I dont know what others solutions you tried, but if you are using a custom viewcell , it might be that you didint enable "User Interaction Enabled" on that component.

Title: 'didSelectRowAt' is not being called

Body:
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?


问:
how to stop a quickfix-initiator
I am running a fix-initiator application, coded in c++ on Solaris X86 platform.
To start and stop the application on a regular base I use a shell-script wrapper and cron which, for stop, does a kill on the pid of the application.
I wonder whether there is a more elegant and "professional" way to stop the innitiator, because kill immediately shuts down the complete process without any proper logout on the fix-sessions, disconnects on the sockets, deleting file-handles, etc..

Can you please advice or give an example on how to handle the SIGINT inside the fix-application?

答:
Have a look at sigaction, this is what you actually need. An example how to use you find here - sure, C, but applicable in C++ as well...

If you discover signal being easier to handle (truth...): Well, avoid it (see the link...).

Be aware that kill by default sends SIGTERM, so this is what you actually should catch...

Be aware, too, that from with signal handlers, you only are allowed to use async-safe functions! A list of is contained at here

I assume your programme is running within some loop. To avoid problems with non-async-safe functions, you might consider just resetting a loop condition in the signal handler and let the rest handle the main thread again (breaking from the loop and cleaning up afterwards).

If you rely on blocking IO, though, you might introduce a call to select or poll (if not yet done so anyway), checking the IO handles especially before read. You might add an additional file descriptor you activate from the signal handler then to be able to break select/poll prematurely.

Such an additional file handler you can get with eventfd, which is, however, linux specific, or in a more portable way by opening a pipe and writing to it from within the signal handler.

Title: how to stop a quickfix-initiator


问:
Creating a folder with today's date using c++
I am new to c++ programing and working with visual Studio 2015. I want to create a Folder with  a Name of current date in a particular path. I searched on the Internet but I was not able to find the satisfactory solution. Moreover I tried by my own but unfortunately the result is not successful.
I used _mkdir() and CreateFolder().

For example, if i compile the program today (07.07.2017) then it should create a Folder with a Name: "07072017" and if i compile it again then it should Show the message: "Folder already exists".

Thanks in advance.

答:
Here is an example using <experimental/filesystem> and visual studio.

```<code>#include "stdafx.h"
#include <iostream>
#include <experimental\filesystem>

using namespace std;

int main() {
int sizeofdate = strlen(__DATE__);
char* dirname = new char[4 + sizeofdate];
memcpy(dirname, "C:/", 3);
memcpy(dirname + 4, __DATE__, sizeofdate);

cout << "creating directory" << endl;
if (!experimental::filesystem::exists(dirname)) {
    experimental::filesystem::create_directory(dirname);
}
else {
    cout << "directory already exists!" << endl;
}

delete[] dirname;

int thing;
cin >> thing;

return 0;
}
</code>```

Body:
Here is an example using <experimental/filesystem> and visual studio.

#include "stdafx.h"
#include <iostream>
#include <experimental\filesystem>

using namespace std;

int main() {
int sizeofdate = strlen(__DATE__);
char* dirname = new char[4 + sizeofdate];
memcpy(dirname, "C:/", 3);
memcpy(dirname + 4, __DATE__, sizeofdate);

cout << "creating directory" << endl;
if (!experimental::filesystem::exists(dirname)) {
    experimental::filesystem::create_directory(dirname);
}
else {
    cout << "directory already exists!" << endl;
}

delete[] dirname;

int thing;
cin >> thing;

return 0;
}


问:
Implement AutoCorrect in a Quill editor
I'd like to implement AutoCorrect in my Quill editor.

For example, when the user types the string (c) in their Quill editor, I'd like to replace it with the string ©.

I'd like to use the same mechanism to replace straight quotes with curly quotes, to correct basic misspellings, and to automatically insert a new bulleted list when the user starts a new line with *, so I'm looking for an efficient mechanism that can be generalized around those use-cases.

What do you suggest?

答:
Using keyboard bindings might be a good solution for the use cases you mention except for the "correct basic misspellings" one, since specific characters are expected to trigger the change: ), ', or space. At the moment the ) case will need to use shiftKey + 0, but once support is added for event.key that can be easier for different keyboards. There is already a core implementation for the automatic bullets except triggered by hyphen instead of asterisk so that may be worth looking at.

The correct basic misspellings, unless scoped extremely narrowly, seems far more complex than all the others combined. Not sure there is a suggestion here without more details on scope.

Title: Implement AutoCorrect in a Quill editor


问:
IBM WAS HTTPS connection certificate chain error
I have IBM WAS 8.5.5.9 ND and MS Exchange server which I try to access with EWS Java API. Deployment manager is set on one machine, my app server with java app runs on other machine.

```<code>         ExchangeService service = new ExchangeService();
         ExchangeCredentials credentials = new WebCredentials("username", "password", "host");
         service.setCredentials(credentials);
         service.setUrl(URI.create("https://xxxxxxxxx/EWS/Exchange.asmx"));

         List msgList = new ArrayList();

         Folder folder = Folder.bind(service, WellKnownFolderName.Inbox);
         FindItemsResults results = service.findItems(folder.getId(), new ItemView(5));
         List items = results.getItems();

         service.close();
</code>```

But my app fails to acceess MS Exchange. HTTPS connection problems:

```<code>The request failed. The request failed. com.ibm.jsse2.util.j: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is:
            java.security.cert.CertPathValidatorException: The certificate issued by CN=XXX Root CA, O=XXX, C=ES is not trusted; internal cause is:
            java.security.cert.CertPathValidatorException: Certificate chaining error
</code>```

I have founded this IBM guide (http://www-01.ibm.com/support/docview.wss?uid=swg21592616).

I downloaded root and intermediate certificates from my firefox browser with which I can acceess OWA. Installed them in NodeDefaultTrustStore and even in CellDefaultTrustStore, reloaded my app server with java EWS API running on it. But still have this problem.

What did I do wrong? Maybe I missed something? Is this problem connected to IBW WAS and truststore settings or I just have wrong certificates? Shoul I add this certificates to java truststore ? Is value of Alias field in adding singer certificates important (I made alias value for my intermediate certificate other than trusted)?

答: To resolve this I also had to add root and intermediate certificates in java truststore</p>

Body:
I have IBM WAS 8.5.5.9 ND and MS Exchange server which I try to access with EWS Java API. Deployment manager is set on one machine, my app server with java app runs on other machine.

         ExchangeService service = new ExchangeService();
         ExchangeCredentials credentials = new WebCredentials("username", "password", "host");
         service.setCredentials(credentials);
         service.setUrl(URI.create("https://xxxxxxxxx/EWS/Exchange.asmx"));

         List msgList = new ArrayList();

         Folder folder = Folder.bind(service, WellKnownFolderName.Inbox);
         FindItemsResults results = service.findItems(folder.getId(), new ItemView(5));
         List items = results.getItems();

         service.close();

But my app fails to acceess MS Exchange. HTTPS connection problems:

The request failed. The request failed. com.ibm.jsse2.util.j: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is:
            java.security.cert.CertPathValidatorException: The certificate issued by CN=XXX Root CA, O=XXX, C=ES is not trusted; internal cause is:
            java.security.cert.CertPathValidatorException: Certificate chaining error

I have founded this IBM guide (http://www-01.ibm.com/support/docview.wss?uid=swg21592616).

I downloaded root and intermediate certificates from my firefox browser with which I can acceess OWA. Installed them in NodeDefaultTrustStore and even in CellDefaultTrustStore, reloaded my app server with java EWS API running on it. But still have this problem.

What did I do wrong? Maybe I missed something? Is this problem connected to IBW WAS and truststore settings or I just have wrong certificates? Shoul I add this certificates to java truststore ? Is value of Alias field in adding singer certificates important (I made alias value for my intermediate certificate other than trusted)?


问:
Grep data from multiple file then feed into a log in Python
I'm new to Python, hopefully someone can help me in this.
I want to grep data from multiple files then combine the data I grep into a single log.

My input files as such:

Input file1 (200MHz)

```<code>Cell_a  freq_100  50
Cell_a  freq_200  6.8
Cell_b  freq_100  70
</code>```

Input file2 (100MHz)

Cell_a  freq_100  100

   Cell_a  freq_200  10.5

   Cell_b  freq_100  60

This is my expected output

[cell]  [freq] [value_frm_file1] [value_frm_file2] [value_frm_file3] [etc...]

Example expected output:-

Cell_a  freq_100 50 100     #50 is taken from file1, 100 from file2

   Cell_a  freq_200 6.8 10.5

   Cell_b  freq_100 70 60

I guess the best way is to store in Python dictionary? Can you give me example or show me how to do this? Here is my code, but I'm only able to get the value one at a time, how to combined them accordingly to it's respective freq type?

```<code>for i in cmaxFreqList: #this is the list base on it's frq type, IE 200MHz, 100MHz etc
    file = path + freqfile
    with open (file) as f:
        data = f.readlines()

    for line in data:
        line = line.rstrip('\n')
        freqlength = len(line.split())
        if freqlength == 3:
            searchFreqValue =re.search("(\S+)\s+(\S+)\s+(\S+)",line)
            cell = searchFreqValue.group(1)
            freq = searchFreqValue.group(2)
            value = searchFreqValue.group(3)
            print ('cell + ' ' + freq + ' ' + value)  #only can get up to printing out one value at a time
</code>```

Thank you for your help!

答:
I dont fully understand the question due to the readability of your expected ouput, however here are some tips you could use to iterate through the parameters and the values:

for searching a type of value (i.e cell, freq, etc) you could use the list index method:

```<code>parameters = ['Cell_', 'freq_', 'etc'] #Name of the parameters you are looking for

for parameter in parameters:
    for line in data:
        new_list = line.split()
        position_of_the_value = new_list.index(parameter) + 1
</code>```

if you

```<code>print(new_list[position_of_the_value])
</code>```

you get the value for that parameter in that line, you can then store it in a list

```<code>parameter1_list = list()
parameter1_list.append(new_list[position_of_the_value])
</code>```

finally, you construct the string you want to print

```<code>print('Parameter_1 '+ ' '.join(parameter1_list))
</code>```

and this will print something like

```<code>Parameter_1 100 50 200 300
</code>```

you just have to contruct loops to iterate over every parameter and every list in order to get them all printed.

Body:
I'm new to Python, hopefully someone can help me in this.
I want to grep data from multiple files then combine the data I grep into a single log.

My input files as such:

Input file1 (200MHz)

Cell_a  freq_100  50
Cell_a  freq_200  6.8
Cell_b  freq_100  70

Input file2 (100MHz)

Cell_a  freq_100  100

   Cell_a  freq_200  10.5

   Cell_b  freq_100  60

This is my expected output

[cell]  [freq] [value_frm_file1] [value_frm_file2] [value_frm_file3] [etc...]

Example expected output:-

Cell_a  freq_100 50 100     #50 is taken from file1, 100 from file2

   Cell_a  freq_200 6.8 10.5

   Cell_b  freq_100 70 60

I guess the best way is to store in Python dictionary? Can you give me example or show me how to do this? Here is my code, but I'm only able to get the value one at a time, how to combined them accordingly to it's respective freq type?

for i in cmaxFreqList: #this is the list base on it's frq type, IE 200MHz, 100MHz etc
    file = path + freqfile
    with open (file) as f:
        data = f.readlines()

    for line in data:
        line = line.rstrip('\n')
        freqlength = len(line.split())
        if freqlength == 3:
            searchFreqValue =re.search("(\S+)\s+(\S+)\s+(\S+)",line)
            cell = searchFreqValue.group(1)
            freq = searchFreqValue.group(2)
            value = searchFreqValue.group(3)
            print ('cell + ' ' + freq + ' ' + value)  #only can get up to printing out one value at a time

Thank you for your help!

Body:
I dont fully understand the question due to the readability of your expected ouput, however here are some tips you could use to iterate through the parameters and the values:

for searching a type of value (i.e cell, freq, etc) you could use the list index method:

parameters = ['Cell_', 'freq_', 'etc'] #Name of the parameters you are looking for

for parameter in parameters:
    for line in data:
        new_list = line.split()
        position_of_the_value = new_list.index(parameter) + 1

if you

print(new_list[position_of_the_value])

you get the value for that parameter in that line, you can then store it in a list

parameter1_list = list()
parameter1_list.append(new_list[position_of_the_value])

finally, you construct the string you want to print

print('Parameter_1 '+ ' '.join(parameter1_list))

and this will print something like

Parameter_1 100 50 200 300

you just have to contruct loops to iterate over every parameter and every list in order to get them all printed.


问:
How can I read input from the console using the Scanner class in Java?
How could I read input from the console using the Scanner class? Something like this:

```<code>System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
</code>```

Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.

答:
There is a simple way to read from the console.

Please find the below code:

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

    public class ScannerDemo {

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);

            // Reading of Integer
            int number = sc.nextInt();

            // Reading of String
            String str = sc.next();
        }
    }
</code>```

For a detailed understanding, please refer to the below documents.

Doc

Now let's talk about the detailed understanding of the Scanner class working:

```<code>public Scanner(InputStream source) {
    this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
</code>```

This is the constructor for creating the Scanner instance.

Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.

```<code>public InputStreamReader(InputStream in) {
    super(in);
    try {
        sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
    }
    catch (UnsupportedEncodingException e) {
        // The default encoding should always be available
        throw new Error(e);
    }
}
</code>```

By passing the System.in this code will opens the socket for reading from console.

Body:
How could I read input from the console using the Scanner class? Something like this:

System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code

Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.

Body:
There is a simple way to read from the console.

Please find the below code:

import java.util.Scanner;

    public class ScannerDemo {

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);

            // Reading of Integer
            int number = sc.nextInt();

            // Reading of String
            String str = sc.next();
        }
    }

For a detailed understanding, please refer to the below documents.

Doc

Now let's talk about the detailed understanding of the Scanner class working:

public Scanner(InputStream source) {
    this(new InputStreamReader(source), WHITESPACE_PATTERN);
}

This is the constructor for creating the Scanner instance.

Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.

public InputStreamReader(InputStream in) {
    super(in);
    try {
        sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
    }
    catch (UnsupportedEncodingException e) {
        // The default encoding should always be available
        throw new Error(e);
    }
}

By passing the System.in this code will opens the socket for reading from console.


问:
Difference between universal and nth-child selector to get all direct children?
I wonder, if there is a difference of getting every direct child in css between

```<code>tag > *
</code>```

and

```<code>tag > :nth-child(n)
</code>```

I know that the universal selector is slow, but I don't know, what the nth-child selector is doing under the hood.

答:
I know that the universal selector is slow

No, the universal selector is fast, because it does nothing except guarantee a match (there are rare exceptions but they don't apply here). The only time it's "slow" is when you have a page with a ridiculously large number of elements (in the order of thousands) — then the browser has to run it on every element to determine if it's a child of whatever parent.

Using :nth-child(n) is needlessly asking the browser to evaluate an n expression as opposed to immediately matching the element no questions asked. Even if a browser did optimize away :nth-child(n), you're left with a guaranteed match exactly the way * works. So you're really just wasting space by using :nth-child(n) (12 whole bytes longer than *), and not getting any computational gains out of it versus just using *.

Just stick with the universal selector. Or, if you're that worried about CSS selector performance, you can always add a class name to every desired child element and select that class instead, at the cost of markup bloat.

The only functional difference between * and :nth-child(n) is specificity — the specificity of * is zero, which is less than a pseudo-class. You generally never need the extra specificity, so again, there is no reason not to stick with * for this use case. See my answer to this question for a specificity-centric use case.

Body:
I wonder, if there is a difference of getting every direct child in css between

tag > *

and

tag > :nth-child(n)

I know that the universal selector is slow, but I don't know, what the nth-child selector is doing under the hood.

ContentLicense: CC BY-SA 4.0


问:
Jquery Ajax GET call different results
I've written a few lines of code to tackle the following problem:

Get the TwitchTV UserID based on the username. The usernames are in an arrray. After hitting a button a GET AJAX request will be called to GET the UserID and to push it in another array and the call to the API will made via AJAX after hitting a button.

My problem is that if I hit the button again the usersID are in wrong order.

If I set async: false, it works.

Is this problem because of Asynchronous AJAX? What would be the approach for a valid fix? Use callback? A hint in the right direction would be appreciated.

The comments in the code are for testing.

Code:

```<code><script>

        var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "spicyjewlive"];
            clientID = "?client_id=XXX";
            userID = [];
            userStatus = [];
for(var i=0; i<users.length; i++){
          idCall(users[i]);

        };
function idCall (data){
            $.ajax({
              type: "GET",
              url: "https://api.twitch.tv/kraken/users/" + data + clientID,
              async: false,
              cache: false,
              dataType: "jsonp",
              success: function (data){
                console.log(data._id);
              },
              error: function (data) {
                console.log("error");
              }});
        };
</script>
</code>```

答:
What would be the approach for a valid fix?

I think @charlieftl answer is a good one. I don't think I can really improve on this. I've mainly added this to try and explain your difficulties here. As I mentioned in a previous question you posted, you need to read and understand How do I return the response from an asynchronous call?.

If you had control of the server side then a simpler option is to send the array server side in order and use this to maintain the order, but your using a third party API so this isn't really practical.

A simpler option would be to use a callback method:

```<code> var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "spicyjewlive"];
 var clientID = "?client_id=XXX";
 var userID = [];
 var userStatus = [];
 idCall(users);

 function idCall (users, x=0){
        if (x < users.length)
        {
            var data = users[x];
            $.ajax({
              type: "GET",
              url: "https://api.twitch.tv/kraken/users/" + data+ clientID,
              cache: false,
              dataType: "jsonp",
              success: function (data){
                console.log(data._id);
              },
              error: function (data) {
                console.log("error");
              }})
              .then(function(){
                  idCall(users, x++);
              });
          }
    };
</code>```

though like I said, charlies answer is better. This will guarantee the order and won't lock the UI. But it's slow.

Is this problem because of Asynchronous AJAX?

Yes, well asynchronous processing on a server and ordering.

When you first this open up the network panel of your debugging tool and watch the HTTP requests. What you'll see is a load of requests getting sent off at the same time but returning in different orders. You cannot guarantee the response order of a async request. It depends on the server response time, load, etc.

Example:

These request we're sent in order A,B,C,D,E,F,G but the responses we're received in B,C,E,F,G,D,A this is the nub of your problem.

Setting async to false does this:

Now no request will be sent until the previous has returned but. So stuff is sent A-G and returns A-G but this is A LOT slower than the previous example (the graphs here aren't to scale, I struggled to capture a good async:false example as I never use it, see reasons below).

Never do this (pretty much ever). What will happen is the UI thread will become locked (Javascript/browsers are single threaded, mostly) waiting for an external call and your web site will become unresponsive for long periods of time. Locking this thread doesn't just stop Javascript, it stops the entire site, so links don't work, hover overs, everything, until the async call returns the thread back to the UI.

Title: Jquery Ajax GET call different results

Body:
What would be the approach for a valid fix?

I think @charlieftl answer is a good one. I don't think I can really improve on this. I've mainly added this to try and explain your difficulties here. As I mentioned in a previous question you posted, you need to read and understand How do I return the response from an asynchronous call?.

If you had control of the server side then a simpler option is to send the array server side in order and use this to maintain the order, but your using a third party API so this isn't really practical.

A simpler option would be to use a callback method:

 var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "spicyjewlive"];
 var clientID = "?client_id=XXX";
 var userID = [];
 var userStatus = [];
 idCall(users);

 function idCall (users, x=0){
        if (x < users.length)
        {
            var data = users[x];
            $.ajax({
              type: "GET",
              url: "https://api.twitch.tv/kraken/users/" + data+ clientID,
              cache: false,
              dataType: "jsonp",
              success: function (data){
                console.log(data._id);
              },
              error: function (data) {
                console.log("error");
              }})
              .then(function(){
                  idCall(users, x++);
              });
          }
    };

though like I said, charlies answer is better. This will guarantee the order and won't lock the UI. But it's slow.

Is this problem because of Asynchronous AJAX?

Yes, well asynchronous processing on a server and ordering.

When you first this open up the network panel of your debugging tool and watch the HTTP requests. What you'll see is a load of requests getting sent off at the same time but returning in different orders. You cannot guarantee the response order of a async request. It depends on the server response time, load, etc.

Example:

These request we're sent in order A,B,C,D,E,F,G but the responses we're received in B,C,E,F,G,D,A this is the nub of your problem.

Setting async to false does this:

Now no request will be sent until the previous has returned but. So stuff is sent A-G and returns A-G but this is A LOT slower than the previous example (the graphs here aren't to scale, I struggled to capture a good async:false example as I never use it, see reasons below).

Never do this (pretty much ever). What will happen is the UI thread will become locked (Javascript/browsers are single threaded, mostly) waiting for an external call and your web site will become unresponsive for long periods of time. Locking this thread doesn't just stop Javascript, it stops the entire site, so links don't work, hover overs, everything, until the async call returns the thread back to the UI.


问:
App Splash Screen Takes Time After Clearing Cache Data
I am newbie in Android Application Development.My Splash screen takes 19s to load when the app data is cleared from settings.
When App launches the Splash Screen takes 5s.I have no idea why it is taking time
Below is my android AndroidManifest file code:

```<code>   <activity android:name=".activity.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

My Splash Activity is as follows

```<code>public class SplashActivity extends AppCompatActivity {

public final int SPLASH_DISPLAY_LENGTH=1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
   setTheme(R.style.SplashTheme);
   super.onCreate(savedInstanceState);
   // setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            /* Create an Intent that will start the Menu-Activity. */
            Intent mainIntent = new Intent(SplashActivity.this,MainActivity.class);
            startActivity(mainIntent);
            finish();
        }
    }, SPLASH_DISPLAY_LENGTH);
}
}
</code>```

My Splash theme is as follows:

```<code><style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowDisablePreview">true</item>
    <item name="android:windowBackground">@drawable/splash_screen_drawable</item>
</style>
</code>```

My Splash screen drawable is as follows:

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/icons"

        />

    <item
        android:left="65dp"
        android:right="65dp">
        <bitmap
            android:gravity="center"
            android:src="@drawable/placeholder_splash"

             />

    </item>
    <item android:drawable="@android:color/transparent"></item>
</layer-list>
</code>```

答:
```<code>public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setTheme(R.style.SplashTheme);

 Thread th = new Thread() {
            @Override
            public void run() {
                try {
                    sleep(1000);
                    Intent i = new Intent(getBaseContext(), MainActivity.class);
                    startActivity(i);
                    finish();
                } catch (Exception e) {

                }
            }
        };
        th.start();
}
}
</code>```

Body:
I am newbie in Android Application Development.My Splash screen takes 19s to load when the app data is cleared from settings.
When App launches the Splash Screen takes 5s.I have no idea why it is taking time
Below is my android AndroidManifest file code:

   <activity android:name=".activity.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

My Splash Activity is as follows

public class SplashActivity extends AppCompatActivity {

public final int SPLASH_DISPLAY_LENGTH=1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
   setTheme(R.style.SplashTheme);
   super.onCreate(savedInstanceState);
   // setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            /* Create an Intent that will start the Menu-Activity. */
            Intent mainIntent = new Intent(SplashActivity.this,MainActivity.class);
            startActivity(mainIntent);
            finish();
        }
    }, SPLASH_DISPLAY_LENGTH);
}
}

My Splash theme is as follows:

My Splash screen drawable is as follows:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/icons"

        />

    <item
        android:left="65dp"
        android:right="65dp">
        <bitmap
            android:gravity="center"
            android:src="@drawable/placeholder_splash"

             />

    </item>
    <item android:drawable="@android:color/transparent"></item>
</layer-list>


问:
Incorrect string value written to a cell using vba
I have a string variable price.

```<code>Dim price As String
</code>```

price is storing a value 301.20.But when I am trying to write it to a cell using

```<code>ThisWorkbook.Sheets(4).Cells(1,1) = price
</code>```

It is writing 22.

Note : I debugged it and in this mode I found that it is writing correct value(301.20) to the cell.
But when I run it,it is printing the wrong value.

EDIT :

Take a look at the below code

```<code>Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate "url1"
Set htmldoc = ie.document

ie.navigate "url2"
Set htmldoc1 = ie.document

Dim element As Object
Set element = htmldoc1.getElementById("lastPrice")

Dim price As String
price = element.innerText

ThisWorkbook.Sheets(4).Cells(1, 1) = price
</code>```

url1 has an element with id lastPrice.It is printing innertext of this element.

What actually it should do?
Search element with id lastPrice from url2 and print its innertext

Magically in debug mode it is printing the appropriate value.

How can I fix this ?

答:
I found a solution for this.

Define enum

```<code>Enum READYSTATE
READYSTATE_UNINITIALIZED = 0
READYSTATE_LOADING = 1
READYSTATE_LOADED = 2
READYSTATE_INTERACTIVE = 3
READYSTATE_COMPLETE = 4
End Enum
</code>```

Add below code

```<code>ie.navigate url2

'Added this

Do While ie.READYSTATE <> READYSTATE_COMPLETE
Application.StatusBar = "Trying to go to url2 ..."
DoEvents
Loop

Set htmldoc1 = ie.document
</code>```

Now because we have ordered to do events until READYSTATE_COMPLETE,it navigates to url2 and then takes the HTML document into htmldoc1.

Thanks

Body:
I have a string variable price.

Dim price As String

price is storing a value 301.20.But when I am trying to write it to a cell using

ThisWorkbook.Sheets(4).Cells(1,1) = price

It is writing 22.

Note : I debugged it and in this mode I found that it is writing correct value(301.20) to the cell.
But when I run it,it is printing the wrong value.

EDIT :

Take a look at the below code

Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate "url1"
Set htmldoc = ie.document

ie.navigate "url2"
Set htmldoc1 = ie.document

Dim element As Object
Set element = htmldoc1.getElementById("lastPrice")

Dim price As String
price = element.innerText

ThisWorkbook.Sheets(4).Cells(1, 1) = price

url1 has an element with id lastPrice.It is printing innertext of this element.

What actually it should do?
Search element with id lastPrice from url2 and print its innertext

Magically in debug mode it is printing the appropriate value.

How can I fix this ?

Body:
I found a solution for this.

Define enum

Enum READYSTATE
READYSTATE_UNINITIALIZED = 0
READYSTATE_LOADING = 1
READYSTATE_LOADED = 2
READYSTATE_INTERACTIVE = 3
READYSTATE_COMPLETE = 4
End Enum

Add below code

ie.navigate url2

'Added this

Do While ie.READYSTATE <> READYSTATE_COMPLETE
Application.StatusBar = "Trying to go to url2 ..."
DoEvents
Loop

Set htmldoc1 = ie.document

Now because we have ordered to do events until READYSTATE_COMPLETE,it navigates to url2 and then takes the HTML document into htmldoc1.

Thanks


问:
What is the difference between DoS and Brute Force attacks?
I was reading about DoS attacks on Apache servers but the "Brute Force" word pops up sometimes I know DoS attacks but "Brute Force" seems to be similar, is there a difference or it is just another word of DoS?</p>

答:
DoS or Denial of Service is an attempt to make a computer resource unavailable to its intended users. it generally consists of the concerted, malevolent efforts of a person or persons to prevent an Internet site or service from functioning efficiently or at all, temporarily or indefinitely

A brute force attack is a method of defeating a cryptographic scheme by systematically trying a large number of possibilities. For example trying a large number of the possible keys in a key space in order to decrypt a message.

OwnerDisplayName: Sulaiman

LastEditorDisplayName: Jeremy Ruten

OwnerDisplayName: GreenShadow


问:
disable java log rotation
I use java.util.logging.Logger to log in my app :

```<code>    FileHandler fh=new FileHandler(this.todayFileName, 0, 1, true);

    fh.setFormatter(new SimpleFormatter());

    Logger.getLogger(rootLogger.getName()).setLevel(Level.ALL);

    Logger.getLogger(rootLogger.getName()).addHandler(fh);
</code>```

but this does work well except that log rotation is enabled.

and i get files :

run.log run.log.1 run.log.2

what I want is to get only one log file, with no rotation enabled.

how do I do that ?

答:
Apart from the answers already given I would question your desire to disable logrotation. There are very good reasons to have logs rotate (like running out of disc space and so on) that make is a standard procedure. I would say investigate what makes you want to turn it off and eliminate that need. E.g. if you want to be able to mine the logs information easily maybe you should consider looking at a package that does that for you (e.g. splunk or whatever) and can work fine with rotated logs. Also consider that log rotation is highly configurable so maybe you just want to change the rotation config. Also consider that you could get the information you need from the log sent somewhere else for that purpose and leave the rotating log alone...

And depending on the operating system/log rotation configuration system you will probably be able to just turn the rotation off right there in the operating system and not worry about your code.

Title: disable java log rotation

Body:
I use java.util.logging.Logger to log in my app :

    FileHandler fh=new FileHandler(this.todayFileName, 0, 1, true);

    fh.setFormatter(new SimpleFormatter());

    Logger.getLogger(rootLogger.getName()).setLevel(Level.ALL);

    Logger.getLogger(rootLogger.getName()).addHandler(fh);

but this does work well except that log rotation is enabled.

and i get files :

run.log run.log.1 run.log.2

what I want is to get only one log file, with no rotation enabled.

how do I do that ?


问:
How to add dummy rows in MakeTable Query - Access 2000?
I have this picture:

As you can see the field "promet" can go from 1 to 9. However for tipprod = "02" promet has values of 1, 2, 3, 5 and 7.

I want to add dummy rows for missing values of promet, 4, 6, 8 and 9, and I want to do it for other values of tipprod, like "03" for example or "04" etc...

Here is an example of my query with some columns removed:

How can i do that?

答:
Going for a pure SQL answer:

First, create a query that returns the dummy variables:

```<code>SELECT A.tipprod, B.promet
FROM
(SELECT DISTINCT tipprod FROM T11_nezbirni) AS A, (SELECT DISTINCT promet FROM T11_nezbirni) AS B
</code>```

And then just left join the rest of your query to that on tipprod and promet

Body:
Going for a pure SQL answer:

First, create a query that returns the dummy variables:

SELECT A.tipprod, B.promet
FROM
(SELECT DISTINCT tipprod FROM T11_nezbirni) AS A, (SELECT DISTINCT promet FROM T11_nezbirni) AS B

And then just left join the rest of your query to that on tipprod and promet


问:
How to fetch value of stdClass Object inside value?
```<code>stdClass Object
(
   [net_type] => Net 1
   [No of Windows] => 2
   [0] => stdClass Object
    (
        [Windows1] => stdClass Object
            (
                [Width1] => 20
                [Height1] => 10
            )

        [Windows2] => stdClass Object
            (
                [Width2] => 40
                [Height2] => 15
            )

    )

   [Pricing/sq ft] => 20
   [Total Area] => 2
   [Total Price] => 5
)
</code>```

I know to get value of net_type:

```<code>$details_decode = json_decode($details);
echo "details==".$details_decode->net_type;
</code>```

But how to get value of Width1 i.e:

```<code>echo "windows 1==".$details_decode->Windows1['Width1'];
</code>```

答:
You are probably best to pass a second (true) parameter with json_decode:

When TRUE, returned objects will be converted into associative arrays.

i.e.:

```<code>$details_decode = json_decode($details, true);
</code>```

And then access it like an array, this is better since some of the object properties have spaces in them. e.g.:

```<code>$details_decode['net_type']
$details_decode[0]['Windows1']
$details_decode['Pricing/sq ft']
</code>```

Hope this helps.

Body:
stdClass Object
(
   [net_type] => Net 1
   [No of Windows] => 2
   [0] => stdClass Object
    (
        [Windows1] => stdClass Object
            (
                [Width1] => 20
                [Height1] => 10
            )

        [Windows2] => stdClass Object
            (
                [Width2] => 40
                [Height2] => 15
            )

    )

   [Pricing/sq ft] => 20
   [Total Area] => 2
   [Total Price] => 5
)

I know to get value of net_type:

$details_decode = json_decode($details);
echo "details==".$details_decode->net_type;

But how to get value of Width1 i.e:

echo "windows 1==".$details_decode->Windows1['Width1'];

Body:
You are probably best to pass a second (true) parameter with json_decode:

When TRUE, returned objects will be converted into associative arrays.

i.e.:

$details_decode = json_decode($details, true);

And then access it like an array, this is better since some of the object properties have spaces in them. e.g.:

$details_decode['net_type']
$details_decode[0]['Windows1']
$details_decode['Pricing/sq ft']

Hope this helps.