问:
OnErrorNotImplementedException using RxJava2 and Retrofit2 Mosby MVI
I'm getting a OnErrorNotImplementedException thrown and the app crashes, despite handling the error downstream(?).

Exception

```<code>E/AndroidRuntime: FATAL EXCEPTION: RxCachedThreadScheduler-1
Process: pl.netlandgroup.smartsab, PID: 9920
io.reactivex.exceptions.OnErrorNotImplementedException: HTTP 401 Unauthorized
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
    at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:74)
    at io.reactivex.internal.operators.observable.ObservableDoOnEach$DoOnEachObserver.onError(ObservableDoOnEach.java:119)
    at io.reactivex.internal.operators.observable.ObservableDoOnEach$DoOnEachObserver.onError(ObservableDoOnEach.java:119)
    at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeOnObserver.onError(ObservableSubscribeOn.java:63)
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:56)
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:37)
    at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:43)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
    at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
    at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
    at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
 Caused by: retrofit2.adapter.rxjava2.HttpException: HTTP 401 Unauthorized
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:54)
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:37)
    at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:43)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
    at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
    at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
    at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
</code>```

Retrofit Repository:

```<code>class RetrofitRepository (retrofit: Retrofit) {

    val apiService: ApiService = retrofit.create(ApiService::class.java)
    var size: Int = 0

    fun getMapResponse(pageIndex: Int = 0): Observable<MapResponse> {
        return apiService.getMapResponse(pageIndex = pageIndex)
                .doOnError { Log.d("error", it.message) }
                .doOnNext { Log.d("currThread", Thread.currentThread().name) }

    }

    fun getItemsFormResponses(): Observable<List<Item>> {
        val list = mutableListOf<Observable<List<Item>>>()
        val resp0 = getMapResponse()
        resp0.subscribe { size = it.totalCount }
        var accum = 0
        do {
            list.add(getMapResponse(accum).map { it.items })
            accum++
        } while (list.size*200 < size)
        return Observable.merge(list)
    }
}
</code>```

This results are observed by Interactor:

```<code>class MapInteractor @Inject constructor(private val repository: RetrofitRepository) {

    fun getMapItems(): Observable<MapViewState> {
        return repository.getItemsFormResponses()
                .map {
                    if(it.isEmpty()) {
                        return@map MapViewState.EmptyResult()
                    } else {
                        val mapItems = it.map { it.toMapItem() }
                        return@map MapViewState.MapResult(mapItems)
                    }
                }
                .doOnNext { Log.d("currThread", Thread.currentThread().name) }
                .startWith(MapViewState.Loading())
                .onErrorReturn { MapViewState.Error(it) }
    }
}
</code>```

The onErrorReturn { MapViewState.Error(it) } emits correctly (right before the app crash I can see the correct thing rendered on screen). How can I avoid this exception while still maintaining the MVI architecture?

EDIT

The answer provided by dimsuz was the correct solution, although to achieve the merging and returning one Observable with all items it had to be modified to this:

```<code>fun getMapItems(): Observable<List<Item>> {
    return getMapResponse().map {
        val size = it.totalCount
        val list = mutableListOf<Observable<List<Item>>>()
        var accum = 0
        do {
            list.add(getMapResponse(accum++).map { it.items })
        } while (list.size*200 < size)
        return@map list.zip { it.flatten() }
    }.mergeAll()
}
</code>```

答:
I believe the error is thrown in getItemsFromResponse() along the lines of:

```<code>    val resp0 = getMapResponse()
    resp0.subscribe { size = it.totalCount }
</code>```

Here you subscribe, but do not handle the error case.
Actually this code is incorrect, because you break the Rx chain in two independent pieces, you shouldn't do that.

What you should do is something like this:

```<code>fun getItemsFormResponses(): Observable<List<Item>> {
  return getMapResponse().map { resp0 ->
    val size = resp0.totalCount

    val list = mutableListOf<Observable<List<Item>>>()
    var accum = 0
    do {
      list.add(getMapResponse(accum).map { it.items })
      accum++
    } while (list.size*200 < size)
    return Observable.merge(list)
  }
}
</code>```

I.e. extract size by extending the chain with an operator, rather then breaking it with subscribe().

Body:
I'm getting a OnErrorNotImplementedException thrown and the app crashes, despite handling the error downstream(?).

Exception

E/AndroidRuntime: FATAL EXCEPTION: RxCachedThreadScheduler-1
Process: pl.netlandgroup.smartsab, PID: 9920
io.reactivex.exceptions.OnErrorNotImplementedException: HTTP 401 Unauthorized
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
    at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:74)
    at io.reactivex.internal.operators.observable.ObservableDoOnEach$DoOnEachObserver.onError(ObservableDoOnEach.java:119)
    at io.reactivex.internal.operators.observable.ObservableDoOnEach$DoOnEachObserver.onError(ObservableDoOnEach.java:119)
    at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeOnObserver.onError(ObservableSubscribeOn.java:63)
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:56)
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:37)
    at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:43)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
    at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
    at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
    at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
 Caused by: retrofit2.adapter.rxjava2.HttpException: HTTP 401 Unauthorized
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:54)
    at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:37)
    at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:43)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
    at io.reactivex.Observable.subscribe(Observable.java:10838)
    at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
    at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
    at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
    at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)

Retrofit Repository:

class RetrofitRepository (retrofit: Retrofit) {

    val apiService: ApiService = retrofit.create(ApiService::class.java)
    var size: Int = 0

    fun getMapResponse(pageIndex: Int = 0): Observable<MapResponse> {
        return apiService.getMapResponse(pageIndex = pageIndex)
                .doOnError { Log.d("error", it.message) }
                .doOnNext { Log.d("currThread", Thread.currentThread().name) }

    }

    fun getItemsFormResponses(): Observable<List<Item>> {
        val list = mutableListOf<Observable<List<Item>>>()
        val resp0 = getMapResponse()
        resp0.subscribe { size = it.totalCount }
        var accum = 0
        do {
            list.add(getMapResponse(accum).map { it.items })
            accum++
        } while (list.size*200 < size)
        return Observable.merge(list)
    }
}

This results are observed by Interactor:

class MapInteractor @Inject constructor(private val repository: RetrofitRepository) {

    fun getMapItems(): Observable<MapViewState> {
        return repository.getItemsFormResponses()
                .map {
                    if(it.isEmpty()) {
                        return@map MapViewState.EmptyResult()
                    } else {
                        val mapItems = it.map { it.toMapItem() }
                        return@map MapViewState.MapResult(mapItems)
                    }
                }
                .doOnNext { Log.d("currThread", Thread.currentThread().name) }
                .startWith(MapViewState.Loading())
                .onErrorReturn { MapViewState.Error(it) }
    }
}

The onErrorReturn { MapViewState.Error(it) } emits correctly (right before the app crash I can see the correct thing rendered on screen). How can I avoid this exception while still maintaining the MVI architecture?

EDIT

The answer provided by dimsuz was the correct solution, although to achieve the merging and returning one Observable with all items it had to be modified to this:

fun getMapItems(): Observable<List<Item>> {
    return getMapResponse().map {
        val size = it.totalCount
        val list = mutableListOf<Observable<List<Item>>>()
        var accum = 0
        do {
            list.add(getMapResponse(accum++).map { it.items })
        } while (list.size*200 < size)
        return@map list.zip { it.flatten() }
    }.mergeAll()
}

Body:
I believe the error is thrown in getItemsFromResponse() along the lines of:

    val resp0 = getMapResponse()
    resp0.subscribe { size = it.totalCount }

Here you subscribe, but do not handle the error case.
Actually this code is incorrect, because you break the Rx chain in two independent pieces, you shouldn't do that.

What you should do is something like this:

fun getItemsFormResponses(): Observable<List<Item>> {
  return getMapResponse().map { resp0 ->
    val size = resp0.totalCount

    val list = mutableListOf<Observable<List<Item>>>()
    var accum = 0
    do {
      list.add(getMapResponse(accum).map { it.items })
      accum++
    } while (list.size*200 < size)
    return Observable.merge(list)
  }
}

I.e. extract size by extending the chain with an operator, rather then breaking it with subscribe().


来源: stackexchange

问:
Most performant way to use a background image throughout an iphone application
I have an image that I want to use as the background for every view in my application including several modal views.

Right now I'm just creating a new UIColor for each view:

```<code>view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"metal-bg.png"]];
</code>```

This works for the most part but with the modal views there is a brief period during the sliding animation before the background image displays when I can see through the modal view to the view below it.

Is there a better way to do this?
Such as setting up some sort of global object that all the views can use?

答: Have you tried setting the background image in viewWillAppear:(BOOL)animated?

ContentLicense: CC BY-SA 2.5

Body:
I have an image that I want to use as the background for every view in my application including several modal views.

Right now I'm just creating a new UIColor for each view:

view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"metal-bg.png"]];

This works for the most part but with the modal views there is a brief period during the sliding animation before the background image displays when I can see through the modal view to the view below it.

Is there a better way to do this?
Such as setting up some sort of global object that all the views can use?


问:
JQ: Nested JSON Array transformation
Since some month ago i had a little problem with a jq Transformation (j1 1.5 on Windows 10). Since them the command worked excellent: "[{nid, title, nights, company: .operator.shortTitle, zone: .zones[0].title}
+ (.sails[] | { sails_nid: .nid, arrival, departure } )
+ (.sails[].cabins[] | { cabinname: .cabinType.title, cabintype: .cabinType.kindName, cabinnid: .cabinType.nid,  catalogPrice, discountPrice, discountPercentage, currency } )]". Since some days ago the api deliver "bigger" json files JSON File. With the jq command i got a lot of duplicates (with the attached file i got around 3146 objects, expected objects are arround 250). I tried to Change the jq command to avoid the duplicates but had no "luck" on that.
The json files contains a variable amount of sails (10 in these case), while each sail has a variable amount of cabins (25 in this case). Any tips how i can realize that? Regards timo

