问:
Ajax operation running later than javascript function
I am building a django project which is a website sending form to server and server responds with the queryset just registered by the form and a message string "Create new event successful.".

This is code for it:

listevent is another javascript function which shows the queryset the server just received to "sidebar" div. After that, by document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );, appends the message above the result.

Javascript

```<code>function makeEvent(event){
            event.preventDefault();
            var year = event.target.childNodes[3].children[0].value.slice(0,4);
            var month = event.target.childNodes[3].children[0].value.slice(5,7);
            var day = event.target.childNodes[3].children[0].value.slice(8,10);
            var form = $("#makeEventForm");
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
                success: function(response){
                    console.log(response);
                    listevent(year, month, day);
                    document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );
                },
                error: function(request,status,error){
                    if (request.status == 599) {
                        listevent(year, month, day);
                        document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Error : time overlaps with another event" );
                    } else {
                        alert("code:"+request.status+"\n"+"message:"+status+"\n"+"error:"+error);
                    }
                },
            });
        }
</code>```

The problem is, when this makeEventfunction ran and ajax operation successfully done, second line of success function(listevent(year, month, day);) seems to run later than third line. As a result, "Create new event successful" does not displayed, because listevent function overwrites all contents in sidebar div.

So I tried using setTimeout on the third line, but it seems like does not work at all time. It'll work if I set the time value sufficiently big, but It looks so bad.

So, my question is:

1. Second line of success function looks like running later than third line, is that right?

2. If so, to third line run after second line ended running, what should I do?

Edit

listevent function

```<code>function listevent(year, month, day){
            $.ajax({
                type: "POST",
                url: "{% url 'listevent' %}",
                data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                dataType: "json",
                success: function(response){
                    $("#sidebar").attr('year', year);
                    $("#sidebar").attr('month', month);
                    $("#sidebar").attr('day', day);
                    events = JSON.parse(response.events)
                    var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"
                    if(events.length > 0){
                         events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));
                    } else {
                        str += "No events currently."
                    }
                    $("#sidebar").html(str);
                    var btn = $("<button></button>").html("New event");
                    btn.click(function(){
                        makeEventClick(day);
                    });
                    $("#sidebar").append(btn);
                },
                error: function(request,status,error){
                       console.log(error);
                },
            });
        }
</code>```

答:
It's obvious because inside listevent() you are calling an Async AJAX so it'll run in parallel and obviously will result later than the script response so the script will be executed first, then the ajax response will come and will come into the effect.

To fix you can use async:false is the ajax method. This will force the script to wait until the ajax returns response. But this is not a good practice.

```<code>function listevent(year, month, day){
        $.ajax({
            type: "POST",
            url: "{% url 'listevent' %}",
            async:false, // added
            data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            dataType: "json",
            success: function(response){
                $("#sidebar").attr('year', year);
                $("#sidebar").attr('month', month);
                $("#sidebar").attr('day', day);
                events = JSON.parse(response.events)
                var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"
                if(events.length > 0){
                     events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));
                } else {
                    str += "No events currently."
                }
                $("#sidebar").html(str);
                var btn = $("<button></button>").html("New event");
                btn.click(function(){
                    makeEventClick(day);
                });
                $("#sidebar").append(btn);
            },
            error: function(request,status,error){
                   console.log(error);
            },
        });
    }
</code>```

So as a good practice, you can move the next line inside the listevent().

```<code>function listevent(year, month, day){
        $.ajax({
            type: "POST",
            url: "{% url 'listevent' %}",
            data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            dataType: "json",
            success: function(response){
                $("#sidebar").attr('year', year);
                $("#sidebar").attr('month', month);
                $("#sidebar").attr('day', day);
                events = JSON.parse(response.events)
                var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"
                if(events.length > 0){
                     events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));
                } else {
                    str += "No events currently."
                }
                $("#sidebar").html(str);
                var btn = $("<button></button>").html("New event");
                btn.click(function(){
                    makeEventClick(day);
                });
                $("#sidebar").append(btn);
                document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." ); // Added
            },
            error: function(request,status,error){
                   console.log(error);
            },
        });
    }
</code>```

Body:
I am building a django project which is a website sending form to server and server responds with the queryset just registered by the form and a message string "Create new event successful.".

This is code for it:

listevent is another javascript function which shows the queryset the server just received to "sidebar" div. After that, by document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );, appends the message above the result.

Javascript

function makeEvent(event){
            event.preventDefault();
            var year = event.target.childNodes[3].children[0].value.slice(0,4);
            var month = event.target.childNodes[3].children[0].value.slice(5,7);
            var day = event.target.childNodes[3].children[0].value.slice(8,10);
            var form = $("#makeEventForm");
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
                success: function(response){
                    console.log(response);
                    listevent(year, month, day);
                    document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );
                },
                error: function(request,status,error){
                    if (request.status == 599) {
                        listevent(year, month, day);
                        document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Error : time overlaps with another event" );
                    } else {
                        alert("code:"+request.status+"\n"+"message:"+status+"\n"+"error:"+error);
                    }
                },
            });
        }

The problem is, when this makeEventfunction ran and ajax operation successfully done, second line of success function(listevent(year, month, day);) seems to run later than third line. As a result, "Create new event successful" does not displayed, because listevent function overwrites all contents in sidebar div.

So I tried using setTimeout on the third line, but it seems like does not work at all time. It'll work if I set the time value sufficiently big, but It looks so bad.

So, my question is:

1. Second line of success function looks like running later than third line, is that right?

2. If so, to third line run after second line ended running, what should I do?

Edit

listevent function

function listevent(year, month, day){
            $.ajax({
                type: "POST",
                url: "{% url 'listevent' %}",
                data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                dataType: "json",
                success: function(response){
                    $("#sidebar").attr('year', year);
                    $("#sidebar").attr('month', month);
                    $("#sidebar").attr('day', day);
                    events = JSON.parse(response.events)
                    var str = "
"+year+"/"+month+"/"+day+"

"
                    if(events.length > 0){
                         events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"
"));
                    } else {
                        str += "No events currently."
                    }
                    $("#sidebar").html(str);
                    var btn = $("<button></button>").html("New event");
                    btn.click(function(){
                        makeEventClick(day);
                    });
                    $("#sidebar").append(btn);
                },
                error: function(request,status,error){
                       console.log(error);
                },
            });
        }

Body:
It's obvious because inside listevent() you are calling an Async AJAX so it'll run in parallel and obviously will result later than the script response so the script will be executed first, then the ajax response will come and will come into the effect.

To fix you can use async:false is the ajax method. This will force the script to wait until the ajax returns response. But this is not a good practice.

function listevent(year, month, day){
        $.ajax({
            type: "POST",
            url: "{% url 'listevent' %}",
            async:false, // added
            data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            dataType: "json",
            success: function(response){
                $("#sidebar").attr('year', year);
                $("#sidebar").attr('month', month);
                $("#sidebar").attr('day', day);
                events = JSON.parse(response.events)
                var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"
                if(events.length > 0){
                     events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));
                } else {
                    str += "No events currently."
                }
                $("#sidebar").html(str);
                var btn = $("<button></button>").html("New event");
                btn.click(function(){
                    makeEventClick(day);
                });
                $("#sidebar").append(btn);
            },
            error: function(request,status,error){
                   console.log(error);
            },
        });
    }

So as a good practice, you can move the next line inside the listevent().

function listevent(year, month, day){
        $.ajax({
            type: "POST",
            url: "{% url 'listevent' %}",
            data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            dataType: "json",
            success: function(response){
                $("#sidebar").attr('year', year);
                $("#sidebar").attr('month', month);
                $("#sidebar").attr('day', day);
                events = JSON.parse(response.events)
                var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"
                if(events.length > 0){
                     events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));
                } else {
                    str += "No events currently."
                }
                $("#sidebar").html(str);
                var btn = $("<button></button>").html("New event");
                btn.click(function(){
                    makeEventClick(day);
                });
                $("#sidebar").append(btn);
                document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." ); // Added
            },
            error: function(request,status,error){
                   console.log(error);
            },
        });
    }


来源: stackexchange

问:
Can someone explain the parameter void(*pfn)(void*)?
I've come across this piece of code

```<code>inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
</code>```

I don't understand this part

```<code>void(*pfn)(void*)
</code>```

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

答:
These things are easiest read inside out:

(*pfn) => "pfn is a pointer"

void x(void*) => "x is a function accepting a void * argument and returning void"

Put them together and you have:

"pfn is a pointer to a function accepting a void * argument and returning void"

Note that the parens around (*pfn) are necessary because of precedence. void *pfn(void*) would be interpreted as if it were written (void *)pfn(void *): "pfn is a function that accepts a void * and returns a void *".

ContentLicense: CC BY-SA 3.0

Body:
I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?


问:
Add see more option to the server data in angular 8
I am facing an issue with my project.

I want to add see more option to a paragraph and that paragraph's data is coming from a server.

I know how to add see more option to HTML paragraph, but I don't know how to add see more option to the data that is coming from the server.

```<code><p>Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas <span id="dots">...</span>
<span id="more">Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas .</span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>
</code>```

JavaScript code

```<code><script>
function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
</script>
</code>```

So you can see above I tried above code for a paragraph and it is working fine for me.

but in my project, the HTML component is as below.

```<code><div  class="col-12 col-lg-12" *ngFor="let post of rec?.attributes?.Postings | filter : searchText | filter:filterText; let i=index">
<div class="col-12 noRightPadding" style="overflow-wrap: break-word;white-space: pre-line;word-break:break-all;
">{{post?.attributes?.Message}} </div>
</div>
</code>```

you can see the paragraph is coming as post.attributes.Message and I don't have an idea how to add see more option for this if it exceeds more than two lines.

can anyone help me with this?

答:
You can do something like:

```<code><p class="text-center">{{ post.attributes.Message.length <= 50 ? post.attributes.Message : post.attributes.Message.substring(0, 50) + '...' }}</p>
</code>```

if your text contain more than 50 characters then it will only display 50 characters.

ContentLicense: CC BY-SA 4.0

Body:
I am facing an issue with my project.

I want to add see more option to a paragraph and that paragraph's data is coming from a server.

I know how to add see more option to HTML paragraph, but I don't know how to add see more option to the data that is coming from the server.

Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas ...
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas Jayesh Vyas
Jayesh Vyas Jayesh Vyas Jayesh Vyas .

<button onclick="myFunction()" id="myBtn">Read more</button>

JavaScript code

So you can see above I tried above code for a paragraph and it is working fine for me.

but in my project, the HTML component is as below.

{{post?.attributes?.Message}}

you can see the paragraph is coming as post.attributes.Message and I don't have an idea how to add see more option for this if it exceeds more than two lines.

can anyone help me with this?

Body:
You can do something like:

<p class="text-center">{{ post.attributes.Message.length <= 50 ? post.attributes.Message : post.attributes.Message.substring(0, 50) + '...' }}</p>

if your text contain more than 50 characters then it will only display 50 characters.


问:
parSequence and parTraverse in tagless final
Using tagless final (without using IO, but rather a generic F) how can I abstract over something like this:

```<code>def doSomething(s: String): IO[Unit] = ???

List("authMethods", "secretEngines", "plugins", "CAs", "common").parTraverse(doSomething)
</code>```

The closest I can get is using parTraverseN from the Concurrent object, but I assume this will run concurrently instead of in parallel (as in parallelism). It also forces me to choose an n where as parTraverse does not.

The size of the list is just an example, it could be way bigger. doSomething is a pure function, multiple executions of it can run in parallel without problems.

Ideally, given that doSomething returns IO[Unit] I would like to abstract over parTraverse_ to an F with the correct typeclass instance.

答:
Here's a similar complete working example:

```<code>import cats.Applicative
import cats.instances.list._
import cats.syntax.foldable._

trait Service[F[_]] {
  val items = List("authMethods", "secretEngines", "plugins", "CAs", "common")

  def doSomething(s: String): F[Unit] = ???

  def result(implicit F: Applicative[F]): F[Unit] =
    items.traverse_(doSomething)
}
</code>```

If you want to use parTraverse_ here, the minimal changes necessary would look something like this:

```<code>import cats.{Applicative, Parallel}
import cats.instances.list._
import cats.syntax.parallel._

trait Service[F[_]] {
  val items = List("authMethods", "secretEngines", "plugins", "CAs", "common")

  def doSomething(s: String): F[Unit] = ???

  def result(implicit F: Applicative[F], P: Parallel[F]): F[Unit] =
    items.parTraverse_(doSomething)
}
</code>```

Alternatively you could use Parallel.parTraverse_(items)(doSomething) and skip the syntax import. Both approaches require a Foldable instance for List (provided here by the cats.instances.list._ import, which will no longer be necessary in Cats 2.2.0), and a Parallel instance for F, which you get via the P constraint.

(Note that the Applicative constraint on result is no longer necessary in the second version, but that's only because this is a very simple example—I'm assuming your real code relies on something like Sync instead, and will need both that and Parallel.)

This answer needs a couple of footnotes, though. The first is that it might not actually be a good thing that parTraverse_ doesn't make you specify a bound in the way that parTraverseN does, and may result in excessive memory use, etc. (but this will depend on e.g. the expected size of your lists and the kind of work doSomething is doing, and is probably outside the scope of the question).

The second footnote is that "parallel" in the sense of the Parallel type class is more general than the "parallel" in the parallel-vs.-concurrent distinction in the Cats "Concurrency Basics" document. The Parallel type class models a very generic kind of logical parallelism that also encompasses error accumulation, for example. So when you write:

I assume this will run concurrently instead of in parallel (as in parallelism).

…your assumption is correct, but not exactly because the parTraverseN method is on Concurrent instead of Parallel; note that Concurrent.parTraverseN still requires a Parallel instance. When you see par or the Parallel type class in the context of cats.effect.Concurrent, you should think of concurrency, not "parallelism" in the "Concurrency Basics" sense.

Body:
Using tagless final (without using IO, but rather a generic F) how can I abstract over something like this:

def doSomething(s: String): IO[Unit] = ???

List("authMethods", "secretEngines", "plugins", "CAs", "common").parTraverse(doSomething)

The closest I can get is using parTraverseN from the Concurrent object, but I assume this will run concurrently instead of in parallel (as in parallelism). It also forces me to choose an n where as parTraverse does not.

The size of the list is just an example, it could be way bigger. doSomething is a pure function, multiple executions of it can run in parallel without problems.

Ideally, given that doSomething returns IO[Unit] I would like to abstract over parTraverse_ to an F with the correct typeclass instance.

Body:
Here's a similar complete working example:

import cats.Applicative
import cats.instances.list._
import cats.syntax.foldable._

trait Service[F[_]] {
  val items = List("authMethods", "secretEngines", "plugins", "CAs", "common")

  def doSomething(s: String): F[Unit] = ???

  def result(implicit F: Applicative[F]): F[Unit] =
    items.traverse_(doSomething)
}

If you want to use parTraverse_ here, the minimal changes necessary would look something like this:

import cats.{Applicative, Parallel}
import cats.instances.list._
import cats.syntax.parallel._

trait Service[F[_]] {
  val items = List("authMethods", "secretEngines", "plugins", "CAs", "common")

  def doSomething(s: String): F[Unit] = ???

  def result(implicit F: Applicative[F], P: Parallel[F]): F[Unit] =
    items.parTraverse_(doSomething)
}

Alternatively you could use Parallel.parTraverse_(items)(doSomething) and skip the syntax import. Both approaches require a Foldable instance for List (provided here by the cats.instances.list._ import, which will no longer be necessary in Cats 2.2.0), and a Parallel instance for F, which you get via the P constraint.

(Note that the Applicative constraint on result is no longer necessary in the second version, but that's only because this is a very simple example—I'm assuming your real code relies on something like Sync instead, and will need both that and Parallel.)

This answer needs a couple of footnotes, though. The first is that it might not actually be a good thing that parTraverse_ doesn't make you specify a bound in the way that parTraverseN does, and may result in excessive memory use, etc. (but this will depend on e.g. the expected size of your lists and the kind of work doSomething is doing, and is probably outside the scope of the question).

The second footnote is that "parallel" in the sense of the Parallel type class is more general than the "parallel" in the parallel-vs.-concurrent distinction in the Cats "Concurrency Basics" document. The Parallel type class models a very generic kind of logical parallelism that also encompasses error accumulation, for example. So when you write:

I assume this will run concurrently instead of in parallel (as in parallelism).

…your assumption is correct, but not exactly because the parTraverseN method is on Concurrent instead of Parallel; note that Concurrent.parTraverseN still requires a Parallel instance. When you see par or the Parallel type class in the context of cats.effect.Concurrent, you should think of concurrency, not "parallelism" in the "Concurrency Basics" sense.


问:
Subscribing to multiple observables sequentially with Rxjs
I am trying to make a http request only when my form is dirty. I tried using zip but it will still make the http request regardless as the pipe results will only apply on the subscribe block. Is there anyway for me to NOT nest the observables as I have to subscribe to another observable after the http call which will result is 3 nested layers of observable.

```<code>  @ViewChild('form')
  form: NgForm;

  // only take events when form is dirty
  const formValueChanges$ = this.form.valueChanges
    .pipe(
      debounceTime(500),
      filter(() => this.form.dirty),
      takeUntil(this._destroy$),
      distinctUntilChanged(),
      tap(result => {
        console.log(result);
      })
    );

  // http request returning an observable
  const updateForm$ = this.tempService.update();

  zip(formValueChanges$, updateForm$)
    .subscribe((response) => {
        console.log(response);
      }
    );
</code>```

Intended Behaviour

```<code>this.form.valueChanges
  .pipe(
     debounceTime(500),
     filter(() => this.form.dirty),
     takeUntil(this._destroy$),
     distinctUntilChanged(),
  ).subscribe(() => {
     console.log("SAVED");
     this.tempService.update().subscribe();
  });
</code>```

答:
You can use concatMap operator to be sure of the order, concatMap will wait for previous HTTP Observable to complete before mapping the new value from the form.

```<code>this.form.valueChanges
 .pipe(
  debounceTime(500),
  filter(() => this.form.dirty),
  takeUntil(this._destroy$),
  distinctUntilChanged(),
  concatMap(val => this.tempService.update())
).subscribe(console.log);
</code>```