答:
This is probably what you're looking for:

```<code>[{nid, title, nights, company: .operator.shortTitle, zone: .zones[0].title}
 + (.sails[] | ({ sails_nid: .nid, arrival, departure } +
                (.cabins[] | { cabinname: .cabinType.title,
                               cabintype: .cabinType.kindName,
                               cabinnid: .cabinType.nid,
                               catalogPrice,
                               discountPrice,
                               discountPercentage,
                               currency } ))) ]
</code>```

Hopefully the layout will clarify the difference with your jq filter.

ContentLicense: CC BY-SA 3.0

Title: JQ: Nested JSON Array transformation

Body:
This is probably what you're looking for:

[{nid, title, nights, company: .operator.shortTitle, zone: .zones[0].title}
 + (.sails[] | ({ sails_nid: .nid, arrival, departure } +
                (.cabins[] | { cabinname: .cabinType.title,
                               cabintype: .cabinType.kindName,
                               cabinnid: .cabinType.nid,
                               catalogPrice,
                               discountPrice,
                               discountPercentage,
                               currency } ))) ]

Hopefully the layout will clarify the difference with your jq filter.


问:
how to pass angular js variable inside onclick function as parameter
I have tried to pass AngularJS variable as argument value inside onclick() to call javascript function. Can anyone guide me on how to do it?

My code:

```<code> <div onclick="deleteArrival({{filterList.id}})" class="table-icon deleteIcon">{{filterList.id}}</div>
</code>```

答:
I had a case where I could not use ng-click due to window binding. Did not get direct answer but the below did work for me. I know it is not a good solution but workable in my case.

angular.element(this).scope().ctrlName.variable

You can try using your own class structure. So the click will be as below:

onclick="test(angular.element(this).scope().ctrlName.ObjName.variable)"

Body:
I have tried to pass AngularJS variable as argument value inside onclick() to call javascript function. Can anyone guide me on how to do it?

My code:

{{filterList.id}}


问:
Splitting divs into 2 columns
I have a code like this:

title1

article1

title2

article2

title3

article3

title4

article4

```
</div>
</div>
</p>

<p>and I want to transform this 1 lined column into 2 columns like this:</p>

<p><img src="https://i.stack.imgur.com/NKI4c.png" alt="example image"></p>

<p>I already tried to use this code, but is there any different way to split the div?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex-grow: 1;
  flex-basis: 50%;
}

.article:after {
  content: "";
  flex: auto;
}</code>```

title1

article1

title2

article2

title3

article3

title4

article4

```

It's different from this other question Split Div Into 2 Columns Using CSS, the "article" arrangement from this question is different. Anyone got the idea?

答:
This is actually quite simple. You just need to set .article to display: inline-block;, and seporate the second one from the first one with a
, and perhaps width: 49%; on the .article to get the effect of a proper column

.article {
  display: inline-block;
  width: 49%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="article-container">
  <div class="article">
    <h3>title1</h3>
    <p>article1</p>
  </div>
  <div class="article">
    <h3>title2</h3>
    <p>article2</p>
  </div>
  <br>
  <div class="article">
    <h3>title3</h3>
    <p>article3</p>
  </div>
  <div class="article">
    <h3>title4</h3>
    <p>article4</p>
  </div>
</div></code>```

Title: Splitting divs into 2 columns

Body:
I have a code like this:

title1

article1

title2

article2

title3

article3

title4

article4

and I want to transform this 1 lined column into 2 columns like this:

I already tried to use this code, but is there any different way to split the div?

.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex-grow: 1;
  flex-basis: 50%;
}

.article:after {
  content: "";
  flex: auto;
}

title1

article1

title2

article2

title3

article3

title4

article4

It's different from this other question Split Div Into 2 Columns Using CSS, the "article" arrangement from this question is different. Anyone got the idea?

Body:
This is actually quite simple. You just need to set .article to display: inline-block;, and seporate the second one from the first one with a <br>, and perhaps width: 49%; on the .article to get the effect of a proper column

.article {
  display: inline-block;
  width: 49%;
}

<div class="article-container">
  <div class="article">
    <h3>title1</h3>
    <p>article1</p>
  </div>
  <div class="article">
    <h3>title2</h3>
    <p>article2</p>
  </div>
  <br>
  <div class="article">
    <h3>title3</h3>
    <p>article3</p>
  </div>
  <div class="article">
    <h3>title4</h3>
    <p>article4</p>
  </div>
</div>


问:
Cannot $_POST data to php file from a form
I am very new to html and php and need a little help. This is actually my first post on stackoverflow so I apologize if the content isn't done right.

I am asking for a username and password from a user and then I want to take that information and use it in a script that is run on the server via PHP.

The problem I'm having is that the first time a user goes to the html and fills out the form, the $_POST in the php file doesn't receive anything. I know that because I echoed the variables in the php file. But after the user presses the 'Back' button on the php page and returns back to the html, when going through it again, everything works fine.

So the code works, it just doesn't work the first time. Any ideas?

HTML:

```<code><body>
<div class="loader" id="container" style="visibility:hidden;"></div>
  <form method="post" action="Login_Page.php">
     <b>Username:</b><input type="text" placeholder="University ID" name="userid" autofocus/>
     <b>Password:</b><input type="password" placeholder="Password" name="pswrd"/>
     <input type="submit" class="button" value="Submit" onclick="showDiv()"/>
</form>
</div>
</body>
</code>```

CSS:

```<code>    .loader {
                position: fixed;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                z-index: 9999;
                background: url('https://cdn.shopify.com/s/files/1/1247/2733/t/4/assets/loading.gif?11916921113420493983') 50% 50% no-repeat rgba(255, 255, 255, 0.3);
                filter: alpha(opacity=60);
        }
</code>```

Script:

```<code><script type="text/javascript">
showDiv = function() {
            document.getElementById("container").style.visibility="visible";
            }
</script>
</code>```

PHP:

```<code><?php
    $username = $_POST["userid"];
    $pswrd = $_POST["pswrd"];

    echo $username;
    echo $pswrd;

    $cmd = "path/to/script.sh $username $pswrd";

    exec($cmd, $output, $return);

if ($return != "0") {
        echo '<h1><b>Login was unsuccessful. Please try again.</b></h1>';
        echo '<form>';
          echo '<input type="button" value="Back" onClick="history.go(-1);return true;"/>';
        echo '</form>';
    } else {
        echo '<h1><b>Login was Successful.</b></h1>';
    }
?>
</code>```

答: So it ended up being a security certificate issue. I was trying to open up my website on an iPad and I didn't have the correct security certificate download on the iPad. This might sound weird but it has been consistently working after I did that. Thank you, everyone, for all of your helpful comments and assistance.</p>

Body:
I am very new to html and php and need a little help. This is actually my first post on stackoverflow so I apologize if the content isn't done right.

I am asking for a username and password from a user and then I want to take that information and use it in a script that is run on the server via PHP.

The problem I'm having is that the first time a user goes to the html and fills out the form, the $_POST in the php file doesn't receive anything. I know that because I echoed the variables in the php file. But after the user presses the 'Back' button on the php page and returns back to the html, when going through it again, everything works fine.

So the code works, it just doesn't work the first time. Any ideas?

HTML:

  <form method="post" action="Login_Page.php">
     Username:<input type="text" placeholder="University ID" name="userid" autofocus/>
     Password:<input type="password" placeholder="Password" name="pswrd"/>
     <input type="submit" class="button" value="Submit" onclick="showDiv()"/>
</form>

CSS:

    .loader {
                position: fixed;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                z-index: 9999;
                background: url('https://cdn.shopify.com/s/files/1/1247/2733/t/4/assets/loading.gif?11916921113420493983') 50% 50% no-repeat rgba(255, 255, 255, 0.3);
                filter: alpha(opacity=60);
        }

Script:

PHP:

<?php
    $username = $_POST["userid"];
    $pswrd = $_POST["pswrd"];

    echo $username;
    echo $pswrd;

    $cmd = "path/to/script.sh $username $pswrd";

    exec($cmd, $output, $return);

if ($return != "0") {
        echo '
Login was unsuccessful. Please try again.
';
        echo '<form>';
          echo '<input type="button" value="Back" onClick="history.go(-1);return true;"/>';
        echo '</form>';
    } else {
        echo '
Login was Successful.
';
    }
?>


问:
How to change server time?
I need to change server time from asp.net page. Is it possible?</p>

答:
I know this is not what you asked and does not change the server time, only changes the time from the perspective of the asp.net page. If the time difference is a constant then this code might be your friend!

This example adds 1 hour from now...

```<code>var today = DateTime.Now;
var duration = new TimeSpan(1, 0, 0);
var answer = today.Add(duration);
</code>```

Title: How to change server time?

Body:
I know this is not what you asked and does not change the server time, only changes the time from the perspective of the asp.net page. If the time difference is a constant then this code might be your friend!

This example adds 1 hour from now...

var today = DateTime.Now;
var duration = new TimeSpan(1, 0, 0);
var answer = today.Add(duration);


问:
django instance.id=None when uploading image
instance.id is returning None when upload images through the admin page. The idea was to upload all the images of each Residence to a different folder. Here's my code:

models.py

```<code>from django.db import models
import os

def get_image_path(instance, filename):
    return os.path.join('photos', "residence_%s" % instance.id, filename)

# Create your models here.
class Residence(models.Model):
    big_image = models.ImageField("Main Image",upload_to=get_image_path)
    small_images = models.ImageField("Small Images",upload_to=get_image_path, blank=True, null=True)
</code>```

settings.py

```<code>MEDIA_URL = '/media/'
</code>```