Body:
I am trying to make a http request only when my form is dirty. I tried using zip but it will still make the http request regardless as the pipe results will only apply on the subscribe block. Is there anyway for me to NOT nest the observables as I have to subscribe to another observable after the http call which will result is 3 nested layers of observable.

  @ViewChild('form')
  form: NgForm;

  // only take events when form is dirty
  const formValueChanges$ = this.form.valueChanges
    .pipe(
      debounceTime(500),
      filter(() => this.form.dirty),
      takeUntil(this._destroy$),
      distinctUntilChanged(),
      tap(result => {
        console.log(result);
      })
    );

  // http request returning an observable
  const updateForm$ = this.tempService.update();

  zip(formValueChanges$, updateForm$)
    .subscribe((response) => {
        console.log(response);
      }
    );

Intended Behaviour

this.form.valueChanges
  .pipe(
     debounceTime(500),
     filter(() => this.form.dirty),
     takeUntil(this._destroy$),
     distinctUntilChanged(),
  ).subscribe(() => {
     console.log("SAVED");
     this.tempService.update().subscribe();
  });

Body:
You can use concatMap operator to be sure of the order, concatMap will wait for previous HTTP Observable to complete before mapping the new value from the form.

this.form.valueChanges
 .pipe(
  debounceTime(500),
  filter(() => this.form.dirty),
  takeUntil(this._destroy$),
  distinctUntilChanged(),
  concatMap(val => this.tempService.update())
).subscribe(console.log);


问:
IBM Cloud User Management API - Invite users - Forbidden
i'm getting an error while trying to invite a user to an ibm cloud account by REST API.
The error says that the IMS account is not valid.
Does anyone know whats an IMS Account?

here is my request:

```<code>curl -X POST \
  https://user-management.cloud.ibm.com/v2/accounts/&MYACCOUNT/users \
 -H 'Authorization: Bearer $TOKEN' \
  -H 'Content-Type: application/json' \
    -d '{
      "users": [
      {
        "email": "myuser@ibm.com",
        "account_role": "Member"
      }],
      "iam_policy": [
      {
        "roles": [
        {
          "id": "crn:v1:bluemix:public:iam::::role:Viewer"
        }]
      }]
    }'
</code>```

And the respsonse:

```<code>{
    "trace": "558156745",
    "errors": [
        {
            "code": 9999,
            "message": "Not Authenticated.",
            "more_info": "IMS account id from token is incorrect."
        }
    ]
}
</code>```

Any ideas how to handle this ?

答:
API keys on IBM Cloud are tied to either a user or can be for a service ID, a specific service and more. The API keys for user IDs and service IDs can be used to generate an IAM (authentication) token.

When you call into a REST API and use a token, it is checked that the token is not expired, belongs to a valid user and if the required privileges are held to execute that desired function.

If you want to invite a user to an account and want to grant privileges as part of that invitation process, you would need to use a user ID with the privilege to invite to that specific account. It can be different for any account in an enterprise hierarchy, including the enterprise account. On top of that, the privileges to grant the desired roles or resource access is needed. If one is missing, it gives an error message (not always the best).

Body:
i'm getting an error while trying to invite a user to an ibm cloud account by REST API.
The error says that the IMS account is not valid.
Does anyone know whats an IMS Account?

here is my request:

curl -X POST \
  https://user-management.cloud.ibm.com/v2/accounts/&MYACCOUNT/users \
 -H 'Authorization: Bearer $TOKEN' \
  -H 'Content-Type: application/json' \
    -d '{
      "users": [
      {
        "email": "myuser@ibm.com",
        "account_role": "Member"
      }],
      "iam_policy": [
      {
        "roles": [
        {
          "id": "crn:v1:bluemix:public:iam::::role:Viewer"
        }]
      }]
    }'

And the respsonse:

{
    "trace": "558156745",
    "errors": [
        {
            "code": 9999,
            "message": "Not Authenticated.",
            "more_info": "IMS account id from token is incorrect."
        }
    ]
}

Any ideas how to handle this ?


问:
C++ Thread does not detect global variable change
I have 2 threads monitoring the same global state, if the state.shutdown becomes false, the thread run() should return.  The code is below.

```<code>#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>

using namespace std;

struct State {
    bool shutdown = false;

    ~State() {
        shutdown = true;
    }
};

State state;

#define CHECK_SHUTDOWN     \
  {                        \
    std::cout << (state.shutdown ? " SHUTDOWN " : " NOSHUT ") << typeid(*this).name() << std::endl; \
    if (state.shutdown) {  \
        return;            \
    }                      \
  }

class Mythread {
public:
    void join();
    void run();
    void launch();
    std::thread self_thread;
};

void Mythread::run() {
    while(1) {
        CHECK_SHUTDOWN
    }
}

void Mythread::join() {
    if (self_thread.joinable()) {
        self_thread.join();
    }
}

void Mythread::launch() {
    self_thread = std::thread(&Mythread::run, this);
}

std::mutex mtx;
void shut() {
    std::lock_guard<std::mutex> lock(mtx);
    state.shutdown = true;
}

int main()
{
    Mythread thread1;
    Mythread thread2;

    thread1.launch();
    thread2.launch();

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    //state.shutdown = true;
    shut(); //This makes no difference with the line above

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    thread1.join();
    thread2.join();

    return 0;
}

</code>```

However, even I manually set the state.shutdown to be true, the threads can never detect it. I got prints like:

```<code> NOSHUT 8Mythread
 NOSHUT 8Mythread
 NOSHUT 8Mythread

...Program finished with exit code 0
Press ENTER to exit console.
</code>```

at the end. I'm also confused given that the run() function is never returned, the threads join should hang. However the threads can join successfully.

Any help would be very appreciated here!

答:
You have a data race on shutdown.

When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race [...]

In shut() you set the shutdown flag using a mutex, but the check is performed without the mutex (and the State destructor doesn't use a mutex either). Thus you have conflicting operations (read + write) on a non-atomic variable, without the proper happens before relation. This is a data race which results in undefined behavior.

The simple solution would be to make shutdown an std::atomic<bool>, then you wouldn't even need the mutex to set the flag.

For more details about data races and the C++ memory model I can recommend this paper which I have co-authored: Memory Models for C/C++ Programmers

Body:
I have 2 threads monitoring the same global state, if the state.shutdown becomes false, the thread run() should return.  The code is below.

#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>

using namespace std;

struct State {
    bool shutdown = false;

    ~State() {
        shutdown = true;
    }
};

State state;

#define CHECK_SHUTDOWN     \
  {                        \
    std::cout << (state.shutdown ? " SHUTDOWN " : " NOSHUT ") << typeid(*this).name() << std::endl; \
    if (state.shutdown) {  \
        return;            \
    }                      \
  }

class Mythread {
public:
    void join();
    void run();
    void launch();
    std::thread self_thread;
};

void Mythread::run() {
    while(1) {
        CHECK_SHUTDOWN
    }
}

void Mythread::join() {
    if (self_thread.joinable()) {
        self_thread.join();
    }
}

void Mythread::launch() {
    self_thread = std::thread(&Mythread::run, this);
}

std::mutex mtx;
void shut() {
    std::lock_guard<std::mutex> lock(mtx);
    state.shutdown = true;
}

int main()
{
    Mythread thread1;
    Mythread thread2;

    thread1.launch();
    thread2.launch();

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    //state.shutdown = true;
    shut(); //This makes no difference with the line above

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    thread1.join();
    thread2.join();

    return 0;
}

However, even I manually set the state.shutdown to be true, the threads can never detect it. I got prints like:

 NOSHUT 8Mythread
 NOSHUT 8Mythread
 NOSHUT 8Mythread

...Program finished with exit code 0
Press ENTER to exit console.

at the end. I'm also confused given that the run() function is never returned, the threads join should hang. However the threads can join successfully.

Any help would be very appreciated here!


问:
Eclipse - Unable to delete project from workspace. NPE
I unable to delete the project from the workspace. Eclipse throws NPE and I have NFI how to resolve this issue.

```
java.lang.NullPointerException
    at org.eclipse.ltk.ui.refactoring.resource.DeleteResourcesWizard$DeleteResourcesRefactoringConfigurationPage.createControl(DeleteResourcesWizard.java:89)
    at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:631)
    at org.eclipse.jface.window.Window.create(Window.java:431)
    at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:1089)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation$1.run(RefactoringWizardOpenOperation.java:171)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:192)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:115)
    at org.eclipse.ltk.internal.ui.refactoring.actions.DeleteResourcesHandler.execute(DeleteResourcesHandler.java:40)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommandInContext(HandlerService.java:270)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.runCommand(LTKLauncher.java:95)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.openDeleteWizard(LTKLauncher.java:47)
    at org.eclipse.ui.actions.DeleteResourceAction.run(DeleteResourceAction.java:481)
    at org.eclipse.jdt.internal.ui.refactoring.reorg.DeleteAction.run(DeleteAction.java:162)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:274)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:250)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
    at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:119)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:786)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:885)
    at org.eclipse.ui.internal.keys.OutOfOrderListener.handleEvent(OutOfOrderListener.java:76)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1282)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1267)
    at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1294)
    at org.eclipse.swt.widgets.Widget.gtk_key_press_event(Widget.java:730)
    at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:2841)
    at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java:734)
    at org.eclipse.swt.widgets.Tree.gtk_key_press_event(Tree.java:1977)
    at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1743)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4796)
    at org.eclipse.swt.widgets.Tree.windowProc(Tree.java:3485)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:4360)
    at org.eclipse.swt.internal.gtk.OS._gtk_main_do_event(Native Method)
    at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(OS.java:8189)
    at org.eclipse.swt.widgets.Display.eventProc(Display.java:1238)
    at org.eclipse.swt.internal.gtk.OS._g_main_context_iteration(Native Method)
    at org.eclipse.swt.internal.gtk.OS.g_main_context_iteration(OS.java:2237)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3159)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1384)

```

and this is my environment :-

```
eclipse.buildId=M20110210-1200
java.version=1.6.0_21
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_AU
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os linux -ws gtk -arch x86 -product
org.eclipse.epp.package.jee.product
```

答: Thanks, I've changed my icon set to GNOME and it worked! Ubuntu 11.04 the worst Ubuntu ever! It seems like Ubuntu is aiming to be like Windows ME and Vista... </p>

Body:
I unable to delete the project from the workspace. Eclipse throws NPE and I have NFI how to resolve this issue.

java.lang.NullPointerException
    at org.eclipse.ltk.ui.refactoring.resource.DeleteResourcesWizard$DeleteResourcesRefactoringConfigurationPage.createControl(DeleteResourcesWizard.java:89)
    at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:631)
    at org.eclipse.jface.window.Window.create(Window.java:431)
    at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:1089)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation$1.run(RefactoringWizardOpenOperation.java:171)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:192)
    at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:115)
    at org.eclipse.ltk.internal.ui.refactoring.actions.DeleteResourcesHandler.execute(DeleteResourcesHandler.java:40)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommandInContext(HandlerService.java:270)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.runCommand(LTKLauncher.java:95)
    at org.eclipse.ui.internal.ide.actions.LTKLauncher.openDeleteWizard(LTKLauncher.java:47)
    at org.eclipse.ui.actions.DeleteResourceAction.run(DeleteResourceAction.java:481)
    at org.eclipse.jdt.internal.ui.refactoring.reorg.DeleteAction.run(DeleteAction.java:162)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:274)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:250)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
    at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:119)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:786)
    at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:885)
    at org.eclipse.ui.internal.keys.OutOfOrderListener.handleEvent(OutOfOrderListener.java:76)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1282)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1267)
    at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1294)
    at org.eclipse.swt.widgets.Widget.gtk_key_press_event(Widget.java:730)
    at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:2841)
    at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java:734)
    at org.eclipse.swt.widgets.Tree.gtk_key_press_event(Tree.java:1977)
    at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1743)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4796)
    at org.eclipse.swt.widgets.Tree.windowProc(Tree.java:3485)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:4360)
    at org.eclipse.swt.internal.gtk.OS._gtk_main_do_event(Native Method)
    at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(OS.java:8189)
    at org.eclipse.swt.widgets.Display.eventProc(Display.java:1238)
    at org.eclipse.swt.internal.gtk.OS._g_main_context_iteration(Native Method)
    at org.eclipse.swt.internal.gtk.OS.g_main_context_iteration(OS.java:2237)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3159)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1384)

and this is my environment :-

eclipse.buildId=M20110210-1200
java.version=1.6.0_21
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_AU
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os linux -ws gtk -arch x86 -product
org.eclipse.epp.package.jee.product


问:
Cannot see the DbContext from another project in asp.net core
I have a web api project "Reactivities" and another project "Persisitence" to place my DbContext. When I try to use my add-migration in the Reactivities, using this syntax in the console add-migration InitalCreate -Context .\Persistence I get this error:

No DbContext named '.\Persistence' was found.

Even if I use add-migration InitialCreate -Context .\Persistence\DataContext still I get the same error,

This is in my startup class in Reactivities

```<code>services.AddDbContext<DataContext>(opt =>
            {
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
</code>```

How can I correct this?

答:
You have to do migration work in a project that instantiates the dbcontext, in my case I have created a dbmigrator project with a class that inherits the
IDesignTimeDbContextFactory<T>
where T is the dbcontext type.

This allows me to have a project that has the dbcontexts, a project that works with migrations and a project that uses the dbcontexts independently of each other.

This guide shows you how to use the interface i mentioned:
https://codingblast.com/entityframework-core-idesigntimedbcontextfactory/

Body:
I have a web api project "Reactivities" and another project "Persisitence" to place my DbContext. When I try to use my add-migration in the Reactivities, using this syntax in the console add-migration InitalCreate -Context .\Persistence I get this error:

No DbContext named '.\Persistence' was found.

Even if I use add-migration InitialCreate -Context .\Persistence\DataContext still I get the same error,

This is in my startup class in Reactivities

services.AddDbContext<DataContext>(opt =>
            {
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });

How can I correct this?


问:
Pass method from child component to parent component in vuejs
Can someone help me with passing a function from the child component to the parent component? I am calling a modal in parent component . Inside  component there are two buttons cancel and submit. I want to close the child component after clicking on the submit or cancel buttons. I tried to close the modal by declaring "show" in data, It makes the style display=None and makes the modal disappear but I am not able to scroll the screen after that.

Parent component

```<code><div>
  <modal-dialog v-if="show" id="showCommentEffortBox">
     <input type="button" value="Cancel" @click="show=false">
     <input type="button" value="Submit" @click="show=false">
  </modal-dialog>
</code>```

```<code>data() {
     return {
        show: true
       }
    }
</code>```

Child component

```<code><template>
    <transition name="modal">
        <div class="modal fade" tabindex="-1" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog" style="max-width: 95%">
                <div class="modal-content"  style="max-height: 90vh;">
                    <header class="modal-header">
                        <slot name="header">
                        </slot>
                    </header>
                    <section class="modal-body" style="overflow-y: auto">
                        <slot name="body">
                        </slot>
                    </section>
                </div>
            </div>
        </div>
    </transition>
    </template>

    <script>
    export default {
    *****
    }
    </script>
</code>```

Thanks in Advance

答:
Have a look at these docs, this is the basic standard behaviour.

https://v2.vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events

Body:
Can someone help me with passing a function from the child component to the parent component? I am calling a modal in parent component . Inside  component there are two buttons cancel and submit. I want to close the child component after clicking on the submit or cancel buttons. I tried to close the modal by declaring "show" in data, It makes the style display=None and makes the modal disappear but I am not able to scroll the screen after that.

Parent component

  <modal-dialog v-if="show" id="showCommentEffortBox">
     <input type="button" value="Cancel" @click="show=false">
     <input type="button" value="Submit" @click="show=false">
  </modal-dialog>

data() {
     return {
        show: true
       }
    }

Child component

<template>
    <transition name="modal">

                        <slot name="header">
                        </slot>

                        <slot name="body">
                        </slot>

    </transition>
    </template>

Thanks in Advance


问:
Getting HTTP Error 500.30 - PhysicalFileProvider
I want to use a Path outside from wwwroot for some files which can only reached by authorized user and found the PhysicalFileProvider Method.

My Startup looks like:

```<code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();

        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "Files")),
            RequestPath = "/Files"
        });
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
</code>```

nothing special here i think and works on my local machine.
After Upload this to the hosting server (Hoster: smarterasp.net) i get HTTP Error 500.30 - ANCM In-Process Start Failure. If i comment out the new StaticFileOptions it works, of course the Folder isn´t reachable.

Do i have anything more to do when using the PhysicalFileProvider?

Using .Net Core 3.1

答:
I reproduced the error of you,and the error is caused by the Path cannot be found.I soveld it by adding the static file folder into the publish folder.

This is my partial code of my startup.cs:

```<code>app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "Files")),
                RequestPath = "/Files"
            });
</code>```

And this is my partial code of view:

```<code><img src="~/Files/banner1.svg" alt="ASP.NET" class="img-responsive" />
</code>```

The publish folder contains the content required for publishing,I add the Files Folder  into publish folder.And then it works.

Body:
I want to use a Path outside from wwwroot for some files which can only reached by authorized user and found the PhysicalFileProvider Method.

My Startup looks like:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();

        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "Files")),
            RequestPath = "/Files"
        });
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

nothing special here i think and works on my local machine.
After Upload this to the hosting server (Hoster: smarterasp.net) i get HTTP Error 500.30 - ANCM In-Process Start Failure. If i comment out the new StaticFileOptions it works, of course the Folder isn´t reachable.

Do i have anything more to do when using the PhysicalFileProvider?

Using .Net Core 3.1

Body:
I reproduced the error of you,and the error is caused by the Path cannot be found.I soveld it by adding the static file folder into the publish folder.

This is my partial code of my startup.cs:

app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "Files")),
                RequestPath = "/Files"
            });

And this is my partial code of view:

<img src="~/Files/banner1.svg" alt="ASP.NET" class="img-responsive" />

The publish folder contains the content required for publishing,I add the Files Folder  into publish folder.And then it works.