EDIT: It works if I modify the image after the model is already added.

答:
Another nice way to solve this problem that requires much less code is to have your model use a UUID for the primary key rather then the database generated id. This means at the point the model is saved for the first time the UUID is already known and can be used with any upload_to callbacks.

So for the original example you would do something like this

```<code>from django.db import models

import uuid
import os

def get_image_path(instance, filename):
    return os.path.join('photos', "residence_%s" % str(instance.id), filename)

# Create your models here.
class Residence(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    big_image = models.ImageField("Main Image",upload_to=get_image_path)
    small_images = models.ImageField("Small Images",upload_to=get_image_path, blank=True, null=True)
</code>```

See Django's UUIDField reference for more info

Body:
instance.id is returning None when upload images through the admin page. The idea was to upload all the images of each Residence to a different folder. Here's my code:

models.py

from django.db import models
import os

def get_image_path(instance, filename):
    return os.path.join('photos', "residence_%s" % instance.id, filename)

# Create your models here.
class Residence(models.Model):
    big_image = models.ImageField("Main Image",upload_to=get_image_path)
    small_images = models.ImageField("Small Images",upload_to=get_image_path, blank=True, null=True)

settings.py

MEDIA_URL = '/media/'

EDIT: It works if I modify the image after the model is already added.

Body:
Another nice way to solve this problem that requires much less code is to have your model use a UUID for the primary key rather then the database generated id. This means at the point the model is saved for the first time the UUID is already known and can be used with any upload_to callbacks.

So for the original example you would do something like this

from django.db import models

import uuid
import os

def get_image_path(instance, filename):
    return os.path.join('photos', "residence_%s" % str(instance.id), filename)