问:
How to get AWS_Completer for AWS CLI on Windows?
I want to have aws_completer on Windows 10 in GitBash terminal.

AWS docs say that aws_completer is only available for UNIX-like systems

On Unix-like systems, the AWS CLI includes a command-completion feature

And my version of AWS CLI that I downloaded from AWS doesn't have any aws_completer packages or scripts indeed.

Is there a way to enable completion on Windows?

答:
If you're using PowerShell 5.1 (/PowerShell Core) you can use this PS Module - https://www.powershellgallery.com/packages/AWSCompleter/
Just Install-Module AWSCompleter in PowerShell and you'll have tab-completion running.


问:
impossible to html parsing facebook public profile with php
i grabbed an html from this url : http://facebook.com/zuck
there is no problem to echo it to the client browser but i found it impossible to parse it with php.

i am trying to parse the text inside div tags for example :

```<code>preg_match_all("/<div class=\"mediaPageName\">(.*)<\/div>/",$html,$matches);
print_r($matches);
</code>```

returns empty array
i also tried with DOMDocument and with PHP Simple HTML DOM Parser both of them return empty elements and can't grab the text of the html.

how is it even possible?
there is a solution to that?

答:
It is quite possible.

Easiest way is to load the complete DOM into DOMDocument or phpQuery

Edit:

From looking at the source code of the link provided, the element you are searching for is replacing less than characters, < with the unicode representation: \u003c.

Example: \u003cdiv class=\"mediaPageName\">Nirvana\u003c\/div>

Edit 2:

As mentioned by others, do not parse HTML when not necessary. But it looks like this is required in this case as Frank Farmer mentions.

This regex will find some matches (only one per line, hopefully someone can adjust it to get all the matches).
preg_match_all('%\\\\u003cdiv class=.*mediaPageName[^>]*>([^>]*)\\\\u003c%i', $html, $matches);

It may be worthwhile finding out how to use Unicode regex as outlined here.

Body:
i grabbed an html from this url : http://facebook.com/zuck
there is no problem to echo it to the client browser but i found it impossible to parse it with php.

i am trying to parse the text inside div tags for example :

preg_match_all("/
(.*)<\/div>/",$html,$matches);
print_r($matches);

returns empty array
i also tried with DOMDocument and with PHP Simple HTML DOM Parser both of them return empty elements and can't grab the text of the html.

how is it even possible?
there is a solution to that?


问:
How to get average with rows in pig
Through the following processing

```<code>REGISTER 's3://jmh-dtg-2016/jeon_dtg/test.py' USING jython as test;
raw01  = LOAD 's3://jmh-dtg-2016/jeon_dtg/test_pig.csv' USING org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'NO_MULTILINE', 'UNIX', 'SKIP_INPUT_HEADER');
raw02 = FOREACH raw01 GENERATE (chararray)$2 as date, (chararray)$3 as code, (chararray)$4 as car_num, (chararray)$5 as pre_time, (FLOAT)$8 as vel, (chararray)$18 as link_id;
raw03 = GROUP raw02 BY (link_id, car_num);
raw04 = FOREACH raw03 GENERATE group, test.my_fun(raw02.vel) AS val;
dump raw04;
</code>```

Got these results

enter image description here

i wanna get average of each rows.
In conclusion, I want results like this :

```<code>{(39.0),(45.0)}) -> 42
{(1.0)}) -> 1
</code>```

This is the python function I used.

```<code>@outputSchema('num01:float')
def my_fun(data01):
    a = data01
    b = sorted(a)
    c = int((len(b)/100.0) * 10.0)
    d = int((len(b)/100.0) * 90.0)
    e = b[c:d]
    return e
</code>```

and it is impossible

```<code> @outputSchema('num01:float')
    def my_fun(data01):
        a = data01
        b = sorted(a)
        c = int((len(b)/100.0) * 10.0)
        d = int((len(b)/100.0) * 90.0)
        e = b[c:d]
        return sum(e)
</code>```

help me please..

答:
It sounds like you just need to get the average from a bag of values? Correct me if I'm wrong. The PIG operator AVG should do this and will be more performant than a Python UDF.</p>

```<code>raw04 = FOREACH raw03 GENERATE group, AVG(raw02.vel) AS val;
</code>```

Title: How to get average with rows in pig

Body:
Through the following processing

REGISTER 's3://jmh-dtg-2016/jeon_dtg/test.py' USING jython as test;
raw01  = LOAD 's3://jmh-dtg-2016/jeon_dtg/test_pig.csv' USING org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'NO_MULTILINE', 'UNIX', 'SKIP_INPUT_HEADER');
raw02 = FOREACH raw01 GENERATE (chararray)$2 as date, (chararray)$3 as code, (chararray)$4 as car_num, (chararray)$5 as pre_time, (FLOAT)$8 as vel, (chararray)$18 as link_id;
raw03 = GROUP raw02 BY (link_id, car_num);
raw04 = FOREACH raw03 GENERATE group, test.my_fun(raw02.vel) AS val;
dump raw04;

Got these results

enter image description here

i wanna get average of each rows.
In conclusion, I want results like this :

{(39.0),(45.0)}) -> 42
{(1.0)}) -> 1

This is the python function I used.

@outputSchema('num01:float')
def my_fun(data01):
    a = data01
    b = sorted(a)
    c = int((len(b)/100.0) * 10.0)
    d = int((len(b)/100.0) * 90.0)
    e = b[c:d]
    return e

and it is impossible

 @outputSchema('num01:float')
    def my_fun(data01):
        a = data01
        b = sorted(a)
        c = int((len(b)/100.0) * 10.0)
        d = int((len(b)/100.0) * 90.0)
        e = b[c:d]
        return sum(e)

help me please..

Body:
It sounds like you just need to get the average from a bag of values? Correct me if I'm wrong. The PIG operator AVG should do this and will be more performant than a Python UDF.

raw04 = FOREACH raw03 GENERATE group, AVG(raw02.vel) AS val;


问:
Hibernate: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
I'm trying to create one to one relationship in Jpa. When I run this program throw the Exception

```<code>ERROR: Cannot add or update a child row: a foreign key constraint fails (`ngsharma`.`student`, CONSTRAINT `FK8nqh8nm4hrwx9hlqwhxf6kfen` FOREIGN KEY (`laptop_lid`) REFERENCES `laptop` (`lid`))
</code>```

Student

```<code>@Entity(name = "student")
public class Student {

    @Id
    private  int rollno;
    private String name;
    @OneToOne
    private Laptop laptop;

    /*Setter & Getter*/
}
</code>```

Laptop

```<code>@Entity(name = "laptop")
public class Laptop {

    @Id
    private int lid;
    private String laptopName;

    /*Setter & Getter*/
}
</code>```

Hibernate.cfg.xml

```<code><hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ngsharma</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MariaDBDialect</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>
</code>```

Run CLass

```<code>    Configuration configuration =
            new Configuration().configure()
                                                    .addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class);

    SessionFactory sessionFactory = configuration.buildSessionFactory();

    Session session = sessionFactory.openSession();

    Laptop laptop = new Laptop();
    laptop.setLid(101);
    laptop.setLaptopName("Mac Nootbook");

    Student student = new Student();
    student.setRollno(1);
    student.setName("Shri Krishan");
    student.setLaptop(laptop);

     Serializable serializable = session.save(student);
     System.out.println("Test Code : "  + serializable);

     session.beginTransaction().commit();
</code>```

答:
In your example, you are trying to save a student entity, for which laptop association does not exist in database. Both instances are newly created as far as understand from the code snippet you provided. Hence, according to the foreign constraint at database level, you are trying to reference laptop table from within student table; where the corresponding laptop row with the referenced id does not exist.

If you also persist the associated laptop entity while persisting the student entity your problem will be solved. The only modification you need to do is to update the @OneToOne relation as:

```<code>    @OneToOne(cascade=CascadeType.PERSIST)
    private Laptop laptop;
</code>```

This will work; since it will also insert the laptop entity to the database along with the student entity itself.

Body:
I'm trying to create one to one relationship in Jpa. When I run this program throw the Exception

ERROR: Cannot add or update a child row: a foreign key constraint fails (`ngsharma`.`student`, CONSTRAINT `FK8nqh8nm4hrwx9hlqwhxf6kfen` FOREIGN KEY (`laptop_lid`) REFERENCES `laptop` (`lid`))

Student

@Entity(name = "student")
public class Student {

    @Id
    private  int rollno;
    private String name;
    @OneToOne
    private Laptop laptop;

    /*Setter & Getter*/
}

Laptop

@Entity(name = "laptop")
public class Laptop {

    @Id
    private int lid;
    private String laptopName;

    /*Setter & Getter*/
}

Hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ngsharma</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MariaDBDialect</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Run CLass

    Configuration configuration =
            new Configuration().configure()
                                                    .addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class);

    SessionFactory sessionFactory = configuration.buildSessionFactory();

    Session session = sessionFactory.openSession();

    Laptop laptop = new Laptop();
    laptop.setLid(101);
    laptop.setLaptopName("Mac Nootbook");

    Student student = new Student();
    student.setRollno(1);
    student.setName("Shri Krishan");
    student.setLaptop(laptop);

     Serializable serializable = session.save(student);
     System.out.println("Test Code : "  + serializable);

     session.beginTransaction().commit();

Body:
In your example, you are trying to save a student entity, for which laptop association does not exist in database. Both instances are newly created as far as understand from the code snippet you provided. Hence, according to the foreign constraint at database level, you are trying to reference laptop table from within student table; where the corresponding laptop row with the referenced id does not exist.

If you also persist the associated laptop entity while persisting the student entity your problem will be solved. The only modification you need to do is to update the @OneToOne relation as:

    @OneToOne(cascade=CascadeType.PERSIST)
    private Laptop laptop;

This will work; since it will also insert the laptop entity to the database along with the student entity itself.


问:
MariaDB CAST OR CONVERT Function is not work
my table has a varchar(64) column ,when i try to convert it to char(36), it not work.

```<code>SELECT
CONVERT('00edff66-3ef4-4447-8319-fc8eb45776ab',CHAR(36)) AS A,
CAST('00edff66-3ef4-4447-8319-fc8eb45776ab' AS CHAR(36)) as B
</code>```

this is desc result

答:
It's like this because it is derived from MySQL where there was no CAST AS VARCHAR option. In MySQL there was only CAST AS CHAR which was producing VARCHAR. Here are what the supported options were in MySQL 5.6:

https://dev.mysql.com/doc/refman/5.6/en/cast-functions.html#function_cast

See they explicitly mention that "No padding occurs for values shorter than N characters". Later MariaDB started adding CAST AS VARCHAR only to make it more cross-platform compatible with systems like Oracle, Postgre, MSSQL, etc.:

https://jira.mariadb.org/browse/MDEV-11283

But still CAST AS CHAR and CAST AS VARCHAR is the same. And I guess it should be the same. Why do you need the fixed length datatype in RAM? It should matter only when you store it.

For example if you have a table with CHAR datatype:

```<code>    CREATE TABLE tbltest(col CHAR(10));
</code>```

and you insert casted as VARCHAR data for example:

```<code>    INSERT INTO tbltest(col) VALUES(CAST('test' AS VARCHAR(5)));
</code>```

it will be stored as CHAR(10) datatype. Because that's what the table uses.

Body:
my table has a varchar(64) column ,when i try to convert it to char(36), it not work.

SELECT
CONVERT('00edff66-3ef4-4447-8319-fc8eb45776ab',CHAR(36)) AS A,
CAST('00edff66-3ef4-4447-8319-fc8eb45776ab' AS CHAR(36)) as B

this is desc result

Body:
It's like this because it is derived from MySQL where there was no CAST AS VARCHAR option. In MySQL there was only CAST AS CHAR which was producing VARCHAR. Here are what the supported options were in MySQL 5.6:

https://dev.mysql.com/doc/refman/5.6/en/cast-functions.html#function_cast

See they explicitly mention that "No padding occurs for values shorter than N characters". Later MariaDB started adding CAST AS VARCHAR only to make it more cross-platform compatible with systems like Oracle, Postgre, MSSQL, etc.:

https://jira.mariadb.org/browse/MDEV-11283

But still CAST AS CHAR and CAST AS VARCHAR is the same. And I guess it should be the same. Why do you need the fixed length datatype in RAM? It should matter only when you store it.

For example if you have a table with CHAR datatype:

    CREATE TABLE tbltest(col CHAR(10));

and you insert casted as VARCHAR data for example:

    INSERT INTO tbltest(col) VALUES(CAST('test' AS VARCHAR(5)));

it will be stored as CHAR(10) datatype. Because that's what the table uses.


问:
Ruby: Is there a way to get the enclosing Module const of a Class?
I'm doing some metaprogramming in Ruby, and I need to dynamically generate a sibling class inside of a module. In doing so, I want to call const_set on the module, but I don't know which Module constant to call that on until runtime. An example:

Given classes

```<code>Foo::Bar::Baz
Foo::Quox::Quack
</code>```

I want to be able to call a function like this (oversimplified here):

```<code>def generate_from klass
  mod = klass.enclosing_module # <- THIS LINE is the one I need to figure out
  mod.const_set("GeneratedClassName", Class.new)
end
</code>```

and what I want to end up with, when calling with Baz, is a new class defined as

```<code>Foo::Bar::GeneratedClassName
</code>```

and with a Quack, I want

```<code>Foo::Quox::GeneratedClassName
</code>```

The only way I know of is to split up klass.name, then repeatedly call const_get on those strings, constantized. Does anyone know of a more elegant way?

答:
This should get you on track:

```<code>module Foo
  module Bar
    class Baz
      def initialize
        @nesting = Module.nesting
      end

      def enclosing_module
        @nesting.last
      end
    end
  end
end

puts Foo::Bar::Baz.new.enclosing_module #=> Foo
</code>```

Relevant documentation:

http://ruby-doc.org/core/classes/Module.html#M000441

Body:
I'm doing some metaprogramming in Ruby, and I need to dynamically generate a sibling class inside of a module. In doing so, I want to call const_set on the module, but I don't know which Module constant to call that on until runtime. An example:

Given classes

Foo::Bar::Baz
Foo::Quox::Quack

I want to be able to call a function like this (oversimplified here):

def generate_from klass
  mod = klass.enclosing_module # <- THIS LINE is the one I need to figure out
  mod.const_set("GeneratedClassName", Class.new)
end

and what I want to end up with, when calling with Baz, is a new class defined as

Foo::Bar::GeneratedClassName

and with a Quack, I want

Foo::Quox::GeneratedClassName

The only way I know of is to split up klass.name, then repeatedly call const_get on those strings, constantized. Does anyone know of a more elegant way?

Body:
This should get you on track:

module Foo
  module Bar
    class Baz
      def initialize
        @nesting = Module.nesting
      end

      def enclosing_module
        @nesting.last
      end
    end
  end
end

puts Foo::Bar::Baz.new.enclosing_module #=> Foo

Relevant documentation:

http://ruby-doc.org/core/classes/Module.html#M000441


问:
Mysql Join with max date and first row
I have 2 tables properties and property_history
structure some thing like that

```<code>proerties -
id | property_address | owner
1  | abc              | xyz
2  | 123              | efg

property_history-

id | property_id |   date1    |   date2    |   date3    |    date4
1  | 1           | 2012-05-01 | 0000-00-00 | 2002-06-11 | 2006-06-11 |
2  | 1           | 2019-05-01 | 0000-00-00 | 2003-06-11 | 2007-06-11 |
3  | 1           | 0000-00-00 | 2011-06-11 | 2004-06-11 | 2011-06-11 |
4  | 1           | 0000-00-00 | 2020-01-31 | 2005-06-11 | 0000-00-11 |
</code>```

I need to join these two table as

All rows from properties table

Only 1 row form property history with latest date from any of the date column as latest date
for eg. latest date between( date1, date2, date3, date4) as latest_date as one column

If property_history not have any row with respect property id then latest_date should be null

答:
```<code>SELECT properties.id, properties.parcel_id, properties.state, properties.county, properties.assessed_value, properties.in_same_zip, properties.in_same_state
FROM  properties left join (SELECT GREATEST(tax_history.date_paid_2nd_half_2,
     COALESCE(tax_history.date_paid_2nd_half_1, 0),
     COALESCE(tax_history.date_paid_1st_half_2, 0),
     COALESCE(tax_history.date_paid_1st_half_1, 0)) as latest_date, property_id from tax_history) as tax_history ON tax_history.property_id = properties.id
</code>```

```<code>This query is working but it is very slow, I have thousands of records
</code>```

Title: Mysql Join with max date and first row

Body:
I have 2 tables properties and property_history
structure some thing like that

proerties -
id | property_address | owner
1  | abc              | xyz
2  | 123              | efg

property_history-

id | property_id |   date1    |   date2    |   date3    |    date4
1  | 1           | 2012-05-01 | 0000-00-00 | 2002-06-11 | 2006-06-11 |
2  | 1           | 2019-05-01 | 0000-00-00 | 2003-06-11 | 2007-06-11 |
3  | 1           | 0000-00-00 | 2011-06-11 | 2004-06-11 | 2011-06-11 |
4  | 1           | 0000-00-00 | 2020-01-31 | 2005-06-11 | 0000-00-11 |

I need to join these two table as

All rows from properties table

Only 1 row form property history with latest date from any of the date column as latest date
for eg. latest date between( date1, date2, date3, date4) as latest_date as one column

If property_history not have any row with respect property id then latest_date should be null

Body:
SELECT properties.id, properties.parcel_id, properties.state, properties.county, properties.assessed_value, properties.in_same_zip, properties.in_same_state
FROM  properties left join (SELECT GREATEST(tax_history.date_paid_2nd_half_2,
     COALESCE(tax_history.date_paid_2nd_half_1, 0),
     COALESCE(tax_history.date_paid_1st_half_2, 0),
     COALESCE(tax_history.date_paid_1st_half_1, 0)) as latest_date, property_id from tax_history) as tax_history ON tax_history.property_id = properties.id

This query is working but it is very slow, I have thousands of records