# Create your models here.
class Residence(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    big_image = models.ImageField("Main Image",upload_to=get_image_path)
    small_images = models.ImageField("Small Images",upload_to=get_image_path, blank=True, null=True)

See Django's UUIDField reference for more info


问:
Calling SaveAsync method sends email to attendees for existing appointment?
I just noticed following change related office js (in compose mode for outlook add-in),

```<code>Office.context.mailbox.item.saveAsync(function(result){..}
</code>```

Previously calling saveAsync method inside Outlook Add-in was sending invitation email for new appointment or draft, could be due to recent fixes or changes now it won't send invitation email to attendees for new/draft appointment. But this change has introduced new BUG, now it sends email on existing appointment which was working fine previously.

Can anybody help me to avoid sending email in case saveAsync call, in case of update appointment, as my connector does the work of sending invitation?

答:
Manoj, there was indeed a recent change to behavior for new calendar items like you described. However, we are fairly certain that there was no change in behavior for existing calendar items - it used to send updates and it still does.

There is no concept of drafts in OWA calendar today, so there is no way for the user to make changes to an item and postpone sending an update. Because of this, we don't have a good story for this yet but we are looking into a solution to mitigate this

Body:
I just noticed following change related office js (in compose mode for outlook add-in),

Office.context.mailbox.item.saveAsync(function(result){..}

Previously calling saveAsync method inside Outlook Add-in was sending invitation email for new appointment or draft, could be due to recent fixes or changes now it won't send invitation email to attendees for new/draft appointment. But this change has introduced new BUG, now it sends email on existing appointment which was working fine previously.

Can anybody help me to avoid sending email in case saveAsync call, in case of update appointment, as my connector does the work of sending invitation?


问:
WebView - go to original URL
The application I'm working on has one section where a WebView component (a react-native one) is loaded. Well, this WebView is loaded when the users taps an icon from the bottom navigation bar (sharing those details to make you understand the context better). The user can navigate inside that WebView and let's say that he arrives to a page that seems to be a 404 page. By tapping again that icon, the user would expect to load again the first URL loaded and he can get rid of that error page, but no, there's no method goToTheFirst() URL from a WebView. There's goBack() or goForward() methods but this doesn't help (maybe the user navigated through 10 different URL's to arrive to that 404 page).

I've tried this:

Update the already rendered source of the WebView by injecting a script (nothing happens).

Reload the WebView (reloading the web view it will reload the current URL where the user arrived by navigating into that WebView).

Does anybody have any idea how I could solve this?

答:
Do something like this to retrieve the url of the current page: React Native webview get url

Essentially:

Set a state that changes only once when you go from a regular component to a webview. That state variable will be the first url.

Inject Javascript, but instead of changing the rendered source, just make your script go to the page itself from the saved state. Look at the code inside goBack() and goForward() for reference.

Title: WebView - go to original URL


问:
Android Dynamically Choosing Cities According To The Countries
At some point of my Android app, I need to store user's country and city and write it to Firebase. I know how to do the Firebase stuff.

My question is how to retrieve cities based on the chosen country from the spinner? I am planning to have two spinners for cities and countries but I don't know how to implement this logic.

I wonder if I should hardcode the countries and cities as a string array in the strings.xml file.. (there will be 40 countries at least)

Any idea would be appreciated.

答:
it's not the best solution but you can use this file.json
put it as assets or send request to it.</p>


问:
Odoo computed field Year from date_invoice
How can I extract only the year from a date field (x_date_invoice) to a new computed odoo field for example x_jaar

I am using Odoo 10.

答:
fields.Datetime and fields.Date are storaged as string, so yo have to parse into a python datetime. Then you can extract the year.</p>

```<code>datetime.strptime(your_datetime, your_datetime_format).year
</code>```

Body:
fields.Datetime and fields.Date are storaged as string, so yo have to parse into a python datetime. Then you can extract the year.

datetime.strptime(your_datetime, your_datetime_format).year


问:
Python I have device ID how to get dev address
I have a USB device, it may not be connected to the same port everytime it is plugged into the PC, how can i find it's dev-address given that I have its UID ?

```<code>import serial.tools.list_ports as port

portlist = list(port.comports())
for p in portlist:
  print p
</code>```

gives me the output :

```<code>/dev/ttyS0 - ttyS0
/dev/ttyUSB1 - USB2.0-Serial
/dev/ttyUSB0 - FT232R USB UART
</code>```

my device is FT232R USB UART ,currently whose dev address is /dev/ttyUSB0 ,and I need this in my program for serial  r/w (ser = serial.Serial(port, baud)).But if multiple devices are connected previously and I plug in this device, it changes this address, my question is how can I find out this address every time I plug my device?

答:
You do not need to use pyusb. If your system uses udev to manage hot-plug devices (like most Linux distributions do nowadays) you could use pyudev library to look up your device. Or even simpler, find your device in /dev/serial/by-id and use that symlink instead of /dev/ttyUSBx in your code. It is guaranteed to stay the same regardless of the order of connection as long you do not connect another device with the same serial number.

Otherwise:

```<code>import serial

UID = '12345678'
ports = {p.serial_number:p.device for p in serial.tools.list_ports.comports() if p.serial_number}
if UID in ports:
    port = serial.Serial(ports[UID], ...)
</code>```

Body:
I have a USB device, it may not be connected to the same port everytime it is plugged into the PC, how can i find it's dev-address given that I have its UID ?

import serial.tools.list_ports as port

portlist = list(port.comports())
for p in portlist:
  print p

gives me the output :

/dev/ttyS0 - ttyS0
/dev/ttyUSB1 - USB2.0-Serial
/dev/ttyUSB0 - FT232R USB UART

my device is FT232R USB UART ,currently whose dev address is /dev/ttyUSB0 ,and I need this in my program for serial  r/w (ser = serial.Serial(port, baud)).But if multiple devices are connected previously and I plug in this device, it changes this address, my question is how can I find out this address every time I plug my device?

Body:
You do not need to use pyusb. If your system uses udev to manage hot-plug devices (like most Linux distributions do nowadays) you could use pyudev library to look up your device. Or even simpler, find your device in /dev/serial/by-id and use that symlink instead of /dev/ttyUSBx in your code. It is guaranteed to stay the same regardless of the order of connection as long you do not connect another device with the same serial number.

Otherwise:

import serial

UID = '12345678'
ports = {p.serial_number:p.device for p in serial.tools.list_ports.comports() if p.serial_number}
if UID in ports:
    port = serial.Serial(ports[UID], ...)


问:
How do I get my WordPress dropdown to stop/wrap and shift to the right?
I am trying to get the drop-down list on my WordPress Salient theme to stop and wrap to the right on certain elements. I've tried some different css things but so far no luck.

I believe the class I need to edit is:

```<code>.sf-menu a {

display: block;
position: relative;
</code>```

HTML:

```<code><ul class="sub-menu" style="display: none;">
    <li id="menu-item-59258" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59258"><a href="https://myunion.edu/academics/bachelors/business-management/">Business Management</a></li>
    <li id="menu-item-59259" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59259"><a href="https://myunion.edu/academics/bachelors/child-and-adolescent-development/">Child & Adolescent Development</a></li>
    <li id="menu-item-59260" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59260"><a href="https://myunion.edu/bachelors-degree/criminal-justice-management/">Criminal Justice Management</a></li>
    <li id="menu-item-59261" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59261"><a href="https://myunion.edu/academics/bachelors/early-childhood-studies/">Early Childhood Studies</a></li>
    <li id="menu-item-59264" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59264"><a href="https://myunion.edu/academics/bachelors/elementary-education/">Elementary Education</a></li>
    <li id="menu-item-59265" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59265"><a href="https://myunion.edu/academics/bachelors/emergency-services-management/">Emergency Services Management</a></li>
    <li id="menu-item-59266" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59266"><a href="https://myunion.edu/academics/bachelors/exceptional-student-education/">Exceptional Student Education</a></li>
    <li id="menu-item-59267" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59267"><a href="https://myunion.edu/academics/bachelors/maternal-child-health/">Maternal Child Health: Human Lactation</a></li>
    <li id="menu-item-59268" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59268"><a href="https://myunion.edu/academics/bachelors/organizational-leadership/">Organizational Leadership</a></li>
    <li id="menu-item-59269" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59269"><a href="/academics/bachelors/psychology/">Psychology</a></li>
    <li id="menu-item-59270" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59270"><a href="https://myunion.edu/academics/bachelors/secondary-education/">Secondary Education</a></li>
    <li id="menu-item-59271" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-59271"><a href="https://myunion.edu/academics/bachelors/social-work/">Social Work</a></li>
</ul>
</code>```

答:
Assuming I understood your question right, add this to your CSS and see if that's what you are after

```<code>.submenu .submenu{
          -webkit-column-count: 2; /* Chrome, Safari, Opera */
          -moz-column-count: 2;
           column-count:2;
          -webkit-column-gap:0;
          -moz-column-gap:0;
           column-gap:0;
           width:32em;
}
</code>```

The support for the column-* properties I used above seems to be pretty decent. Let me know how it goes.

Body:
I am trying to get the drop-down list on my WordPress Salient theme to stop and wrap to the right on certain elements. I've tried some different css things but so far no luck.

I believe the class I need to edit is:

.sf-menu a {

display: block;
position: relative;

HTML:

Business Management

Child & Adolescent Development

Criminal Justice Management

Early Childhood Studies

Elementary Education

Emergency Services Management

Exceptional Student Education

Maternal Child Health: Human Lactation

Organizational Leadership

Psychology

Secondary Education

Social Work

Body:
Assuming I understood your question right, add this to your CSS and see if that's what you are after

.submenu .submenu{
          -webkit-column-count: 2; /* Chrome, Safari, Opera */
          -moz-column-count: 2;
           column-count:2;
          -webkit-column-gap:0;
          -moz-column-gap:0;
           column-gap:0;
           width:32em;
}

The support for the column-* properties I used above seems to be pretty decent. Let me know how it goes.


问:
Neo4j inconsistent behaviour of model classes
I have created 5 models in my project using ActiveNode model and using neo4j gem.

There is a model named Disease, defined as:

```<code>  class Disease
    include Neo4j::ActiveNode
    property :disease, type: String, constraint: :unique
    property :created_at, type: DateTime
    property :updated_at, type: DateTime

    enum factor_effect: [:relief, :worsen]

    # Associations
    has_many :in, :factors, type: :AFFECTED_BY
  end
</code>```

and Factor:

```<code>  class Factor
    include Neo4j::ActiveNode
    property :factor, type: String, constraint: :unique
  end
</code>```

I am able to create nodes for Factor easily but for Disease, it gives error with create function and returns a QueryProxy object with new method. (As for other models, they are also working just as Factor, properly as expected)

Here are few commands run on console:

```<code>2.3.3 :012 >   f = Factor.new
=> #<Factor uuid: nil, factor: nil>
2.3.3 :013 > f.factor = "drinking more water"
=> "drinking more water"
2.3.3 :014 > f
=> #<Factor uuid: nil, factor: "drinking more water">
2.3.3 :015 > f.save
HTTP REQUEST: 49ms GET http://localhost:7474/db/data/schema/constraint (0 bytes)
HTTP REQUEST: 8ms GET http://localhost:7474/db/data/schema/index (0 bytes)
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
CYPHER CREATE (n:`Factor`) SET n = {props} RETURN n | {:props=>{:uuid=>"33f683d4-a6b2-4c7a-84f9-549088780033", :factor=>"drinking more water"}}
HTTP REQUEST: 682ms POST http://localhost:7474/db/data/transaction (1 bytes)
HTTP REQUEST: 385ms POST http://localhost:7474/db/data/transaction/5/commit (0 bytes)
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
=> true
2.3.3 :016 > f
=> #<Factor uuid: "33f683d4-a6b2-4c7a-84f9-549088780033", factor: "drinking more water">
</code>```

So Factor node is created easily. Although there are couple of warnings and I'd like to know the reason for that.

When I do the same for Disease:

```<code>2.3.3 :020 >   d = Disease.new
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
CYPHER
MATCH (result_disease:`Disease`)
RETURN result_disease
HTTP REQUEST: 82ms POST http://localhost:7474/db/data/transaction/commit (1 bytes)
=> #<QueryProxy  []>
2.3.3 :021 > Disease.all
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
    Disease
    MATCH (n:`Disease`)
    RETURN n
    HTTP REQUEST: 11ms POST http://localhost:7474/db/data/transaction/commit (1 bytes)
    => #<QueryProxy Disease []>
</code>```

Its getting really bad for me and I'm not getting any workaround for this. Please help!!

答:
I'm really not sure why you are getting a QueryProxy for Disease.new.  I've tried testing your code locally and I get:

```<code>#<Disease uuid: nil, created_at: nil, disease: nil, factor_effect: nil, updated_at: nil>
</code>```

Maybe there is something else in your code that is affecting things?  You might try removing code until it starts working (though that's just a stab in the dark)

The WARNINGs are because constraint: :unique is no longer supported on properties.  That option used to create constraints automatically when the model was loaded, but it became a nightmare to maintain.  Constraints should now be created with migrations.  See the migration guide, especially this section

Body:
I have created 5 models in my project using ActiveNode model and using neo4j gem.

There is a model named Disease, defined as:

  class Disease
    include Neo4j::ActiveNode
    property :disease, type: String, constraint: :unique
    property :created_at, type: DateTime
    property :updated_at, type: DateTime

    enum factor_effect: [:relief, :worsen]

    # Associations
    has_many :in, :factors, type: :AFFECTED_BY
  end

and Factor:

  class Factor
    include Neo4j::ActiveNode
    property :factor, type: String, constraint: :unique
  end

I am able to create nodes for Factor easily but for Disease, it gives error with create function and returns a QueryProxy object with new method. (As for other models, they are also working just as Factor, properly as expected)

Here are few commands run on console:

2.3.3 :012 >   f = Factor.new
=> #<Factor uuid: nil, factor: nil>
2.3.3 :013 > f.factor = "drinking more water"
=> "drinking more water"
2.3.3 :014 > f
=> #<Factor uuid: nil, factor: "drinking more water">
2.3.3 :015 > f.save
HTTP REQUEST: 49ms GET http://localhost:7474/db/data/schema/constraint (0 bytes)
HTTP REQUEST: 8ms GET http://localhost:7474/db/data/schema/index (0 bytes)
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
CYPHER CREATE (n:`Factor`) SET n = {props} RETURN n | {:props=>{:uuid=>"33f683d4-a6b2-4c7a-84f9-549088780033", :factor=>"drinking more water"}}
HTTP REQUEST: 682ms POST http://localhost:7474/db/data/transaction (1 bytes)
HTTP REQUEST: 385ms POST http://localhost:7474/db/data/transaction/5/commit (0 bytes)
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
=> true
2.3.3 :016 > f
=> #<Factor uuid: "33f683d4-a6b2-4c7a-84f9-549088780033", factor: "drinking more water">

So Factor node is created easily. Although there are couple of warnings and I'd like to know the reason for that.

When I do the same for Disease:

2.3.3 :020 >   d = Disease.new
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
CYPHER
MATCH (result_disease:`Disease`)
RETURN result_disease
HTTP REQUEST: 82ms POST http://localhost:7474/db/data/transaction/commit (1 bytes)
=> #<QueryProxy  []>
2.3.3 :021 > Disease.all
WARNING: The constraint option is no longer supported (Defined on Disease for disease)
WARNING: The constraint option is no longer supported (Defined on Factor for factor)
    Disease
    MATCH (n:`Disease`)
    RETURN n
    HTTP REQUEST: 11ms POST http://localhost:7474/db/data/transaction/commit (1 bytes)
    => #<QueryProxy Disease []>

Its getting really bad for me and I'm not getting any workaround for this. Please help!!

Body:
I'm really not sure why you are getting a QueryProxy for Disease.new.  I've tried testing your code locally and I get:

#<Disease uuid: nil, created_at: nil, disease: nil, factor_effect: nil, updated_at: nil>

Maybe there is something else in your code that is affecting things?  You might try removing code until it starts working (though that's just a stab in the dark)

The WARNINGs are because constraint: :unique is no longer supported on properties.  That option used to create constraints automatically when the model was loaded, but it became a nightmare to maintain.  Constraints should now be created with migrations.  See the migration guide, especially this section


问:
Installing plugins keeps failing because of es6-prepare-plugin
I am trying to prepare my iOS app and I need to get socialsharing and the whitelist plugin working, but they do not work. For example, when I do this:

```<code>sudo cordova plugin add cordova-plugin-x-socialsharing
</code>```

I get this:

Installing "cordova-plugin-x-socialsharing" for android

Failed to install 'cordova-plugin-x-socialsharing':
  CordovaError:

Failed to fetch plugin es6-promise-plugin via registry. Probably this
  is either a connection problem, or plugin spec is incorrect. Check
  your connection and plugin name/version/URL. Error: npm: Command
  failed with exit code 1 Error output: npm ERR! code ENOLOCAL npm ERR!
  Could not install from "node_modules/es6-promise-plugin" as it does
  not contain a package.json file.

npm ERR!

How can I fix this? I tried everything. From sudo to non-sudo commands, but nothing is working for me. Adding es6-prepare-plugin manually does not work either.

My system information:

```<code>Cordova CLI: 7.0.1
Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 1.3.3
Ionic CLI Version: 2.1.0
Ionic App Lib Version: 2.1.0-beta.1
ios-deploy version: 1.9.0
ios-sim version: 5.0.8
OS: Mac OS X El Capitan
Node Version: v6.8.1
Xcode version: Xcode 8.3.3 Build version 8E3004b
</code>```

PS: in my package.json file, I see this:

```<code>"es6-promise-plugin": "file:node_modules/es6-promise-plugin",
</code>```

How can I change this?

答:
Oh dear Lord. I found the answer I was looking for, after I've struggled for hours. This link on Github is the answer to this problem.

Seems like npm version 5.x.x does not work with some ionic-plugins. I downgraded to npm 4 using npm install -g npm@4.6.1 and installing this plugin worked for me afterwards.

Ionic is so buggy sometimes. Very annoying.

Body:
I am trying to prepare my iOS app and I need to get socialsharing and the whitelist plugin working, but they do not work. For example, when I do this:

sudo cordova plugin add cordova-plugin-x-socialsharing

I get this:

Installing "cordova-plugin-x-socialsharing" for android

Failed to install 'cordova-plugin-x-socialsharing':
  CordovaError:

Failed to fetch plugin es6-promise-plugin via registry. Probably this
  is either a connection problem, or plugin spec is incorrect. Check
  your connection and plugin name/version/URL. Error: npm: Command
  failed with exit code 1 Error output: npm ERR! code ENOLOCAL npm ERR!
  Could not install from "node_modules/es6-promise-plugin" as it does
  not contain a package.json file.

npm ERR!

How can I fix this? I tried everything. From sudo to non-sudo commands, but nothing is working for me. Adding es6-prepare-plugin manually does not work either.

My system information:

Cordova CLI: 7.0.1
Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 1.3.3
Ionic CLI Version: 2.1.0
Ionic App Lib Version: 2.1.0-beta.1
ios-deploy version: 1.9.0
ios-sim version: 5.0.8
OS: Mac OS X El Capitan
Node Version: v6.8.1
Xcode version: Xcode 8.3.3 Build version 8E3004b

PS: in my package.json file, I see this:

"es6-promise-plugin": "file:node_modules/es6-promise-plugin",

How can I change this?


问:
Java singleton pattern of hungry implementation
I have some code like this

```<code>public class MySingleton {

private static MySingleton instance = new MySingleton();

private MySingleton(){}

public static MySingleton getInstance() {
    return instance;
}  }
</code>```

This is a hungry implementation for singleton pattern in Java and we know that the instance had been created before getInstance be called.

We also know that a static member  will be instantiated when class MySingleton be instantiated. Class MySingleton will be instantiated  only when getInstance had been called in this code above. So, the instance had been created after getInstance be called.

So which one is right ??

and why ?

The question is not duplicate.

It doesn't talk about when static class initialization happen but some doubts about hungry implementation for singleton pattern.

May be in this case the class as posted in this question will almost certainly not be initialized until getInstance has been called the first time.

答:
2nd statement is false, static members are initialized when the class they are in is loaded, not when the first instance of that class is created.

It is easy to show because you do not need an instance of a class to access its static members
i.E.
MyClass.intVar = 5 works fine.
You do not need to instantiate MyClass first.

Body:
I have some code like this

public class MySingleton {

private static MySingleton instance = new MySingleton();

private MySingleton(){}

public static MySingleton getInstance() {
    return instance;
}  }

This is a hungry implementation for singleton pattern in Java and we know that the instance had been created before getInstance be called.

We also know that a static member  will be instantiated when class MySingleton be instantiated. Class MySingleton will be instantiated  only when getInstance had been called in this code above. So, the instance had been created after getInstance be called.

So which one is right ??

and why ?

The question is not duplicate.

It doesn't talk about when static class initialization happen but some doubts about hungry implementation for singleton pattern.

May be in this case the class as posted in this question will almost certainly not be initialized until getInstance has been called the first time.


问:
How to resize the portion of geometry keeping other parts constant in wpf?
I am under a situation where i have to resize a geometry having path this

```<code>   viewModel.Shapes.Add(new ShapeDataModel
            {
                Type = "T-Type",
                Geometry = Geometry.Parse("M 0,0 H 600 V 200 H 375 V 600 H 225 V 200 H 0 V 0 Z"),  /path
                Width = 170, Height=300,

                //new RectangleGeometry(new Rect(200, 50, 50, 100)),
                Fill = Brushes.Yellow,
                Stroke = Brushes.DarkGreen,
                StrokeThickness = 2,
                Left=300,
                Top=200

            });
</code>```

It is binded in View like this :

```<code>         <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Path Data="{Binding Geometry}"
                      Fill="{Binding Fill}"
                      Stroke="{Binding Stroke}"
                      StrokeThickness="{Binding StrokeThickness}"/>

                </DataTemplate>
            </ItemsControl.ItemTemplate>
</code>```

With this geometry   Geometry = Geometry.Parse("M 0,0 H 600 V 200 H 375 V 600 H 225 V 200 H 0 V 0 Z") . I get a T-shaped image using this geometry.

I am able to resize it. The problem is i just want to resize only one portion of this image (lets say it should just resize the part covered in red arrow direction only, dragging from the red circle at bottom in the direction of arrow). Lets say this top-right portion of T-Image like this http://prntscr.com/frzgqf keeping other
part constant.

How to resize the portion of geometry keeping other parts constant ?

答:
As seen here:

https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/how-to-create-multiple-subpaths-within-a-pathgeometry

https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/path-markup-syntax

You could try break down the path M's to create a couple of inner paths which then you could work on seperatly.

Body:
I am under a situation where i have to resize a geometry having path this

   viewModel.Shapes.Add(new ShapeDataModel
            {
                Type = "T-Type",
                Geometry = Geometry.Parse("M 0,0 H 600 V 200 H 375 V 600 H 225 V 200 H 0 V 0 Z"),  /path
                Width = 170, Height=300,

                //new RectangleGeometry(new Rect(200, 50, 50, 100)),
                Fill = Brushes.Yellow,
                Stroke = Brushes.DarkGreen,
                StrokeThickness = 2,
                Left=300,
                Top=200

            });

It is binded in View like this :

         <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Path Data="{Binding Geometry}"
                      Fill="{Binding Fill}"
                      Stroke="{Binding Stroke}"
                      StrokeThickness="{Binding StrokeThickness}"/>

                </DataTemplate>
            </ItemsControl.ItemTemplate>

With this geometry   Geometry = Geometry.Parse("M 0,0 H 600 V 200 H 375 V 600 H 225 V 200 H 0 V 0 Z") . I get a T-shaped image using this geometry.

I am able to resize it. The problem is i just want to resize only one portion of this image (lets say it should just resize the part covered in red arrow direction only, dragging from the red circle at bottom in the direction of arrow). Lets say this top-right portion of T-Image like this http://prntscr.com/frzgqf keeping other
part constant.

How to resize the portion of geometry keeping other parts constant ?


问:
Hiding a private overloaded virtual function?
I have a class hierarchy that works approximately like this:

```<code>class A
{
protected:
    virtual void f(int) = 0;
};

class B
{
protected:
    virtual void f(char*) = 0;
};

class DA : A
{
private:
    virtual void f(int) override {}
};

class DB : public DA, B
{
private:
    virtual void f(char*) override {}
};
</code>```

When I try to compile with clang (or gcc, for that matter), it gives me the warning

```<code><source>:22:18: warning: 'DB::f' hides overloaded virtual function [-Woverloaded-virtual]
    virtual void f(char*) override {}
                 ^
<source>:16:18: note: hidden overloaded virtual function 'DA::f' declared here: type mismatch at 1st parameter ('int' vs 'char *')
    virtual void f(int) override {}
                 ^
</code>```

Which I understand, but should it really give that warning? After all, DB cannot even see the hidden function (which might even be named the same by coincidence).

If it wasn't private, I could use

```<code>using DA::f;
</code>```

to clarify, of course, but the function is private, DB doesn't even know about it, and certainly shouldn't expose it.

Is there a way to fix this without deactivating that warning, i.e. telling the compiler that everything is designed as is intended?

答:
After all, DB cannot even see the hidden function (which might even be named the same by coincidence).

Accessibility and visibility are different concepts in C++. DA::f() is by default visible inside DB (and then hidden by DB::f()), but it is not accessible, because it is private inside DA, and DB is not a friend of DA. One could argue that hiding a function that is inaccessible is harmless, because it cannot be called anyway. However, the distinction between hidden and inaccessible can be significant because visible and inaccessible functions do participate in overload resolution. If db is an object of type DB, then what does db.f(0) do? If DA::f() is visible but inaccessible, it will be selected as best match and the compiler will emit a diagnostic because it is inaccessible and therefore cannot be called. If DA::f() is hidden, however, the compiler will select the overload that accepts a pointer instead, and treat the literal 0 as a null pointer.

Body:
I have a class hierarchy that works approximately like this:

class A
{
protected:
    virtual void f(int) = 0;
};

class B
{
protected:
    virtual void f(char*) = 0;
};

class DA : A
{
private:
    virtual void f(int) override {}
};

class DB : public DA, B
{
private:
    virtual void f(char*) override {}
};

When I try to compile with clang (or gcc, for that matter), it gives me the warning

<source>:22:18: warning: 'DB::f' hides overloaded virtual function [-Woverloaded-virtual]
    virtual void f(char*) override {}
                 ^
<source>:16:18: note: hidden overloaded virtual function 'DA::f' declared here: type mismatch at 1st parameter ('int' vs 'char *')
    virtual void f(int) override {}
                 ^

Which I understand, but should it really give that warning? After all, DB cannot even see the hidden function (which might even be named the same by coincidence).

If it wasn't private, I could use

using DA::f;

to clarify, of course, but the function is private, DB doesn't even know about it, and certainly shouldn't expose it.

Is there a way to fix this without deactivating that warning, i.e. telling the compiler that everything is designed as is intended?


问:
javascript foreach find and update
Let say I have an array of tree type data

```<code>[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ]
</code>```

is it possible to update the array to

```<code>[ { 'id': 1, 'name': 'root', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3, 'parent_name': 'level 2' } ]
</code>```

using lodash forEach and find?

```<code>_.forEach(arr, function (o) {
  let item = _.find(arr, {'id': o.parent_id})
  o.parent_name = item.name
})
</code>```

my problem is inside the function of forEach, it has no idea what arr is, I got it working replacing the forEach with a plain for loop.

```<code>for (i = 0; i < arr.length; i++) {
  let item = _.find(arr, {'id': arr[i].parent_id})
  arr[i].parent_name = item.name
}
</code>```

So wondering if there're any more elegant way to accomplish this

答:
Here's another way to solve your problem using a hash to improve performance:

```<code>let hash = _.keyBy(data, 'id');
</code>```

This will create an object where the keys are the id:

```<code>{
    1: { id: 1, name: 'root' ... },
    2: { id: 2, name: 'level 1' ... },
    ...
}
</code>```

Then just iterate over the data to set the parent_name using the hash:

```<code>_.each(data, item => item.parent_name = _.get(hash, [item.parent_id, 'name']));
</code>```

Title: javascript foreach find and update

Body:
Let say I have an array of tree type data

[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ]

is it possible to update the array to

[ { 'id': 1, 'name': 'root', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3, 'parent_name': 'level 2' } ]

using lodash forEach and find?

_.forEach(arr, function (o) {
  let item = _.find(arr, {'id': o.parent_id})
  o.parent_name = item.name
})

my problem is inside the function of forEach, it has no idea what arr is, I got it working replacing the forEach with a plain for loop.

for (i = 0; i < arr.length; i++) {
  let item = _.find(arr, {'id': arr[i].parent_id})
  arr[i].parent_name = item.name
}

So wondering if there're any more elegant way to accomplish this

Body:
Here's another way to solve your problem using a hash to improve performance:

let hash = _.keyBy(data, 'id');

This will create an object where the keys are the id:

{
    1: { id: 1, name: 'root' ... },
    2: { id: 2, name: 'level 1' ... },
    ...
}

Then just iterate over the data to set the parent_name using the hash:

_.each(data, item => item.parent_name = _.get(hash, [item.parent_id, 'name']));


问:
Find the time complexity of a recursive function
Why is the time complexity of this function O(n1*n2) when n1 is the length of s1 and n2 is the length of s2?   </p>

<p>I tried to build an equation but failed. </p>

```<code>#include <stdio.h>

int f(char* s1, int i1, char* s2, int i2) {
    if (s2[i2] == '\0')
        return 1;
    if (s1[i1] == '\0')
        return 0;
    if (s1[i1] != s2[i2])
        return f(s1, i1 + 1, s2, 0);
    return f(s1, i1+1, s2, i2+1);
}

void main() {
    printf("%d", f("hello", 0, "he", 0));
}
</code>```

答:
Let a be the first integer index where s1[a] != s2[a] ∧ s1[a] != '\0' ∧ s2[a] != '\0'

If a exists, then your function is O(n1).

Else, it is O(min{ n1, n2 }).

In simpler terms, if one of your string is a right trimmed version of the other one, then the function will be O(n), with n the size of the substring.

Else, it will be O(n1).

To understand this, I would advise you to try some iterations of the function yourself, with a pen and a paper, at first without the last if.

Body:
Why is the time complexity of this function O(n1*n2) when n1 is the length of s1 and n2 is the length of s2?

I tried to build an equation but failed.

#include <stdio.h>

int f(char* s1, int i1, char* s2, int i2) {
    if (s2[i2] == '\0')
        return 1;
    if (s1[i1] == '\0')
        return 0;
    if (s1[i1] != s2[i2])
        return f(s1, i1 + 1, s2, 0);
    return f(s1, i1+1, s2, i2+1);
}

void main() {
    printf("%d", f("hello", 0, "he", 0));
}


问:
Create folder in batch script and ignore if it exists
How do I create folder (and any subfolders) in batch script? But the important thing is that, if the folder (or any subfolders) already exists, it should not return error.

For example, something like this:

mkdir mydir - success(directory is now created)

mkdir mydir\subdir - success(now mydir contains subdir)

mkdir mydir - success(folder already exists, should not throw an error)

mkdir mydir\subdir - success(folders already exists, should not throw an error)

What I actually need is just to ensure that the folder structure exists.

答:
You need to check the path and create if it doesn't exist

if not exist "mydir\subdir" md "mydir\subdir"
```
<p>Or you can also suppress the error message by redirecting stderr</p>
<pre class="lang-bat prettyprint-override"><code>md "mydir\subdir" 2>NUL
</code>```

You don't need to run mkdir mydir first because

Command extensions, which are enabled by default, allow you to use a single md command to create intermediate directories in a specified path.

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/md

See also https://ss64.com/nt/md.html

ContentLicense: CC BY-SA 4.0

Body:
You need to check the path and create if it doesn't exist

if not exist "mydir\subdir" md "mydir\subdir"

Or you can also suppress the error message by redirecting stderr

md "mydir\subdir" 2>NUL

You don't need to run mkdir mydir first because

Command extensions, which are enabled by default, allow you to use a single md command to create intermediate directories in a specified path.

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/md

See also https://ss64.com/nt/md.html


问:
MTL will not load in AFrame
When attempting to load in the MTL file for my OBJ object, I continually get the warning: Material component properties are ignored when a .MTL is provided.
I based what I wrote on this https://github.com/aframevr/aframe/blob/master/docs/primitives/a-obj-model.md#example and the documentation on Objects. I suspect the problem has something to with the path of each asset. It is strange that the Object works but the MTL is having issues loading. Currently I have everything saved in the assets folder in A Frame and the Path is the URL that Glitch provides for the Object and MTL. I apologize if this question is simple. Thanks in advance.

https://gamy-duke.glitch.me/

答:
Your MTL and OBJ files are invalid. They point to local directories.

tiefighterMTL = Users\Irishes\Documents\3D Resources\Voxel Models\tiefighter.mtl

Title: MTL will not load in AFrame


问:
How to use a css selector wildcard if the id values keep changing
How to use a css selector wildcard if the id values keep changing?

```<code> <td role="gridcell" style="text-align:center;" title="**Edit**  |  Copy</a" aria-describedby="list4_action"><a href="mac1/notification/edit?id=**12374**">Edit</a>  |  <a href="/mac1/notification/copy?id=12374">Copy</a></td>
</code>```

This is in a table where the id # 12374 changes for every new row . I was looking for selenium to click the EDIT button .

When i use cssSelector:a[href*='/mac1/notication/edit?$id='*] the test is failing with the message

Caused by: org.openqa.selenium.InvalidSelectorException: The given selector a[href*='/mac/notication/edit?$id='*] is either invalid or does not result in a WebElement. The following error occurred:
  InvalidSelectorError: An invalid or illegal selector was specified

答:
You are correct in using the CSS3 [attribute*=value] Selector.

However, you have a typo in your CSS Selector (you spelled notification wrong) and you've included an unnecessary $ character. Try this:

```<code>a[href*='/mac1/notification/edit?id=']
</code>```

Essentially, this CSS Selector will search for an  tag with an href attribute containing the string /mac1/notification/edit?id=.

Body:
How to use a css selector wildcard if the id values keep changing?

 <td role="gridcell" style="text-align:center;" title="**Edit**  |  CopyEdit  |  Copy

This is in a table where the id # 12374 changes for every new row . I was looking for selenium to click the EDIT button .

When i use cssSelector:a[href*='/mac1/notication/edit?$id='*] the test is failing with the message

Caused by: org.openqa.selenium.InvalidSelectorException: The given selector a[href*='/mac/notication/edit?$id='*] is either invalid or does not result in a WebElement. The following error occurred:
  InvalidSelectorError: An invalid or illegal selector was specified

Body:
You are correct in using the CSS3 [attribute*=value] Selector.

However, you have a typo in your CSS Selector (you spelled notification wrong) and you've included an unnecessary $ character. Try this:

a[href*='/mac1/notification/edit?id=']

Essentially, this CSS Selector will search for an <a> tag with an href attribute containing the string /mac1/notification/edit?id=.


问:
Sub package imports with python
I am new to python, but very experienced with PHP and JavaScript and fairly familiar with Java (I use each nearly every day). I have used python for scripts, but have never tried a large, complex project until now.

I am having a hard time wrapping my head around the way python handles package imports. I have search and read several other answers, but still can't get my specific case to work.  I would imagine my error is due to bad or non-pythonic design, but I feel like what I'm doing is such a common practice in other languages I have worked with, that it should be simple.

I have the following directory tree

```<code>+ project (project directory)
    + replicator (source directory)
        + adapters
            - __init__.py
            - wwf_score.py
            - other_adpater.py (there will be many adapter modules in this package)
        - sources.py
        - __init__.py (empty init for replicator)
</code>```

I am looking for a modular design where I can instantiate specific adapters on the fly. Those adapters extend an abc.ABC abstract class in adapters.__init__ which also holds some common utilities for adapters.

Pretty simple.

The issue is that the individual adapter modules need to reference some definitions in replicator.sources. Specifically two classes. What is happening is that each adapter grabs data from a third party and hydrates a RawSource object, which is defined in replicator.sources

wwf_score.py

```<code>import replicator.adapters as adapters
import replicator.sources as sources

@adapters.source_adapter
class WWFScoreAdapter(adapters.AbstractAdapter):
    def __init__(self, data):
        self.data = sources.RawData(data)
</code>```

This throws an error that AttributeError: module 'replicator' has no attribute 'adapters'

I have tried adding an import to replicators.__init__, and have tried relative imports and several other things.

What am I doing wrong?

Thank you all!

EDIT

It appears my real problem is in a specific adapter importing something from the adapters.__init__ or in (somehow) actually registering the adapters package with the replicator. I can import from replicator.sources inside wwf_score.py, it appears. Maybe that helps.

EDIT Updated for clarity and readability.

答:
I found a solution, but would still be open to thoughts on better design

As I expected, my issue was in poor design and not understanding imports. I was trying to do actual definitions inside some of the __init__ files, and referencing those definitions outside the package. It led to spaghetti code. I ended up solving this problem by doing two things:

1. Smaller, clearer modules
I removed all the definitions from the __init__ files and gave them their own modules. One of these included a decorator that was a callable class bound to an attribute that wasn't available outside the init file. I'm not sure exactly how, but I am sure that was muddying things a lot.

My new structure looks like this (if anyone cares)

```<code>+ project
    + bin
        - replicator.py (script that uses the rest)
    + replicator
        + adapters
            - __init__.py (blank except to import modules)
            - contracts.py (pulled from init, includes Abstract)
            - registry.py (has a class decorator bound to attribute)
            - wwf_score.py (class that extends Abstract)
            - other_adapter.py (another class that extends Abstract)
        - sources.py (the same, just some dtos)
        - __init__.py (empty except for imports)
</code>```

2. I used all relative imports inside the package
So, my wwf_score.py imports look like

```<code>from . import contracts
from . import registry
from .. import sources
</code>```

My bin/replicator.py file can reference things via

```<code>import replicator.adapters as adapters
import replicator.sources as sources
</code>```

And all is well.

I hope this helps someone in the future. I'm free to answer questions about my setup and what I found.

Like I said, part of my problem is that I was doing something else complicated -- a class-based decorator that decorated a class. This was used to register all my individual adapters with a registry (and a key), so I could use a factory to create them.

Thanks.

Title: Sub package imports with python

Body:
I am new to python, but very experienced with PHP and JavaScript and fairly familiar with Java (I use each nearly every day). I have used python for scripts, but have never tried a large, complex project until now.

I am having a hard time wrapping my head around the way python handles package imports. I have search and read several other answers, but still can't get my specific case to work.  I would imagine my error is due to bad or non-pythonic design, but I feel like what I'm doing is such a common practice in other languages I have worked with, that it should be simple.

I have the following directory tree

+ project (project directory)
    + replicator (source directory)
        + adapters
            - __init__.py
            - wwf_score.py
            - other_adpater.py (there will be many adapter modules in this package)
        - sources.py
        - __init__.py (empty init for replicator)

I am looking for a modular design where I can instantiate specific adapters on the fly. Those adapters extend an abc.ABC abstract class in adapters.__init__ which also holds some common utilities for adapters.

Pretty simple.

The issue is that the individual adapter modules need to reference some definitions in replicator.sources. Specifically two classes. What is happening is that each adapter grabs data from a third party and hydrates a RawSource object, which is defined in replicator.sources

wwf_score.py

import replicator.adapters as adapters
import replicator.sources as sources

@adapters.source_adapter
class WWFScoreAdapter(adapters.AbstractAdapter):
    def __init__(self, data):
        self.data = sources.RawData(data)

This throws an error that AttributeError: module 'replicator' has no attribute 'adapters'

I have tried adding an import to replicators.__init__, and have tried relative imports and several other things.

What am I doing wrong?

Thank you all!

EDIT

It appears my real problem is in a specific adapter importing something from the adapters.__init__ or in (somehow) actually registering the adapters package with the replicator. I can import from replicator.sources inside wwf_score.py, it appears. Maybe that helps.

EDIT Updated for clarity and readability.

Body:
I found a solution, but would still be open to thoughts on better design

As I expected, my issue was in poor design and not understanding imports. I was trying to do actual definitions inside some of the __init__ files, and referencing those definitions outside the package. It led to spaghetti code. I ended up solving this problem by doing two things:

1. Smaller, clearer modules
I removed all the definitions from the __init__ files and gave them their own modules. One of these included a decorator that was a callable class bound to an attribute that wasn't available outside the init file. I'm not sure exactly how, but I am sure that was muddying things a lot.

My new structure looks like this (if anyone cares)

+ project
    + bin
        - replicator.py (script that uses the rest)
    + replicator
        + adapters
            - __init__.py (blank except to import modules)
            - contracts.py (pulled from init, includes Abstract)
            - registry.py (has a class decorator bound to attribute)
            - wwf_score.py (class that extends Abstract)
            - other_adapter.py (another class that extends Abstract)
        - sources.py (the same, just some dtos)
        - __init__.py (empty except for imports)

2. I used all relative imports inside the package
So, my wwf_score.py imports look like

from . import contracts
from . import registry
from .. import sources

My bin/replicator.py file can reference things via

import replicator.adapters as adapters
import replicator.sources as sources

And all is well.

I hope this helps someone in the future. I'm free to answer questions about my setup and what I found.

Like I said, part of my problem is that I was doing something else complicated -- a class-based decorator that decorated a class. This was used to register all my individual adapters with a registry (and a key), so I could use a factory to create them.

Thanks.


问:
Best way of chaining reduce with Java 8
I have the following code that I'm trying to improve:

```<code>BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);
</code>```

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

答:
If you could add the following method to the Associates class:

```<code>public BigDecimal getSubtotal() {
    return propertyA.add(propertyB).add(propertyC).add(propertyD);
}
</code>```

Then, doing the task would be easy:

```<code>BigDecimal total = entity.getAssociate().stream()
    .map(Associate::getSubtotal)
    .reduce(BigDecimal::add)
    .orElse(BigDecimal.ZERO);
</code>```

Title: Best way of chaining reduce with Java 8

Body:
I have the following code that I'm trying to improve:

BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

Body:
If you could add the following method to the Associates class:

public BigDecimal getSubtotal() {
    return propertyA.add(propertyB).add(propertyC).add(propertyD);
}

Then, doing the task would be easy:

BigDecimal total = entity.getAssociate().stream()
    .map(Associate::getSubtotal)
    .reduce(BigDecimal::add)
    .orElse(BigDecimal.ZERO);


问:
Return type with generic with bounds
I have the following code

```<code>import scala.concurrent.Future

class RequestType
class Read extends RequestType
class Write extends RequestType

object Main {
  def main(args: Array[String]): Unit = {
  }

  def dbrequest[T <: RequestType](t: T): Future[T] = {
    val dBRequest = new DBRequest
    t match {
      case r: Read => dBRequest.read(r)
      case w: Write => dBRequest.write(w)
   }
  }
}

class DBRequest {
  def read(r: Read): Future[Read] = {
    Future(r)
  }

  def write(w: Write): Future[Write] = {
   Future(w)
  }
}
</code>```

read and write method return a Future of type RequestType. If T is bounded and Future is covariant, then why is the compiler failing to conform type of Future[Read] or Future[Write] to Future[T]

答:
Your code will compile with one small change.

```<code>def dbrequest[T <: RequestType](t: T): Future[RequestType] = {
</code>```

So why is it that returning Future[RequestType] works and returning Future[T] doesn't, especially since T is bounded the way it is?

Think of it this way: T is resolved at compile time. With every invocation of dbrequest() the compiler turns T into either Read or Write. The match statement, on the other hand, is resolved at run time. So from the compiler's perspective the match statement returns both Read and Write.

As has been pointed out, you don't really need a type parameter in this code, as presented. The following simplification is equivalent.

```<code>def dbrequest(t: RequestType): Future[RequestType] = {
</code>```

Title: Return type with generic with bounds

Body:
I have the following code

import scala.concurrent.Future

class RequestType
class Read extends RequestType
class Write extends RequestType

object Main {
  def main(args: Array[String]): Unit = {
  }

  def dbrequest[T <: RequestType](t: T): Future[T] = {
    val dBRequest = new DBRequest
    t match {
      case r: Read => dBRequest.read(r)
      case w: Write => dBRequest.write(w)
   }
  }
}

class DBRequest {
  def read(r: Read): Future[Read] = {
    Future(r)
  }

  def write(w: Write): Future[Write] = {
   Future(w)
  }
}

read and write method return a Future of type RequestType. If T is bounded and Future is covariant, then why is the compiler failing to conform type of Future[Read] or Future[Write] to Future[T]

Body:
Your code will compile with one small change.

def dbrequest[T <: RequestType](t: T): Future[RequestType] = {

So why is it that returning Future[RequestType] works and returning Future[T] doesn't, especially since T is bounded the way it is?

Think of it this way: T is resolved at compile time. With every invocation of dbrequest() the compiler turns T into either Read or Write. The match statement, on the other hand, is resolved at run time. So from the compiler's perspective the match statement returns both Read and Write.

As has been pointed out, you don't really need a type parameter in this code, as presented. The following simplification is equivalent.

def dbrequest(t: RequestType): Future[RequestType] = {


问:
Pandas - Drop function error (label not contained in axis)
I have a CSV file that is as the following:

```<code>index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121
</code>```

Based off my question here I am able to add some relevant information to this csv via this short script:

```<code>import pandas as pd

df = pd.read_csv('newdata.csv')
print(df)

df_out = pd.concat([df.set_index('index'),df.set_index('index').agg(['max','min','mean'])]).rename(index={'max':'Max','min':'Min','mean':'Average'}).reset_index()

with open('newdata.csv', 'w') as f:
    df_out.to_csv(f,index=False)
</code>```

This results in this CSV:

```<code>index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121
Max,57.11,40.102,60.20121
Min,55.1134,35.129404123,60.1039
Average,56.1378,38.1181347077,60.16837
</code>```

I would like to now have it so I can update this csv. For example if I ran a new build (build4 for instance) I could add that in and then redo the Max, Min, Average rows. My idea is that I therefore delete the rows with labels Max, Min, Average, add my new row, redo the stats. I believe the code I need is as simple as (just for Max but would have lines for Min and Average as well):

```<code>df = pd.read_csv('newdata.csv')
df = df.drop('Max')
</code>```

However this always results in an ValueError: labels ['Max'] not contained in axis

I have created the csv files in sublime text, could this be part of the issue? I have read other SO posts about this and none seem to help my issue.

I am unsure if this allowed but here is a download link to my csv just in case something is wrong with the file itself.

I would be okay with two possible answers:

How to fix this drop issue

How to add more builds and update the statistics (a method without drop)

答:
You must specify the axis argument. default is axis = 0 which is rows columns is axis = 1.

so this should be your code.

```<code>df = df.drop('Max',axis=1)
</code>```

edit:
looking at this piece of code:

```<code>df = pd.read_csv('newdata.csv')
df = df.drop('Max')
</code>```

The code you used does not specify that the first column of the csv file contains the index for the dataframe. Thus pandas creates an index on the fly. This index is purely a numerical one. So your index does not contain "Max".

try the following:

```<code>df = pd.read_csv("newdata.csv",index_col=0)
df = df.drop("Max",axis=0)
</code>```

This forces pandas to use the first column in the csv file to be used as index. This should mean the code works now.

Body:
I have a CSV file that is as the following:

index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121

Based off my question here I am able to add some relevant information to this csv via this short script:

import pandas as pd

df = pd.read_csv('newdata.csv')
print(df)

df_out = pd.concat([df.set_index('index'),df.set_index('index').agg(['max','min','mean'])]).rename(index={'max':'Max','min':'Min','mean':'Average'}).reset_index()

with open('newdata.csv', 'w') as f:
    df_out.to_csv(f,index=False)

This results in this CSV:

index,Avg,Min,Max
Build1,56.19,39.123,60.1039
Build2,57.11,40.102,60.2
Build3,55.1134,35.129404123,60.20121
Max,57.11,40.102,60.20121
Min,55.1134,35.129404123,60.1039
Average,56.1378,38.1181347077,60.16837

I would like to now have it so I can update this csv. For example if I ran a new build (build4 for instance) I could add that in and then redo the Max, Min, Average rows. My idea is that I therefore delete the rows with labels Max, Min, Average, add my new row, redo the stats. I believe the code I need is as simple as (just for Max but would have lines for Min and Average as well):

df = pd.read_csv('newdata.csv')
df = df.drop('Max')

However this always results in an ValueError: labels ['Max'] not contained in axis

I have created the csv files in sublime text, could this be part of the issue? I have read other SO posts about this and none seem to help my issue.

I am unsure if this allowed but here is a download link to my csv just in case something is wrong with the file itself.

I would be okay with two possible answers:

How to fix this drop issue

How to add more builds and update the statistics (a method without drop)

Body:
You must specify the axis argument. default is axis = 0 which is rows columns is axis = 1.

so this should be your code.

df = df.drop('Max',axis=1)

edit:
looking at this piece of code:

df = pd.read_csv('newdata.csv')
df = df.drop('Max')

The code you used does not specify that the first column of the csv file contains the index for the dataframe. Thus pandas creates an index on the fly. This index is purely a numerical one. So your index does not contain "Max".

try the following:

df = pd.read_csv("newdata.csv",index_col=0)
df = df.drop("Max",axis=0)

This forces pandas to use the first column in the csv file to be used as index. This should mean the code works now.


问:
How to fill image without stretching the image
Site URL: http://theneonplanet.com.au/home-2-2/

Hi, I am working on this wordpress website. I use divi theme but I manually change things with css.

second section image

this is currently placed in the recent stories section.

The problem is that the post image is placed correctly but it is stretched inside the div and it looks very strange; the picture is not suppose to be this thin.
I want the image to be filled inside the div. which means it doen't need to be the same width of the div but it has to fill the space.

is there any code solution for this?
I tried object-fit, and min and max height. both didn't work..

答: use  background-size: cover; attribute in your css for the background image


问:
Directing script output to a file using subprocess?
From within a python script ("main.py"), I am using the subprocess module to run another script ("sub_script.py").

Here's the code in the "main.py" script that 'runs' "sub_script.py":

```<code>subprocess.Popen([sys.executable, "sub_script.py"])
</code>```

this works fine as long as "sub_script.py" does not have any "print" statements in it.

I now want to channel all the output of "sub_script.py" to an external file ("log.txt").

How do I do it?

答:
```<code>subprocess.Popen([sys.executable, "sub_script.py"], stdout=open("log.txt", "a"))
</code>```

Body:
From within a python script ("main.py"), I am using the subprocess module to run another script ("sub_script.py").

Here's the code in the "main.py" script that 'runs' "sub_script.py":

subprocess.Popen([sys.executable, "sub_script.py"])

this works fine as long as "sub_script.py" does not have any "print" statements in it.

I now want to channel all the output of "sub_script.py" to an external file ("log.txt").

How do I do it?


问:
SpringBoot @RequestBody pojo not mapping to my json
Can anyone help me fix this. I have hard coded json object which is suppposed to map to my POJO but I'm getting null values in my Spring Controller. I've checked my getters and setters. They seems to be correct. What am i doing wrong here ?

Controller

```<code>@PostMapping("/dashboard")
public Dashboard getDashboard(@RequestBody PaginationRequest paginationRequest) {
      return topcatService.getDashboard(paginationRequest);
}
</code>```

json

```<code> var paginationRequest = { grouping  : e.target.value ,total : "1", currentPage : "1", pageSize : "5"};
</code>```

POJO

```<code> public class PaginationRequest {
        private String grouping;
        private String total;
        private String  currentPage;
        private String pageSize;

       //setter/getter
    }
</code>```

答:
I'll try to suggest some small changes,</p>

```<code>@RequestMapping(value = "/dashboard", method = RequestMethod.POST,
                consumes = "application/json", produces = "application/json")
public Dashboard getDashboard(@RequestBody PaginationRequest paginationRequest) {
</code>```

Body:
Can anyone help me fix this. I have hard coded json object which is suppposed to map to my POJO but I'm getting null values in my Spring Controller. I've checked my getters and setters. They seems to be correct. What am i doing wrong here ?

Controller

@PostMapping("/dashboard")
public Dashboard getDashboard(@RequestBody PaginationRequest paginationRequest) {
      return topcatService.getDashboard(paginationRequest);
}

json

 var paginationRequest = { grouping  : e.target.value ,total : "1", currentPage : "1", pageSize : "5"};

POJO

 public class PaginationRequest {
        private String grouping;
        private String total;
        private String  currentPage;
        private String pageSize;

       //setter/getter
    }

Body:
I'll try to suggest some small changes,

@RequestMapping(value = "/dashboard", method = RequestMethod.POST,
                consumes = "application/json", produces = "application/json")
public Dashboard getDashboard(@RequestBody PaginationRequest paginationRequest) {


问:
Styles from generic.xaml are not applied
I made a class library assembly in which I created custom controls, and I defined the default styles in the generic.xaml file.

It seems this is a quite common problem, as long as many people are posting about it.
However I couldn't find any useful answer for my case.

the generic.xaml is in the Themes folder.

the generix.xaml file Build Action is set to Page.

the ThemeInfo is properly defined in my AssemblyInfo.cs.

In my test application, if I manually merge the generic.xaml file from my custom controls assembly into the application App.xaml file like this:

```<code><Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="/MyControlsAssembly;component/Themes/generic.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>
</code>```

then the custom controls are properly themed, but if I do not manually merge the generic.xaml, the controls appear with the default Windows theme.

Could you please tell me what am I forgetting and/or doing wrong ?

Additional info:

My ThemeInfo assembly attribute is defined as follow:

[assembly: ThemeInfo(ResourceDictionaryLocation.SourceAssembly, ResourceDictionaryLocation.SourceAssembly)]

(Note: the result is just the same with any combination of parameters for the ThemeInfo attribute)

There are two others .xaml files beside the generic.xaml file in the Themes folder.

There is a subfolder in the Themes folder that itself contains another .xaml file.

答:
Not sure if this works in WPF, but it works for me in Silverlight:

Constructor:

```<code>public class MyCustomControl : Control
{
    static MyCustomControl()
    {
        this.Style = (Style)Application.Current.Resources["MyCustomControlStyle"];
    }
}
</code>```

Style:

```<code><Style x:Key="MyCustomControlStyle" TargetType="{local:MyCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{local:MyCustomControl}">
                <Border>
                    <Label>Testing...</Label>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
I made a class library assembly in which I created custom controls, and I defined the default styles in the generic.xaml file.

It seems this is a quite common problem, as long as many people are posting about it.
However I couldn't find any useful answer for my case.

the generic.xaml is in the Themes folder.

the generix.xaml file Build Action is set to Page.

the ThemeInfo is properly defined in my AssemblyInfo.cs.

In my test application, if I manually merge the generic.xaml file from my custom controls assembly into the application App.xaml file like this:

<Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="/MyControlsAssembly;component/Themes/generic.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>

then the custom controls are properly themed, but if I do not manually merge the generic.xaml, the controls appear with the default Windows theme.

Could you please tell me what am I forgetting and/or doing wrong ?

Additional info:

My ThemeInfo assembly attribute is defined as follow:

[assembly: ThemeInfo(ResourceDictionaryLocation.SourceAssembly, ResourceDictionaryLocation.SourceAssembly)]

(Note: the result is just the same with any combination of parameters for the ThemeInfo attribute)

There are two others .xaml files beside the generic.xaml file in the Themes folder.

There is a subfolder in the Themes folder that itself contains another .xaml file.

Body:
Not sure if this works in WPF, but it works for me in Silverlight:

Constructor:

public class MyCustomControl : Control
{
    static MyCustomControl()
    {
        this.Style = (Style)Application.Current.Resources["MyCustomControlStyle"];
    }
}

Style:

<Style x:Key="MyCustomControlStyle" TargetType="{local:MyCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{local:MyCustomControl}">
                <Border>
                    <Label>Testing...</Label>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>