问:
How to return biggest x coordinate and biggest y coordinate from a list of segments?
So, I have a bunch of segments as inputs, that are made of x coordinates and y coordinates. Horizontal segments have left and right x coordinates, and a unique y coordinate, while vertical segments have up and down y coordinates and a unique x coordinate.
I figured out they are gonna look like this:

Horizontal segment = ((2,8), 4)

Vertical segment = (3, (2,5))

All segments = [((2,8), 1), (3, (2,5)), (5, (3,4)), (4, (6,7))]

I want to return the biggest x coordinate and the biggest y coordinate. How can I do that?

答:
If you are trying to extract the none-tuple values in your list then you can try something like this:

```<code>d = [((2,8), 1), (3, (2,5)), (5, (3,4)), (4, (6,7))]
d_x = [x for x, y in d if not isinstance(x, tuple)]
d_y = [y for x, y in d if not isinstance(y, tuple)]

print ("Max X:", max(d_x))
print ("Max Y:", max(d_y))
</code>```

Edit:

Just wanted to see how short it could be written and came up with this one-liner:

```<code>max_x, max_y = map(lambda l : max([max(i) if isinstance(i, tuple) else i for i in l]), zip(*input_list))
</code>```

Body:
If you are trying to extract the none-tuple values in your list then you can try something like this:

d = [((2,8), 1), (3, (2,5)), (5, (3,4)), (4, (6,7))]
d_x = [x for x, y in d if not isinstance(x, tuple)]
d_y = [y for x, y in d if not isinstance(y, tuple)]

print ("Max X:", max(d_x))
print ("Max Y:", max(d_y))

Edit:

Just wanted to see how short it could be written and came up with this one-liner:

max_x, max_y = map(lambda l : max([max(i) if isinstance(i, tuple) else i for i in l]), zip(*input_list))


问:
How to stop/abort/cancel a page load in PhantomJS?
I use PhantomJS to check a list of links for specific content. Once these content is found I would like to cancel the page load to avoid further ressource requests and continue with the next page to improve speed.

I filter requests in page.onResourceRequested and request.abort(); everything that doesn't match but that doesn't prevent PhantomJS from requesting till the site finished.

Tried page.stop(); -> crashes PhantomJS

The documentation seems lacking and I wonder if there is a command I can use to do that.
I can't use page.close(); because I need the page object after the content is found.

答:
```<code>page.onResourceRequested = function(requestData, request) {
    var matchUrlNeeded = ((/someregexforurl\/js/g).test(requestData.url));
    if (matchUrlNeeded) {
        doStuffWithTheUrl;
        response.close();
        request.abort();
        page.cancel(); }
    }
    else {
        //console.log("NO MATCH : " + requestData.url); request.abort(); } { }
</code>```


问:
How to Pass List using Ajax call to Spring MVC Controller
I have holding object as follows：

```<code>public class Transfer implements Serializable {
     private Integer transferId;
     private Integer transferTypeId;
     private String storeId;
     private String userId;
     private Integer titleId;
     private Integer statusId;
     private String inWorkerId;
     private String outWorkerId;
     private Date createDt;
     private Date updateDt;
     // getters & setts
 }
</code>```

And I have var reqRow that need to be sent to the controller

```<code>function onClickSave(){
    var rows = $('#transferEditGrid').jqGrid('getRowData');
    var reqRow = [];
    for (i = 0; i < rows.length; i++)
    {
        var rowObj = {};
        rowObj.storeId = rows[i].storeId;
        rowObj.inWorkerId = rows[i].inWorkerId;
        rowObj.outWorkerId = rows[i].outWorkerId;
        rowObj.transferTypeId = rows[i].transferTypeId;
        rowObj.statusId = rows[i].statusId;
        rowObj.storeId = rows[i].storeId;
        reqRow.push(rowObj);
    }

    //send reqRow to the Controller
    $.ajax({
        type:'POST',
        url:'${contextPath}/resource-transfer/update.do',
        dataType:"json",
        data : {rows : reqRow},
        //data:JSON.stringify(reqRow),
        success:function(response){
            alert("success");

        }
    });
}
</code>```

The controller is following :

```<code>@RequestMapping(value = "/update", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
@ResponseBody
public String transferUpdate(@RequestBody List<Transfer> rows) throws JSONException, InterruptedException {

    System.out.println("in transfer update section");

    return null;
}
</code>```

Why I could not pass the array object to the controller?
Did I misunderstand the usage of the Ajax call?

Thank you

答:
Java code

```<code>@Controller
public class ContractController {

    @RequestMapping(value="all/contract/change/detail", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public List<ContractAndBidReceiveChangeDetailModel> getAllContractAndBidReceiveChangeDetail(@RequestBody List<ContractReceivedChangedActivityCodesModel> allChangedActivityCodesModel) {

        List<ContractAndBidReceiveChangeDetailModel> allContractAndBidChangeDetails = null;

        if (CollectionUtils.isNotEmpty(allChangedActivityCodesModel)) {
            allContractAndBidChangeDetails = allChangedActivityCodesModel
                    .stream()
                    .map(this::getContractAndBidReceiveChangeDetail)
                    .collect(Collectors.toList());
        }

        return allContractAndBidChangeDetails;
    }
} // end of controller class

@JsonAutoDetect(
    creatorVisibility = JsonAutoDetect.Visibility.NONE,
    fieldVisibility = JsonAutoDetect.Visibility.NONE,
    getterVisibility = JsonAutoDetect.Visibility.NONE,
    isGetterVisibility = JsonAutoDetect.Visibility.NONE,
    setterVisibility = JsonAutoDetect.Visibility.NONE
)
public class ContractReceivedChangedActivityCodesModel {

    private String rowId;
    private Long bidId;
    private Long planId;
    private Long optionCodeId;
    private Long activityCodeId;
    private Long activityPackageId;
    private String activityCodeNoAndName;
    private String planName;

    // constructors

    @JsonProperty
    public String getRowId() {
        return rowId;
    }

    public void setRowId(String rowId) {
        this.rowId = rowId;
    }

    //others getters and setters
}
</code>```

JQuery code. Make sure you make the same json rquest that spring is expecting. Spring will automatically map this json to your java List

```<code>function getDetailRow(url, requestData, $caret, action) {

    $spinner.show();

    $.ajax({
        url: url,
        data : requestData,
        dataType: "json",
        type: "POST",
        contentType: "application/json",
        success: function(response) {
            if (!$.isEmptyObject(response)) {
                switch(action){
                    case "expandLink":
                        insertDetailRow($caret, response);
                    break;
                    case "expandAllLinks":
                        $.each(response, function(index, changeDetailResponse) {
                            var caretId = changeDetailResponse.rowId;
                            let $caret = $('#' + caretId);
                            insertDetailRow($caret, changeDetailResponse);
                        });
                    break;
                }
            }
            $spinner.hide();
        }, error: function(xhr, status, error){
            $spinner.hide();
            if (xhr.status == 500) {
                var errorResponse = xhr.responseText;
                if (errorResponse) {
                    alert(errorResponse);
                }
            }
        }
    });
}

function getRequestJson(requestObject) {
    let requestJson = null;
    if (requestObject != null) {
        requestJson = JSON.stringify(requestObject);
    }
    return requestJson;
}

function getRequestObject($caret) {
    let requestObject = null;
    if ($caret.length > 0) {
        let rowId = $caret.attr("id");
        let bidId = $caret.attr("bidId");
        let planId = $caret.attr("planId");
        let optionCodeId = $caret.attr("optionCodeId");
        let activityCodeId = $caret.attr("activityCodeId");
        let activityPackageId = $caret.attr("activityPackageId");

        requestObject = new Object();
        requestObject.rowId = rowId;
        requestObject.bidId = bidId;
        requestObject.planId = planId;
        requestObject.optionCodeId = optionCodeId;
        requestObject.activityCodeId = activityCodeId;
        requestObject.activityPackageId = activityPackageId;
    }
    return requestObject;
}

let caretsWithoutDetailRow = new Array();
let requestObjects = null;

// process caretsWithoutDetailRow Array with some logic so it contains some elements

if (caretsWithoutDetailRow.length > 0) {
    requestObjects = new Array();
    $.each(caretsWithoutDetailRow, function(index, $caret) {
        let requestObject = getRequestObject($caret);
        requestObjects.push(requestObject);
    });
}

if (requestObjects != null && requestObjects.length > 0) {
    let requestObjectsJson = getRequestJson(requestObjects);
    let url = '<c:url value = "/all/contract/change/detail"/>';
    getDetailRow(url, requestObjectsJson, null, 'expandAllLinks');
}
</code>```

Body:
I have holding object as follows：

public class Transfer implements Serializable {
     private Integer transferId;
     private Integer transferTypeId;
     private String storeId;
     private String userId;
     private Integer titleId;
     private Integer statusId;
     private String inWorkerId;
     private String outWorkerId;
     private Date createDt;
     private Date updateDt;
     // getters & setts
 }

And I have var reqRow that need to be sent to the controller

function onClickSave(){
    var rows = $('#transferEditGrid').jqGrid('getRowData');
    var reqRow = [];
    for (i = 0; i < rows.length; i++)
    {
        var rowObj = {};
        rowObj.storeId = rows[i].storeId;
        rowObj.inWorkerId = rows[i].inWorkerId;
        rowObj.outWorkerId = rows[i].outWorkerId;
        rowObj.transferTypeId = rows[i].transferTypeId;
        rowObj.statusId = rows[i].statusId;
        rowObj.storeId = rows[i].storeId;
        reqRow.push(rowObj);
    }

    //send reqRow to the Controller
    $.ajax({
        type:'POST',
        url:'${contextPath}/resource-transfer/update.do',
        dataType:"json",
        data : {rows : reqRow},
        //data:JSON.stringify(reqRow),
        success:function(response){
            alert("success");

        }
    });
}

The controller is following :

@RequestMapping(value = "/update", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
@ResponseBody
public String transferUpdate(@RequestBody List<Transfer> rows) throws JSONException, InterruptedException {

    System.out.println("in transfer update section");

    return null;
}

Why I could not pass the array object to the controller?
Did I misunderstand the usage of the Ajax call?

Thank you

Body:
Java code

@Controller
public class ContractController {

    @RequestMapping(value="all/contract/change/detail", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public List<ContractAndBidReceiveChangeDetailModel> getAllContractAndBidReceiveChangeDetail(@RequestBody List<ContractReceivedChangedActivityCodesModel> allChangedActivityCodesModel) {

        List<ContractAndBidReceiveChangeDetailModel> allContractAndBidChangeDetails = null;

        if (CollectionUtils.isNotEmpty(allChangedActivityCodesModel)) {
            allContractAndBidChangeDetails = allChangedActivityCodesModel
                    .stream()
                    .map(this::getContractAndBidReceiveChangeDetail)
                    .collect(Collectors.toList());
        }

        return allContractAndBidChangeDetails;
    }
} // end of controller class

@JsonAutoDetect(
    creatorVisibility = JsonAutoDetect.Visibility.NONE,
    fieldVisibility = JsonAutoDetect.Visibility.NONE,
    getterVisibility = JsonAutoDetect.Visibility.NONE,
    isGetterVisibility = JsonAutoDetect.Visibility.NONE,
    setterVisibility = JsonAutoDetect.Visibility.NONE
)
public class ContractReceivedChangedActivityCodesModel {

    private String rowId;
    private Long bidId;
    private Long planId;
    private Long optionCodeId;
    private Long activityCodeId;
    private Long activityPackageId;
    private String activityCodeNoAndName;
    private String planName;

    // constructors

    @JsonProperty
    public String getRowId() {
        return rowId;
    }

    public void setRowId(String rowId) {
        this.rowId = rowId;
    }

    //others getters and setters
}

JQuery code. Make sure you make the same json rquest that spring is expecting. Spring will automatically map this json to your java List

function getDetailRow(url, requestData, $caret, action) {

    $spinner.show();

    $.ajax({
        url: url,
        data : requestData,
        dataType: "json",
        type: "POST",
        contentType: "application/json",
        success: function(response) {
            if (!$.isEmptyObject(response)) {
                switch(action){
                    case "expandLink":
                        insertDetailRow($caret, response);
                    break;
                    case "expandAllLinks":
                        $.each(response, function(index, changeDetailResponse) {
                            var caretId = changeDetailResponse.rowId;
                            let $caret = $('#' + caretId);
                            insertDetailRow($caret, changeDetailResponse);
                        });
                    break;
                }
            }
            $spinner.hide();
        }, error: function(xhr, status, error){
            $spinner.hide();
            if (xhr.status == 500) {
                var errorResponse = xhr.responseText;
                if (errorResponse) {
                    alert(errorResponse);
                }
            }
        }
    });
}

function getRequestJson(requestObject) {
    let requestJson = null;
    if (requestObject != null) {
        requestJson = JSON.stringify(requestObject);
    }
    return requestJson;
}

function getRequestObject($caret) {
    let requestObject = null;
    if ($caret.length > 0) {
        let rowId = $caret.attr("id");
        let bidId = $caret.attr("bidId");
        let planId = $caret.attr("planId");
        let optionCodeId = $caret.attr("optionCodeId");
        let activityCodeId = $caret.attr("activityCodeId");
        let activityPackageId = $caret.attr("activityPackageId");

        requestObject = new Object();
        requestObject.rowId = rowId;
        requestObject.bidId = bidId;
        requestObject.planId = planId;
        requestObject.optionCodeId = optionCodeId;
        requestObject.activityCodeId = activityCodeId;
        requestObject.activityPackageId = activityPackageId;
    }
    return requestObject;
}

let caretsWithoutDetailRow = new Array();
let requestObjects = null;

// process caretsWithoutDetailRow Array with some logic so it contains some elements

if (caretsWithoutDetailRow.length > 0) {
    requestObjects = new Array();
    $.each(caretsWithoutDetailRow, function(index, $caret) {
        let requestObject = getRequestObject($caret);
        requestObjects.push(requestObject);
    });
}

if (requestObjects != null && requestObjects.length > 0) {
    let requestObjectsJson = getRequestJson(requestObjects);
    let url = '<c:url value = "/all/contract/change/detail"/>';
    getDetailRow(url, requestObjectsJson, null, 'expandAllLinks');
}


问:
App Engine High Replication Datastore
I'm a total App Engine newbie, and I want to confirm my understanding of the high replication datastore.

The documentation says that entity groups are a "unit of consistency", and that all data is eventually consistent. Along the same lines, it also says "queries across entity groups can be stale".

Can someone provide some examples where queries can be "stale"? Is it saying I could potentially save an entity without any parent (ie. it's own group), then query for it very soon after and not find it? Does it also imply that if I want data to be always 100% up-to-date I need to save them all in the same entity group?

Is the common workaround for this to use memcache to cache entities for a period of time longer than the average time it takes for data to become consistent across all data centers? What's the ballpark latency for that?

Thanks

答:
Having just migrated my app over from the Master/Slave to the High Replication datastore, I have to say that in practice, eventual consistency isn't a problem for most applications.

Consider the classic guestbook example, where you put() a new guestbook post Entity and then immediately query all the posts in the guestbook. With the High Replication datastore, you won't see the new post appear in the query results until a few seconds later (at Google I/O, the Google engineers said that the lag was on the order of 2-5 seconds).

Now, in practice, your guestbook app is probably doing an AJAX post of the new guestbook post entry. There is no need to refetch all the posts after submitting the new post. The webapp can simply insert the new entry into the UI once the AJAX request has succeeded. By the time the user leaves the webpage and returns to it, or even hits the browser refresh button, several seconds will have elapsed, and it is very likely that the new post will be returned by the query that pulls in all the guestbook posts.

Finally, note that the eventual consistency performance applies only to queries. If you put() an entity and immediately call db.get() to fetch it back, the result is strongly consistent, i.e. you will get the latest snapshot of the entity.

Title: App Engine High Replication Datastore


问:
How do you get responseText from jQuery.getJSON method in javascript?
I am trying to read in a JSON file from my directory using the jQuery.getJSON method and it returns the object shown in the picture. I want to get the responseText from the object but cannot figure out how.

```<code>var jsonData = jQuery.getJSON('relationalData.json');
</code>```

Ive tried to use the following to extract the responseText but they all failed.

```<code>var response = jsonData.responseText;
var response = jsonData['responseText'];
</code>```

I also tried using without any luck, as the method doesn't even get called with a json file. It worked when I used an xml though.

```<code>$.get(filename, function(data){
   var responseText = data;
});
</code>```

答:
Came across this question which has been longed asked, but for future visitors where is my solution:

$.getJSON method fetches data from a server using HTTP GET request, the response on successful call returns in a responseText property as you see in your console.

Therefore to get the data of the responseText you have to use the JSON.parse() method to retrieve data to javaSrcipt object like this:

```<code>var jsonData = JSON.parse(jsonCall.responseText);
</code>```

But $.getJSON() method is asynchronous so this must be done inside the callback function if not the response may not exist.

Final solution:

```<code>var jsonCall = $.getJSON('URL',function(){
   var jsonData = JSON.parse(jsonCall.responseText);
   console.log(jsonData);
  });
</code>```

Body:
I am trying to read in a JSON file from my directory using the jQuery.getJSON method and it returns the object shown in the picture. I want to get the responseText from the object but cannot figure out how.

var jsonData = jQuery.getJSON('relationalData.json');

Ive tried to use the following to extract the responseText but they all failed.

var response = jsonData.responseText;
var response = jsonData['responseText'];

I also tried using without any luck, as the method doesn't even get called with a json file. It worked when I used an xml though.

$.get(filename, function(data){
   var responseText = data;
});

Body:
Came across this question which has been longed asked, but for future visitors where is my solution:

$.getJSON method fetches data from a server using HTTP GET request, the response on successful call returns in a responseText property as you see in your console.

Therefore to get the data of the responseText you have to use the JSON.parse() method to retrieve data to javaSrcipt object like this:

var jsonData = JSON.parse(jsonCall.responseText);

But $.getJSON() method is asynchronous so this must be done inside the callback function if not the response may not exist.

Final solution:

var jsonCall = $.getJSON('URL',function(){
   var jsonData = JSON.parse(jsonCall.responseText);
   console.log(jsonData);
  });