问:
Trouble binding a rich:dataTable
I'm having some problems with defining a binding bean for my rich:dataTable.

The contents of the datatable are already defined in the XHTML, I just want to use the binding to read the rows back later so that the table contents can be exported into a PDF.

In my XHTML file, I put

```<code><rich:dataTable ... binding="#{backingBean.tableBinding}">
</code>```

Then, in my backing bean, I declare a member:

```<code>import org.richfaces.component.html.HtmlDataTable;
class BackingBean {
   private HtmlDataTable tableBinding ;
   public BackingBean() {
      tableBinding = new HtmlDataTable() ;
   }
   // ... (incl. getters and setters for binding)
 } ;
</code>```

However, this results in:

java.lang.NullPointerException
   at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:809)

when I try to load the page. Is there something I need to do with the HtmlDataTable variable besides simply constructing it? Is it even possible to use the binding attribute in the way I intend here?

答: Don't create an instance of HtmlDataTable yourself in the constructor. RichFaces will create an instance and inject it to your BackingBean. All you need is an public getter and setter.

Title: Trouble binding a rich:dataTable

Body:
I'm having some problems with defining a binding bean for my rich:dataTable.

The contents of the datatable are already defined in the XHTML, I just want to use the binding to read the rows back later so that the table contents can be exported into a PDF.

In my XHTML file, I put

<rich:dataTable ... binding="#{backingBean.tableBinding}">

Then, in my backing bean, I declare a member:

import org.richfaces.component.html.HtmlDataTable;
class BackingBean {
   private HtmlDataTable tableBinding ;
   public BackingBean() {
      tableBinding = new HtmlDataTable() ;
   }
   // ... (incl. getters and setters for binding)
 } ;

However, this results in:

java.lang.NullPointerException
   at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:809)

when I try to load the page. Is there something I need to do with the HtmlDataTable variable besides simply constructing it? Is it even possible to use the binding attribute in the way I intend here?


来源: stackexchange

问:
Perform both the normal click and long click at button
I have a single button named as CheckIn.Have a look at my code.

```<code>    checkIn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

       Toast.makeText(HomeSafeActivity.this, "Normal Press", Toast.LENGTH_LONG).show();

    });

    checkIn.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {

            Toast.makeText(HomeSafeActivity.this, "Long press", Toast.LENGTH_LONG).show();

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

Now when i normal press the button the message shows as Normal press.When i Long press the button the message shows as long press as well as Normal press both. What i want that when i long press the button only long press event should triggered not the normal press event.How can i achieve this??

答:
public boolean onLongClick(View v) is boolean returns true if it is clicked
so make return true;</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a single button named as CheckIn.Have a look at my code.

    checkIn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

       Toast.makeText(HomeSafeActivity.this, "Normal Press", Toast.LENGTH_LONG).show();

    });

    checkIn.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {

            Toast.makeText(HomeSafeActivity.this, "Long press", Toast.LENGTH_LONG).show();

            return false;
        }
    });

Now when i normal press the button the message shows as Normal press.When i Long press the button the message shows as long press as well as Normal press both. What i want that when i long press the button only long press event should triggered not the normal press event.How can i achieve this??


问:
aframe adjust camera rotation on mobile
Using Aframe how I can change the camera rotation manually so it works on mobile and still use look-controls?

I've tried via the html attribute like so:

```<code>document
  .querySelector('[camera]')
  .setAttribute('rotation', { x: 0, y: deg, z: 0 })
</code>```

This works fine on desktop however on mobile the look-controls component seems to reset the camera rotation to previous value.

I've setup a demo the issue here, which changes rotation & disables look-controls. Then I set a timeout which re-ables look-controls after 1 sec. https://embed.plnkr.co/WA1rKucPk0cGffrbfrTh/

Pressing any of the html buttons rotates you to a an object and disables the look-controls. 1 sec later the control are re-abled. If you try this on mobile, you'll notice the camera rotates, then 1 sec its reverts when the look-controls are enabled.

Is there some offset I need to reset on mobile too, the lookcontrols.yawObject perhaps?

答:
you need to change the look-controls.js a little bit to make it works,because when on mobile it will not get rotation attribute from the camera entity

function updateOrientation in look-controls.js：

```<code>if (sceneEl.isMobile) {
   // On mobile, do camera rotation with touch events and sensors.
   rotation.x = radToDeg(hmdEuler.x) + radToDeg(pitchObject.rotation.x);
   rotation.y = radToDeg(hmdEuler.y) + radToDeg(yawObject.rotation.y);
   rotation.z = radToDeg(hmdEuler.z);
}
</code>```

Title: aframe adjust camera rotation on mobile

Body:
Using Aframe how I can change the camera rotation manually so it works on mobile and still use look-controls?

I've tried via the html attribute like so:

document
  .querySelector('[camera]')
  .setAttribute('rotation', { x: 0, y: deg, z: 0 })

This works fine on desktop however on mobile the look-controls component seems to reset the camera rotation to previous value.

I've setup a demo the issue here, which changes rotation & disables look-controls. Then I set a timeout which re-ables look-controls after 1 sec. https://embed.plnkr.co/WA1rKucPk0cGffrbfrTh/

Pressing any of the html buttons rotates you to a an object and disables the look-controls. 1 sec later the control are re-abled. If you try this on mobile, you'll notice the camera rotates, then 1 sec its reverts when the look-controls are enabled.

Is there some offset I need to reset on mobile too, the lookcontrols.yawObject perhaps?

Body:
you need to change the look-controls.js a little bit to make it works,because when on mobile it will not get rotation attribute from the camera entity

function updateOrientation in look-controls.js：

if (sceneEl.isMobile) {
   // On mobile, do camera rotation with touch events and sensors.
   rotation.x = radToDeg(hmdEuler.x) + radToDeg(pitchObject.rotation.x);
   rotation.y = radToDeg(hmdEuler.y) + radToDeg(yawObject.rotation.y);
   rotation.z = radToDeg(hmdEuler.z);
}


问:
Facebook LIKE button hiding when page is already LIKED by user
I'm trying to create a page on my site where the Like button should be hidden if the user already likes the page.  If I can't hide it, then maybe there's a way to get a callback when the like button is rendered with a user who already likes the page.  This way I can hide/reveal the iframe myself.

Any clues?

Howie

答:
@Graphain, why are you commenting? You have no valid input.

@Others, I have been trying this too and had it working by looking at the opacity of certain tag's classes but it no longer works again. You can make an api call to /me/likes and go through the returned array to look at each name or id...

Hope that helps.

ContentLicense: CC BY-SA 2.5


问:
jQuery code that set everything to default value every time I hit save
I have a form that has a checkbox; this checkbox when I check it, it disables another form which alternative contact form and set the values in first form which is
main contact to alternative contact. However, when I uncheck it remove "disable"
and set the values in the alternative form to the default. The problem that I am having with my code (which I provide below) is every time I hit save and the checkbox is unchecked. It set the values that inserted to default which is empty string.

```<code>$(".AlternativeContactFields").removeAttr("disabled");
$(".AlternativeContactFields").each(function (index, element) {
  if ($(element).is("input")) {
    $(element).val("");
  } else if ($(element).is("select")) {
    $(element).val(1);
  }
});
</code>```

How can I solve this?

答:
I think this is what you want</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $('#save').click(function() {
    $(".AlternativeContactFields").removeAttr("disabled");
    $(".AlternativeContactFields").each(function (index, element) {
      if ($(element).is("input")) {
        // read the type attribute.
        var type = $(element).attr('type');
        switch(type) {
          case 'checkbox':
          case 'radio':
            // uncheck box
            $(element).prop('checked', false);
            break;
          case 'text':
          default:
            $(element).val("");
            break;
        }
      } else if ($(element).is("select")) {
        $(element).val(1);
      }
    });
  });
});
</script>
<input type="button" value="Save" id="save"/><br/>
<input disabled="disabled" type="checkbox" checked="checked" value="My checkbox 1" class="AlternativeContactFields"/>My checkbox 1<br/>
<input disabled="disabled" type="checkbox" value="My checkbox 2" class="AlternativeContactFields"/>My checkbox 2<br/>
<input disabled="disabled" type="text" value="My textbox value 1" class="AlternativeContactFields"/><br/>
<input disabled="disabled" type="text" value="My textbox value 2" class="AlternativeContactFields"/><br/>
<select disabled="disabled" class="AlternativeContactFields">
  <option value="0">my Option 0</option>
  <option value="1">my Option 1</option>
  <option value="2">my Option 2</option>
</select>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a form that has a checkbox; this checkbox when I check it, it disables another form which alternative contact form and set the values in first form which is
main contact to alternative contact. However, when I uncheck it remove "disable"
and set the values in the alternative form to the default. The problem that I am having with my code (which I provide below) is every time I hit save and the checkbox is unchecked. It set the values that inserted to default which is empty string.

$(".AlternativeContactFields").removeAttr("disabled");
$(".AlternativeContactFields").each(function (index, element) {
  if ($(element).is("input")) {
    $(element).val("");
  } else if ($(element).is("select")) {
    $(element).val(1);
  }
});

How can I solve this?

Body:
I think this is what you want

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $('#save').click(function() {
    $(".AlternativeContactFields").removeAttr("disabled");
    $(".AlternativeContactFields").each(function (index, element) {
      if ($(element).is("input")) {
        // read the type attribute.
        var type = $(element).attr('type');
        switch(type) {
          case 'checkbox':
          case 'radio':
            // uncheck box
            $(element).prop('checked', false);
            break;
          case 'text':
          default:
            $(element).val("");
            break;
        }
      } else if ($(element).is("select")) {
        $(element).val(1);
      }
    });
  });
});
</script>
<input type="button" value="Save" id="save"/><br/>
<input disabled="disabled" type="checkbox" checked="checked" value="My checkbox 1" class="AlternativeContactFields"/>My checkbox 1<br/>
<input disabled="disabled" type="checkbox" value="My checkbox 2" class="AlternativeContactFields"/>My checkbox 2<br/>
<input disabled="disabled" type="text" value="My textbox value 1" class="AlternativeContactFields"/><br/>
<input disabled="disabled" type="text" value="My textbox value 2" class="AlternativeContactFields"/><br/>
<select disabled="disabled" class="AlternativeContactFields">
  <option value="0">my Option 0</option>
  <option value="1">my Option 1</option>
  <option value="2">my Option 2</option>
</select>


问:
Time and coordinates: how can I find this result?
```<code>Longitude,latitude,time
0,1,1
0,1,2
0,1,3
2,4,4
2,5,5
2,4,6
</code>```

My result is: 0,1,1 1 time because they are consecutives and 2,4 2 times because they aren't consecutives in terms of time. How do I calculate this result?

答:
Here is an example, I can’t test as on iPad, Also the -9999 is not perfect, this needs to not be in your data.</p>

```<code>Select x.lat,x.lng,sum(case when lat=nextlat and lng=nextlng then 0 else 1 end ) s
From
(    Select lat,
            lng,
            lead(lat,1,-9999) over (order by time) nextlat ,
             lead(lng,1,-9999) over (order by time) nextlng
     From table
) x
Group by x.lat,x.lng
</code>```

Body:
Longitude,latitude,time
0,1,1
0,1,2
0,1,3
2,4,4
2,5,5
2,4,6

My result is: 0,1,1 1 time because they are consecutives and 2,4 2 times because they aren't consecutives in terms of time. How do I calculate this result?

Body:
Here is an example, I can’t test as on iPad, Also the -9999 is not perfect, this needs to not be in your data.

Select x.lat,x.lng,sum(case when lat=nextlat and lng=nextlng then 0 else 1 end ) s
From
(    Select lat,
            lng,
            lead(lat,1,-9999) over (order by time) nextlat ,
             lead(lng,1,-9999) over (order by time) nextlng
     From table
) x
Group by x.lat,x.lng


问:
Reactive ObjC emit sequence with time interval
I am trying to emit a sequence of numbers with a delay between each emission. I have a NSIndexSet with a series of numbers,

```<code>[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 100)]
</code>```

Now I want to emit each number with a delay,Like emit number 2 few seconds after emitting number 1 and so on. I am new to Reactive ObjC. How can I do this?

I am trying something like this,

```<code>[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, runescapePackages.count-1)].rac_sequence ...
</code>```

Basically I want to emit each item from a background thread and the Subscriber consumes that item in Main Thread.

How to do it in OBJ-C?

答:
There's no built-in operator that does this right away, but it is not too hard to construct by yourself.

You can turn your sequence into a RACSignal via [sequence signal. Also, you can provide a scheduler right there if you want (if not, RAC will create a new scheduler for you)

```<code>RACScheduler *backgroundScheduler = [RACScheduler scheduler];
RACSignal *sequence = [[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 50)]
                                    rac_sequence]
                                   signalWithScheduler:backgroundScheduler];
</code>```

The problem with this signal is, that it emits all values of the sequence right away. Maybe you have tried the delay operation yourself already, but that does not help since it delays all events by the same amount, so they arrive delayed, but still right after each other.

The basic idea to solve this is to paire the number signal with a regular tick.

Here's how you can create a signal that emits events at regular intervals

```<code>RACSignal *tick = [RACSignal interval:0.5 onScheduler:backgroundScheduler];
</code>```

Now in order to "pair them up" you want to use the zip operator, because that waits until both signals have sent their first value until it sends a tuple with both values as its first value, then waits until both sent their second value and so on. Thus, the number values of the sequence have to wait up for their tick events

```<code>[[[[RACSignal zip:@[tick, sequence]] map:^(RACTuple *tuple) {
    return [tuple second];
}] deliverOn:[RACScheduler mainThreadScheduler]]
 subscribeNext:^(id  _Nullable x) {
    NSLog(@"Value: %@", x);
}];
</code>```

Body:
I am trying to emit a sequence of numbers with a delay between each emission. I have a NSIndexSet with a series of numbers,

[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 100)]

Now I want to emit each number with a delay,Like emit number 2 few seconds after emitting number 1 and so on. I am new to Reactive ObjC. How can I do this?

I am trying something like this,

[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, runescapePackages.count-1)].rac_sequence ...

Basically I want to emit each item from a background thread and the Subscriber consumes that item in Main Thread.

How to do it in OBJ-C?

Body:
There's no built-in operator that does this right away, but it is not too hard to construct by yourself.

You can turn your sequence into a RACSignal via [sequence signal. Also, you can provide a scheduler right there if you want (if not, RAC will create a new scheduler for you)

RACScheduler *backgroundScheduler = [RACScheduler scheduler];
RACSignal *sequence = [[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 50)]
                                    rac_sequence]
                                   signalWithScheduler:backgroundScheduler];

The problem with this signal is, that it emits all values of the sequence right away. Maybe you have tried the delay operation yourself already, but that does not help since it delays all events by the same amount, so they arrive delayed, but still right after each other.

The basic idea to solve this is to paire the number signal with a regular tick.

Here's how you can create a signal that emits events at regular intervals

RACSignal *tick = [RACSignal interval:0.5 onScheduler:backgroundScheduler];

Now in order to "pair them up" you want to use the zip operator, because that waits until both signals have sent their first value until it sends a tuple with both values as its first value, then waits until both sent their second value and so on. Thus, the number values of the sequence have to wait up for their tick events

[[[[RACSignal zip:@[tick, sequence]] map:^(RACTuple *tuple) {
    return [tuple second];
}] deliverOn:[RACScheduler mainThreadScheduler]]
 subscribeNext:^(id  _Nullable x) {
    NSLog(@"Value: %@", x);
}];


问:
Constraining a nested 3rd level relationship
I'm building an api using eager loading so i can simply return the user model with its deep relations and it automatically be converted as json. Here's the set up.

```<code>users
    id
    ..

clients
    id
    ..

user_clients
    id
    user_id
    client_id
    ..

campaigns
    id
    ..

client_campaigns
    id
    client_id
    campaign_id
    ..

campaign_activities
    id
    campaign_id
    ..

client_campaign_activity_templates
    id
    campaign_activity_id
    client_id *(templates are unique per client)*
    ..
</code>```

I've setup the models' relationships.

```<code>User
    public function clients() {
        return $this->belongsToMany('App\Client','user_clients');
    }

Client
    public function campaigns() {
        return $this->belongsToMany('App\Campaign','client_campaigns');
    }

Campaign
    public function activities() {
        return $this->hasMany('App\CampaignActivity');
    }

CampaignActivity
    public function templates() {
        return $this->hasMany('App\ClientCampaignActivityTemplate')
    }
</code>```

I have a simple api endpoint to provide a JSON of a User object including its deep relations using eager loading.

```<code>public function getLoggedInUser(Request $request) {
    return \App\User::with('clients.campaigns.activities.templates')->find($request->user()->id);
}
</code>```

Testing this using postman, I can get the user including its deep relations.

```<code>{
    "user": {
        "id": 1,
        "name": "user1",
        "clients": [
            {
                "id": 1,
                "name": "client1",
                "campaigns": [
                    {
                        "id": 1,
                        "name": "campaign1",
                        "activities": [
                            {
                                "id": 1,
                                "name": "activity1",
                                "templates": [
                                    {
                                        "id": 1,
                                        "name": "template1 for client1",
                                        "client_id": 1,
                                        "body": "this is a template.",
                                    }, {
                                        "id": 2,
                                        "name": "template1 for client2",
                                        "client_id": 2,
                                        "body": "This is a template for client2"
                                    }
                                ]
                            }, {
                                "id": 2,
                                "name": "activity2",
                                "templates": []
                            }, {
                                "id": 3,
                                "name": "activity3",
                                "templates": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
}
</code>```

However, on the user->clients->campaigns->activities->templates level, it will list all the templates for that activity. I know based on the code of the relationships of the models above that it's supposed to behave like that.

So the question is How would you filter the templates to filter for both campaign_activity_id and client_id?

I've been experimenting on how to filter the templates so it will only list templates for that activity AND for that client as well. I have a working solution but it's N+1, I'd prefer eloquent approach if possible. I've been scouring with other questions, answers and comments for a closely similar problem, but I had no luck, hence I'm posting this one and seek for your thoughts. Thank you

答:
I think what you need are eager loading constraints.

```<code>public function getLoggedInUser(Request $request) {
    return \App\User::with('clients.campaigns.activities.templates',
        function($query) use($request) {
            $client_ids = Client::whereHas('users', function($q) use($request){
                $q->where('id', $request->user()->id);
            })->pluck('id');
            $query->whereIn('templates.client_id', $client_ids);
        })->find($request->user()->id);
}
</code>```

Not tested but it should only require one additional query.

What I am doing is: define a constraint for your eager loading, namely only show those templates that have a client_id that is in the list (pluck) of Client IDs with a relation to the User.

Body:
I'm building an api using eager loading so i can simply return the user model with its deep relations and it automatically be converted as json. Here's the set up.

users
    id
    ..

clients
    id
    ..

user_clients
    id
    user_id
    client_id
    ..

campaigns
    id
    ..

client_campaigns
    id
    client_id
    campaign_id
    ..

campaign_activities
    id
    campaign_id
    ..

client_campaign_activity_templates
    id
    campaign_activity_id
    client_id *(templates are unique per client)*
    ..

I've setup the models' relationships.

User
    public function clients() {
        return $this->belongsToMany('App\Client','user_clients');
    }

Client
    public function campaigns() {
        return $this->belongsToMany('App\Campaign','client_campaigns');
    }

Campaign
    public function activities() {
        return $this->hasMany('App\CampaignActivity');
    }

CampaignActivity
    public function templates() {
        return $this->hasMany('App\ClientCampaignActivityTemplate')
    }

I have a simple api endpoint to provide a JSON of a User object including its deep relations using eager loading.

public function getLoggedInUser(Request $request) {
    return \App\User::with('clients.campaigns.activities.templates')->find($request->user()->id);
}

Testing this using postman, I can get the user including its deep relations.

{
    "user": {
        "id": 1,
        "name": "user1",
        "clients": [
            {
                "id": 1,
                "name": "client1",
                "campaigns": [
                    {
                        "id": 1,
                        "name": "campaign1",
                        "activities": [
                            {
                                "id": 1,
                                "name": "activity1",
                                "templates": [
                                    {
                                        "id": 1,
                                        "name": "template1 for client1",
                                        "client_id": 1,
                                        "body": "this is a template.",
                                    }, {
                                        "id": 2,
                                        "name": "template1 for client2",
                                        "client_id": 2,
                                        "body": "This is a template for client2"
                                    }
                                ]
                            }, {
                                "id": 2,
                                "name": "activity2",
                                "templates": []
                            }, {
                                "id": 3,
                                "name": "activity3",
                                "templates": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
}

However, on the user->clients->campaigns->activities->templates level, it will list all the templates for that activity. I know based on the code of the relationships of the models above that it's supposed to behave like that.

So the question is How would you filter the templates to filter for both campaign_activity_id and client_id?

I've been experimenting on how to filter the templates so it will only list templates for that activity AND for that client as well. I have a working solution but it's N+1, I'd prefer eloquent approach if possible. I've been scouring with other questions, answers and comments for a closely similar problem, but I had no luck, hence I'm posting this one and seek for your thoughts. Thank you

Body:
I think what you need are eager loading constraints.

public function getLoggedInUser(Request $request) {
    return \App\User::with('clients.campaigns.activities.templates',
        function($query) use($request) {
            $client_ids = Client::whereHas('users', function($q) use($request){
                $q->where('id', $request->user()->id);
            })->pluck('id');
            $query->whereIn('templates.client_id', $client_ids);
        })->find($request->user()->id);
}

Not tested but it should only require one additional query.

What I am doing is: define a constraint for your eager loading, namely only show those templates that have a client_id that is in the list (pluck) of Client IDs with a relation to the User.


问:
adding an object to an empty  in jQuery
I'm attempting

```<code> var a = $("<a/>");
</code>```

then I'm trying to fill this empty variable with the contents of an object, set to variable 'obj'

```<code>obj = {
 Name: " Ben",
 number: 666,
}
</code>```

I have tried to append a using the various methods

```<code>a.append(obj);
a.append("("+obj+")");
</code>```

but if I then do:

```<code>console.log(a)
</code>```

there is no way to tell if the object is now in the link tag. If I look in the console on the site I can see

```<code>([object Object])
</code>```

rather than the contents. Am I missing something?

答:
By just appending the object it is implicitly coerced to a string, hence you see [Object object].

You need to convert the object to a legible string manually. You can do that by using JSON.stringify(), like this:

var $a = $('href="#"/>').appendTo('body');
var obj = {
  Name: " Ben",
  number: 666
};

$a.text(JSON.stringify(obj));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: adding an object to an empty <a/> in jQuery

Body:
I'm attempting

 var a = $("");

then I'm trying to fill this empty variable with the contents of an object, set to variable 'obj'

obj = {
 Name: " Ben",
 number: 666,
}

I have tried to append a using the various methods

a.append(obj);
a.append("("+obj+")");

but if I then do:

console.log(a)

there is no way to tell if the object is now in the link tag. If I look in the console on the site I can see

([object Object])

rather than the contents. Am I missing something?

Body:
By just appending the object it is implicitly coerced to a string, hence you see [Object object].

You need to convert the object to a legible string manually. You can do that by using JSON.stringify(), like this:

var $a = $('<a href="#"/>').appendTo('body');
var obj = {
  Name: " Ben",
  number: 666
};

$a.text(JSON.stringify(obj));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
ModelState.IsValid vs IValidateableObject in MVC3
so according to Gu IValidatableObject.Validate() should get called when a controller validates it's model (i.e. before ModelState.IsValid) however simply making the model implement IValidatableObject doesn't seem to work, because Validate(..) doesn't get called.

Anyone know if there is something else I have to wire up to get this to work?

EDIT:

Here is the code as requested.

```<code>public class LoginModel : IValidatableObject
{
    [Required]
    [Description("Email Address")]
    public string Email { get; set; }

    [Required]
    [Description("Password")]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [DisplayName("Remember Me")]
    public bool RememberMe { get; set; }

    public int UserPk { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var result = DataContext.Fetch( db => {

            var user = db.Users.FirstOrDefault(u => u.Email == Email);

            if (user == null) return new ValidationResult("That email address doesn't exist.");
            if (user.Password != User.CreateHash(Password, user.Salt)) return new ValidationResult("The password supplied is incorrect.");

            UserPk = user.UserPk;
            return null;
        });

        return new List<ValidationResult>(){ result };
    }
}
</code>```

The action. ( I don't do anything special in the Controller...)

```<code>[HttpPost]
public ActionResult Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
        return Redirect(Request.UrlReferrer.AbsolutePath);
    }

    if (ControllerContext.IsChildAction || Request.IsAjaxRequest())
        return View("LoginForm", model);

    return View(model);
}
</code>```

I set a break point on the first line of LoginModel.Validate() and it doesn't seem to get hit.

答: Validation using the DefaultModelBinder is a two stage process. First, Data Annotations are validated. Then (and only if the data annotations validation resulted in zero errors), IValidatableObject.Validate() is called. This all takes place automatically when your post action has a viewmodel parameter. ModelState.IsValid doesn't do anything as such. Rather it just reports whether any item in the ModelState collection has non-empty ModelErrorCollection.

Body:
so according to Gu IValidatableObject.Validate() should get called when a controller validates it's model (i.e. before ModelState.IsValid) however simply making the model implement IValidatableObject doesn't seem to work, because Validate(..) doesn't get called.

Anyone know if there is something else I have to wire up to get this to work?

EDIT:

Here is the code as requested.

public class LoginModel : IValidatableObject
{
    [Required]
    [Description("Email Address")]
    public string Email { get; set; }

    [Required]
    [Description("Password")]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [DisplayName("Remember Me")]
    public bool RememberMe { get; set; }

    public int UserPk { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var result = DataContext.Fetch( db => {

            var user = db.Users.FirstOrDefault(u => u.Email == Email);

            if (user == null) return new ValidationResult("That email address doesn't exist.");
            if (user.Password != User.CreateHash(Password, user.Salt)) return new ValidationResult("The password supplied is incorrect.");

            UserPk = user.UserPk;
            return null;
        });

        return new List<ValidationResult>(){ result };
    }
}

The action. ( I don't do anything special in the Controller...)

[HttpPost]
public ActionResult Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
        return Redirect(Request.UrlReferrer.AbsolutePath);
    }

    if (ControllerContext.IsChildAction || Request.IsAjaxRequest())
        return View("LoginForm", model);

    return View(model);
}

I set a break point on the first line of LoginModel.Validate() and it doesn't seem to get hit.


问:
Check if a process is running using PHP in Linux
I am using kannel to send SMS via PHP. I want to know how can I check if a particular process is running. For kannel to run, a process named bearerbox should be running all time. I want to check if this process is running or not. Because if the process is not running then a mail will be sent to me notifying me about it.

答:
This is the best way

```<code><?php
exec("ps -eo comm,pid | awk '$1 == "."\"gs\""." { print $2 }'", $output);
if ($output != 0) {
    echo "The process gs is running\n";
}
?>
</code>```

in the above code gs is the process that I was checking

Body:
This is the best way

<?php
exec("ps -eo comm,pid | awk '$1 == "."\"gs\""." { print $2 }'", $output);
if ($output != 0) {
    echo "The process gs is running\n";
}
?>

in the above code gs is the process that I was checking


问:
Throw Exception through multiple services
I have a little microservice architecture with 3 depending services. Each service represents a seperate Spring Boot project. If an exception occurs on the lowest level of the architecture I would like to throw it through all other services up to the highest/user endpoint service.

Each service API returns a HttpEntity(Response Entity) including a specific object. I found a lot of possible solutions like ResponseEntityExceptionHandlers but all examples shown for a single service architecture without multiple depending services.

Are there any best practices how to throw an Exception through multiple services with Spring Boot?

答:
Assuming that you have three services A (relates directly on B), b (relates directly on C) and C and user calls your service A, but it can be applied to any number of services.

I will briefly describe you the approach

If error occurs in the service C (exception thrown), your code should catch Exception and return a meaningful response. Simplest I can think of would be a @ControllerAdvice

```<code>@ControllerAdvice
public class GlobalExceptionHandler {

      @ExceptionHandler(YourException.class)
      public ResponseEntity<ApiErrorDto> handleYourException(YourException e) {
      return ResponseEntity
            .status(HttpStatus.BAD_REQUEST) //or any other suitable
            .body(new ApiError(e.getMessage());
     }
}
</code>```

ApiError could be just a basic POJO class with a single field holding the message, or any other field meaningful for your exception handling.

Now when your service B receives response it should check whether it is expected status code or an error status code and act accordingly.

Your ApiError class should be shared between all services so that it can be easily serialized/deserialized everywhere. That way once you receive error you can decide what to do next, one of the scenarios could be throwing another exception to be caught by ExceptionHandler in service B.

It's a starter, you can decide whether you want to return a string message in your ApiError, or maybe some kind of a meaningful code etc. Bottom line is that you should include that information in the response of the service where error occurs and interpret that information in the calling service.

Body:
Assuming that you have three services A (relates directly on B), b (relates directly on C) and C and user calls your service A, but it can be applied to any number of services.

I will briefly describe you the approach

If error occurs in the service C (exception thrown), your code should catch Exception and return a meaningful response. Simplest I can think of would be a @ControllerAdvice

@ControllerAdvice
public class GlobalExceptionHandler {

      @ExceptionHandler(YourException.class)
      public ResponseEntity<ApiErrorDto> handleYourException(YourException e) {
      return ResponseEntity
            .status(HttpStatus.BAD_REQUEST) //or any other suitable
            .body(new ApiError(e.getMessage());
     }
}

ApiError could be just a basic POJO class with a single field holding the message, or any other field meaningful for your exception handling.

Now when your service B receives response it should check whether it is expected status code or an error status code and act accordingly.

Your ApiError class should be shared between all services so that it can be easily serialized/deserialized everywhere. That way once you receive error you can decide what to do next, one of the scenarios could be throwing another exception to be caught by ExceptionHandler in service B.

It's a starter, you can decide whether you want to return a string message in your ApiError, or maybe some kind of a meaningful code etc. Bottom line is that you should include that information in the response of the service where error occurs and interpret that information in the calling service.


问:
sequential call using promise inside loop
i want to perform synchronous operation of functions using promise. I have loop that passes the data to be inserted to insert function and after inserting one row i want to check the no. of rows exists in table hence i am performing select operation.

But the issue is if there are 3 records then it inserts all 3 records and after that my select function gets executed. what i want is after insertion of one record select function gets called.

here is my pseudo code as entire code involves lot of operations

```<code>for(var i=0; data.length ; i++){

 self.executeFeedbackTrack(data);

}

executeFeedbackTrack:function(callInfo){
    var self=this;
   return  self.insertFeedbackTrack(callInfo).then(function(data){

                console.log("insertFeedbackTrack status "+status);

        return self.getFeedbackTrack();

    });
},

getFeedbackTrack :function(){

    return new Promise(function(resolve,reject){
         var objDBFeedbackTrack = new DBFeedbackTrack();
        objDBFeedbackTrack.selectFeedbackTrack(function(arrayCallRegisters){
            if(arrayCallRegisters){

            console.log("notification.js no. of feedbacks "+arrayCallRegisters.length);

            resolve(arrayCallRegisters.length);

            }

        });
    });

},
insertFeedbackTrack :function(callInfo){

return new Promise(function(resolve,reject){
     var objDBFeedbackTrack = new DBFeedbackTrack();
     objDBFeedbackTrack.insertFeedbackTrack(callInfo.callNumber,callInfo.callServiceType,function(status){

             resolve(status);
            $('#loader').hide();

     });
});

}
</code>```

答:
It looks to me like this is caused by executing a series of asynchronous inserts, and assuming that the get of insert n (inside of a .then()) is called before insert n+1 is executed. However, I'm not aware of any such guarantee, in JavaScript; all that I'm familiar with is that then n will be called after insert n, not that it would be called before insert n+1.

What I'd suggest is avoiding this mix of traditional and callback-based code, and instead put the iteration step inside getFeedbackTrack().then. Assuming this understanding of the issue is correct, then something like the following should work:

```<code>function iterate(i) {
    if (i < data.length) {
        obj.insertFeedbackTrack(data[i]).then(function(insertResult) {
            self.getFeedbackTrack().then(function(getResult) {
                // this line is the important one, replacing the `for` loop earlier
                iterate(i+1);
            });
        });
    }
}

iterate(0);
</code>```

By doing that, you would guarantee that insert for the next element does not occur until the current select executes successfully.

Naturally, you may also want to restructure that to use chained .then instead of nested; I used nested rather than chained to emphasize the ordering of callbacks.

Body:
i want to perform synchronous operation of functions using promise. I have loop that passes the data to be inserted to insert function and after inserting one row i want to check the no. of rows exists in table hence i am performing select operation.

But the issue is if there are 3 records then it inserts all 3 records and after that my select function gets executed. what i want is after insertion of one record select function gets called.

here is my pseudo code as entire code involves lot of operations

for(var i=0; data.length ; i++){

 self.executeFeedbackTrack(data);

}

executeFeedbackTrack:function(callInfo){
    var self=this;
   return  self.insertFeedbackTrack(callInfo).then(function(data){

                console.log("insertFeedbackTrack status "+status);

        return self.getFeedbackTrack();

    });
},

getFeedbackTrack :function(){

    return new Promise(function(resolve,reject){
         var objDBFeedbackTrack = new DBFeedbackTrack();
        objDBFeedbackTrack.selectFeedbackTrack(function(arrayCallRegisters){
            if(arrayCallRegisters){

            console.log("notification.js no. of feedbacks "+arrayCallRegisters.length);

            resolve(arrayCallRegisters.length);

            }

        });
    });

},
insertFeedbackTrack :function(callInfo){

return new Promise(function(resolve,reject){
     var objDBFeedbackTrack = new DBFeedbackTrack();
     objDBFeedbackTrack.insertFeedbackTrack(callInfo.callNumber,callInfo.callServiceType,function(status){

             resolve(status);
            $('#loader').hide();

     });
});

}

Body:
It looks to me like this is caused by executing a series of asynchronous inserts, and assuming that the get of insert n (inside of a .then()) is called before insert n+1 is executed. However, I'm not aware of any such guarantee, in JavaScript; all that I'm familiar with is that then n will be called after insert n, not that it would be called before insert n+1.

What I'd suggest is avoiding this mix of traditional and callback-based code, and instead put the iteration step inside getFeedbackTrack().then. Assuming this understanding of the issue is correct, then something like the following should work:

function iterate(i) {
    if (i < data.length) {
        obj.insertFeedbackTrack(data[i]).then(function(insertResult) {
            self.getFeedbackTrack().then(function(getResult) {
                // this line is the important one, replacing the `for` loop earlier
                iterate(i+1);
            });
        });
    }
}

iterate(0);

By doing that, you would guarantee that insert for the next element does not occur until the current select executes successfully.

Naturally, you may also want to restructure that to use chained .then instead of nested; I used nested rather than chained to emphasize the ordering of callbacks.


问:
save and close all currently open excel sheets (python)
I have another script that opens a bunch of excel sheets and exports a bunch of data to them. However, it is incapable of saving those documents automagically. Is there a way in python to grab all the currently open excel sheets, save them, and then close them?</p>

答:
What libraries are you using?

you can use

```<code>for each wb in xl.workbooks:
    wb.close(true)
</code>```

Body:
What libraries are you using?

you can use

for each wb in xl.workbooks:
    wb.close(true)


问:
JavaScript validation for empty input field
I have this input field
<input name="question"/> I want to call IsEmpty function when submit clicking submit button.

I tried the code below but did not work.
any advice?

function IsEmpty() {

  if (document.form.question.value == "") {
    alert("empty");
  }
  return;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Question: <input name="question" /> <br/>

<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" /></code>```

答:
```
       <form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
           <input type="text"   id="name"   name="name" />
           <input type="submit"/>
       </form>
    ```

```

before using above code you have to add the gen_validatorv31.js file

Body:
I have this input field
<input name="question"/> I want to call IsEmpty function when submit clicking submit button.

I tried the code below but did not work.
any advice?

function IsEmpty() {

  if (document.form.question.value == "") {
    alert("empty");
  }
  return;
}

Question: <input name="question" />

<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />

Body:
<pre>
       <form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
           <input type="text"   id="name"   name="name" />
           <input type="submit"/>
       </form>
    </pre>

<script language="JavaScript" type="text/javascript">
  var frmvalidator = new Validator("myform");
  frmvalidator.EnableFocusOnError(false);
  frmvalidator.EnableMsgsTogether();
  frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>

before using above code you have to add the gen_validatorv31.js file


问:
Unity 5.x: Where's the RegisterType<TFrom, TTo>?
I am trying to do something like

```<code>Container.RegisterType<ISettingsService, SettingsService>(new ContainerControlledLifetimeManager());
</code>```

Before v5 I was using using Microsoft.Practices.Unity; for this.
Does the generic method still exists in v5?

答:
It's in the namespace Unity in the Unity.Abstractions package, so

```<code>using Unity;
</code>```

should suffice.

Body:
I am trying to do something like

Container.RegisterType<ISettingsService, SettingsService>(new ContainerControlledLifetimeManager());

Before v5 I was using using Microsoft.Practices.Unity; for this.
Does the generic method still exists in v5?

Body:
It's in the namespace Unity in the Unity.Abstractions package, so

using Unity;

should suffice.


问:
Is possible to expand the border of a lat/long mysql polygon by x miles or km?
So searching for a point within a polygon is quite simple in mysql, doing something like this:

SELECT * FROM table
WHERE ST_CONTAINS(ST_GEOMFROMTEXT('POLYGON((-72.0429540 42.9949644, -72.0405293 42.9929398, -72.0401645 42.9905541, -72.0353365 42.9888747, -72.0326543 42.9897850, -72.0343494 42.9935990, -72.0344567 42.9969733, -72.0367098 42.9980562, -72.0417953 42.9970361, -72.0429540 42.9949644))'), POINT(lat, long))

But let's say I wanted to also find items that are within 1 mile of the border of my polygon. Is there a simple way to this in mysql? My other line of thinking was that maybe I can somehow calculate new points for my polygon, but I'm not sure how I would go about knowing the direction to expand in.

答:
I think I found my own answer digging through the MySQL docs. Instead of expanding the polygon, I can query the shortest distance (in degrees) between two geometries with ST_Distance like so:

SELECT * FROM table
WHERE ST_DISTANCE(ST_GEOMFROMTEXT('POLYGON((-72.0429540 42.9949644, -72.0405293 42.9929398, -72.0401645 42.9905541, -72.0353365 42.9888747, -72.0326543 42.9897850, -72.0343494 42.9935990, -72.0344567 42.9969733, -72.0367098 42.9980562, -72.0417953 42.9970361, -72.0429540 42.9949644))'), ST_GEOMFROMTEXT(CONCAT('POINT(',lat,' ',long,')'))) < 50;

https://dev.mysql.com/doc/refman/5.7/en/spatial-relation-functions-object-shapes.html#function_st-distance


问:
Music Player App - avoid that two music players play at the same time
I am developing a Song Player App using ExoPlayer.
The problem I am currently having is that, on Android 7.x devices, the user is being able to listen to two players at the same time. It seems to be a thing of the new Android versions.

I would like to know if is it possible to avoid this behavior, making the user unable to listen to two players while listening to a media on my app.

答:
You probably need to manage Audio focus in your application.
You can have a look here :
https://developer.android.com/guide/topics/media-apps/audio-focus.html

To avoid every music app playing at the same time, Android introduces
  the idea of audio focus. Only one app can hold audio focus at a time.

When your app needs to output audio, it should request audio focus.

```<code>AudioManager mAudioManager_ = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener_ = new AudioManager.OnAudioFocusChangeListener()
        {   @Override
            public void onAudioFocusChange (int focusChange)
            {   switch (focusChange)
                {   case AudioManager.AUDIOFOCUS_GAIN:
                        Log.e("DEBUG", "##### AUDIOFOCUS_GAIN");
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        Log.e("DEBUG", "##### AUDIOFOCUS_LOSS_TRANSIENT");
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        Log.e("DEBUG", "##### AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                        Log.e("DEBUG", "##### AUDIOFOCUS_LOSS");
                        break;
                }
            }
        };

if (mAudioManager_.requestAudioFocus(mOnAudioFocusChangeListener_, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{   // start play
    // ...
    mAudioManager_.abandonAudioFocus(mOnAudioFocusChangeListener_);
}
</code>```

Body:
You probably need to manage Audio focus in your application.
You can have a look here :
https://developer.android.com/guide/topics/media-apps/audio-focus.html

To avoid every music app playing at the same time, Android introduces
  the idea of audio focus. Only one app can hold audio focus at a time.

When your app needs to output audio, it should request audio focus.

AudioManager mAudioManager_ = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener_ = new AudioManager.OnAudioFocusChangeListener()
        {   @Override
            public void onAudioFocusChange (int focusChange)
            {   switch (focusChange)
                {   case AudioManager.AUDIOFOCUS_GAIN:
                        Log.e("DEBUG", "##### AUDIOFOCUS_GAIN");
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        Log.e("DEBUG", "##### AUDIOFOCUS_LOSS_TRANSIENT");
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        Log.e("DEBUG", "##### AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                        Log.e("DEBUG", "##### AUDIOFOCUS_LOSS");
                        break;
                }
            }
        };

if (mAudioManager_.requestAudioFocus(mOnAudioFocusChangeListener_, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{   // start play
    // ...
    mAudioManager_.abandonAudioFocus(mOnAudioFocusChangeListener_);
}


问:
PowerShell, Exchange 2010 Addressbook
It is possible to access Exchange 2010 Addressbook from a PowerShell Script which is running on a client?
I want to access the addressbook, search by properties and work with the results.

I have not found any tutorial for the EWS and PowerShell.

```<code>[Reflection.Assembly]::LoadFrom("path to ews.dll")

$ExchangeService = new-object ExchangeServiceBinding

$paramName = New-Object UserConfigurationNameType
$paramName.Item = New-Object FolderIdType
$paramName.Name = "CategoryList"

$params = New-Object GetUserConfigurationType
$params.UserConfigurationName = $paramName
$params.UserConfigurationProperties = [UserConfigurationPropertyType]::ALL

$ExchangeService.UseDefaultCredentials
$ExchangeService.Url = "https://path.to.exchange/EWS/Exchange.asmx"
$ExchangeService.GetUserConfiguration($params)
</code>```

答:
You need the Exchange EWS Managed API:

http://msdn.microsoft.com/en-us/library/dd637749.aspx

Title: PowerShell, Exchange 2010 Addressbook

Body:
It is possible to access Exchange 2010 Addressbook from a PowerShell Script which is running on a client?
I want to access the addressbook, search by properties and work with the results.

I have not found any tutorial for the EWS and PowerShell.

[Reflection.Assembly]::LoadFrom("path to ews.dll")

$ExchangeService = new-object ExchangeServiceBinding

$paramName = New-Object UserConfigurationNameType
$paramName.Item = New-Object FolderIdType
$paramName.Name = "CategoryList"

$params = New-Object GetUserConfigurationType
$params.UserConfigurationName = $paramName
$params.UserConfigurationProperties = [UserConfigurationPropertyType]::ALL

$ExchangeService.UseDefaultCredentials
$ExchangeService.Url = "https://path.to.exchange/EWS/Exchange.asmx"
$ExchangeService.GetUserConfiguration($params)


问:
Unable to place condition for a server response in swift 3?
Here I am getting response as String (true or false) from the server by using this I need to place a condition like if jsonObj is true then it need to perform some thing if not it should perform a different thing but here after placing a condition it shows an error that Binary operator cannot be applied to operands of type 'String' and 'Bool' shown in this line if jsonObj == true{ can anyone help me how to place condition to check whether it is true or false ?

```<code>func customerItemsDeleteDownloadJsonWithURL(customerItemsAPI: String){
   let url = URL(string: customerItemsAPI)
   var request = URLRequest(url: url! as URL)
   request.httpMethod = "DELETE"
   request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   request.addValue("Bearer \(self.customerKeyToken!)", forHTTPHeaderField: "Authorization")
   let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
   if error != nil { print(error!); return }
   do {
         if let jsonObj = String(data: data!, encoding: .utf8) {
                print(jsonObj)
                DispatchQueue.main.async {
                if jsonObj == true{

                        }
                        else{

                        }
                    }
               }
           }
           catch {
               print(error)
          }
     }
     task.resume()
}
</code>```

答:
According to the Data output the response is a simple String rather than JSON, Bool or other numeric representations.

So just add double quotes.

```<code>if jsonObj == "true" { ...
</code>```

Side note: There is not need to dispatch this comparison to the main thread.

Body:
Here I am getting response as String (true or false) from the server by using this I need to place a condition like if jsonObj is true then it need to perform some thing if not it should perform a different thing but here after placing a condition it shows an error that Binary operator cannot be applied to operands of type 'String' and 'Bool' shown in this line if jsonObj == true{ can anyone help me how to place condition to check whether it is true or false ?

func customerItemsDeleteDownloadJsonWithURL(customerItemsAPI: String){
   let url = URL(string: customerItemsAPI)
   var request = URLRequest(url: url! as URL)
   request.httpMethod = "DELETE"
   request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   request.addValue("Bearer \(self.customerKeyToken!)", forHTTPHeaderField: "Authorization")
   let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
   if error != nil { print(error!); return }
   do {
         if let jsonObj = String(data: data!, encoding: .utf8) {
                print(jsonObj)
                DispatchQueue.main.async {
                if jsonObj == true{

                        }
                        else{

                        }
                    }
               }
           }
           catch {
               print(error)
          }
     }
     task.resume()
}

Body:
According to the Data output the response is a simple String rather than JSON, Bool or other numeric representations.

So just add double quotes.

if jsonObj == "true" { ...

Side note: There is not need to dispatch this comparison to the main thread.


答:
Try using closures to filter through related models:</p>

```<code>$users = App\User::with([

'clients' => function ($query) {
    $query->where('id', $id);
},

'clients.campaigns' => function ($query) {
    $query->where('id', $id);
}

])->get();
</code>```

Title: Constraining a nested 3rd level relationship

Body:
I'm building an api using eager loading so i can simply return the user model with its deep relations and it automatically be converted as json. Here's the set up.

users
    id
    ..

clients
    id
    ..

user_clients
    id
    user_id
    client_id
    ..

campaigns
    id
    ..

client_campaigns
    id
    client_id
    campaign_id
    ..

campaign_activities
    id
    campaign_id
    ..

client_campaign_activity_templates
    id
    campaign_activity_id
    client_id *(templates are unique per client)*
    ..

I've setup the models' relationships.

User
    public function clients() {
        return $this->belongsToMany('App\Client','user_clients');
    }

Client
    public function campaigns() {
        return $this->belongsToMany('App\Campaign','client_campaigns');
    }

Campaign
    public function activities() {
        return $this->hasMany('App\CampaignActivity');
    }

CampaignActivity
    public function templates() {
        return $this->hasMany('App\ClientCampaignActivityTemplate')
    }

I have a simple api endpoint to provide a JSON of a User object including its deep relations using eager loading.

public function getLoggedInUser(Request $request) {
    return \App\User::with('clients.campaigns.activities.templates')->find($request->user()->id);
}

Testing this using postman, I can get the user including its deep relations.

{
    "user": {
        "id": 1,
        "name": "user1",
        "clients": [
            {
                "id": 1,
                "name": "client1",
                "campaigns": [
                    {
                        "id": 1,
                        "name": "campaign1",
                        "activities": [
                            {
                                "id": 1,
                                "name": "activity1",
                                "templates": [
                                    {
                                        "id": 1,
                                        "name": "template1 for client1",
                                        "client_id": 1,
                                        "body": "this is a template.",
                                    }, {
                                        "id": 2,
                                        "name": "template1 for client2",
                                        "client_id": 2,
                                        "body": "This is a template for client2"
                                    }
                                ]
                            }, {
                                "id": 2,
                                "name": "activity2",
                                "templates": []
                            }, {
                                "id": 3,
                                "name": "activity3",
                                "templates": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
}

However, on the user->clients->campaigns->activities->templates level, it will list all the templates for that activity. I know based on the code of the relationships of the models above that it's supposed to behave like that.

So the question is How would you filter the templates to filter for both campaign_activity_id and client_id?

I've been experimenting on how to filter the templates so it will only list templates for that activity AND for that client as well. I have a working solution but it's N+1, I'd prefer eloquent approach if possible. I've been scouring with other questions, answers and comments for a closely similar problem, but I had no luck, hence I'm posting this one and seek for your thoughts. Thank you

Body:
Try using closures to filter through related models:

$users = App\User::with([

'clients' => function ($query) {
    $query->where('id', $id);
},

'clients.campaigns' => function ($query) {
    $query->where('id', $id);
}

])->get();


问:
.htaccess language redirect: avoid infinite loop by detecting path segment
I want to detect user's browser language and prepend path segment to base url. For example, one of redirects looks like this:

```<code>RewriteEngine On

RewriteCond %{REQUEST_URI} !^/de
RewriteCond %{REQUEST_URI} ^/
RewriteCond %{HTTP:Accept-Language} !en [NC]
RewriteCond %{HTTP:Accept-Language} de [NC]
RewriteRule ^(.*)$ /de [R=302,L]
</code>```

I understand it like this:
If there is no /de segment after www.domain.com and requesting home page (www.domain.com) and English is not in prefered languages and German is in prefered languages redirect to www.domain.com/de.
My question is why RewriteCond %{REQUEST_URI} !^/de and RewriteCond %{REQUEST_URI} ^/ are always true? Before inserting this redirect in my .htaccess i tested my config here (found in other .htaccess questions) and it worked. If you have another solution i welcome it. Thank you.

答:
Your rule should be refactored to this:

```<code>RewriteEngine On

RewriteCond %{REQUEST_URI} !^/de [NC]
RewriteCond %{HTTP:Accept-Language} !en [NC]
RewriteCond %{HTTP:Accept-Language} de [NC]
RewriteRule ^/?$ /de [R=302,L]
</code>```

RewriteCond %{REQUEST_URI} ^/ will always be true because REQUEST_URI always starts with /. If you use RewriteCond %{REQUEST_URI} ^/$ then it will work as intended. Same thing we could do in RewriteRule ^/?$ as well hence I removed that extra condition from my answer.

Body:
I want to detect user's browser language and prepend path segment to base url. For example, one of redirects looks like this:

RewriteEngine On

RewriteCond %{REQUEST_URI} !^/de
RewriteCond %{REQUEST_URI} ^/
RewriteCond %{HTTP:Accept-Language} !en [NC]
RewriteCond %{HTTP:Accept-Language} de [NC]
RewriteRule ^(.*)$ /de [R=302,L]

I understand it like this:
If there is no /de segment after www.domain.com and requesting home page (www.domain.com) and English is not in prefered languages and German is in prefered languages redirect to www.domain.com/de.
My question is why RewriteCond %{REQUEST_URI} !^/de and RewriteCond %{REQUEST_URI} ^/ are always true? Before inserting this redirect in my .htaccess i tested my config here (found in other .htaccess questions) and it worked. If you have another solution i welcome it. Thank you.

Body:
Your rule should be refactored to this:

RewriteEngine On

RewriteCond %{REQUEST_URI} !^/de [NC]
RewriteCond %{HTTP:Accept-Language} !en [NC]
RewriteCond %{HTTP:Accept-Language} de [NC]
RewriteRule ^/?$ /de [R=302,L]

RewriteCond %{REQUEST_URI} ^/ will always be true because REQUEST_URI always starts with /. If you use RewriteCond %{REQUEST_URI} ^/$ then it will work as intended. Same thing we could do in RewriteRule ^/?$ as well hence I removed that extra condition from my answer.


问:
Wordpress tag cloud: how to remove inline style for font size?
Is there a nice way to remove the inline style from wordpress tag cloud tags? I'd like to set the same size for all tags and do not want inline styles at all if I can help it.

Thanks

答:
Unfortunately Rezens regexp didn't work in my case. You can use the following filter and regexp to remove the whole inline style tag on the output:</p>

```<code>add_filter('wp_generate_tag_cloud', 'myprefix_tag_cloud',10,1);

function myprefix_tag_cloud($tag_string){
  return preg_replace('/style=("|\')(.*?)("|\')/','',$tag_string);
}
</code>```

Body:
Unfortunately Rezens regexp didn't work in my case. You can use the following filter and regexp to remove the whole inline style tag on the output:

add_filter('wp_generate_tag_cloud', 'myprefix_tag_cloud',10,1);

function myprefix_tag_cloud($tag_string){
  return preg_replace('/style=("|\')(.*?)("|\')/','',$tag_string);
}


问:
Flex Builder 3: syntax coloring, add keyword
I wish to know where I can add Keywords for the syntax coloring in Flex Builder - i need to extend it a little for my own sanity.</p>

答:
Window > Flex > Editors > Syntax Coloring

If you are looking for sanity when building Flex apps try flashdevelop (flashdevelop.org)

OwnerDisplayName: Kasper

OwnerDisplayName: Chad Compton


问:
What is the difference between docker Swarm and Swarm mode?
I was wondering if anyone could differentiate between these two.Both of them have similar naming.</p>

答:
Docker Swarm (also Swarm classic) is fundamentally different from Swarm Mode. Native Swarm functionality will continue to be supported in Docker 1.12 release, this is done to preserve backward compatibility.

Docker Swarm (classic):

Separate from Docker Engine and can run as Container

Needs external KV store like Consul, etcd, Zookeeper

Usage example:

```<code>docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>
</code>```

Swarm Mode (new, preferable):

Integrated inside Docker engine

No need of separate external KV store

Usage example:

```<code>docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>
</code>```

Body:
Docker Swarm (also Swarm classic) is fundamentally different from Swarm Mode. Native Swarm functionality will continue to be supported in Docker 1.12 release, this is done to preserve backward compatibility.

Docker Swarm (classic):

Separate from Docker Engine and can run as Container

Needs external KV store like Consul, etcd, Zookeeper

Usage example:

docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>

Swarm Mode (new, preferable):

Integrated inside Docker engine

No need of separate external KV store

Usage example:

docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>


问:
Custom Dialog Layout Issue
I have implemented a Custom Dialog with Relative layout as Parent.. The issue is that the layout height goes match_parent size even i use wrap_content on Relative Layout...................................................................................................................................

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/layoutPopup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:text="Standered Delvery"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="18dp"
        />

    <TextView
        android:id="@+id/item_count_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="6 Items"
        android:textAlignment="center" />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@color/bg_ash"
        >
    </View>
    <ListView
        android:id="@+id/listview_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="12dp">

    </ListView>
</LinearLayout>
<TextView
    android:id="@+id/popup_dismiss_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:text="DISMISS"
    android:textColor="@color/orange"
    />
</code>```

This is the java code

```<code>totalCountTxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            customDialog = new Dialog(mContext);
            customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            customDialog.setContentView(R.layout.popup_item_details_delvery_options);
            customDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            ListView listView=(ListView)customDialog.findViewById(R.id.listview_popup) ;

            TextView count=(TextView)customDialog.findViewById(R.id.item_count_popup);
            count.setText(String.valueOf(arrayListCartModel.get(0).getItemCount())+" Items");

            PopupDelveryOptionsAdapter adapter=new PopupDelveryOptionsAdapter(mContext,arrayListCartModel);
            listView.setAdapter(adapter);
            customDialog.show();
        }
    });
</code>```

Screenshot for a reference

Does Anyone have the answer

答: Use Linear Layout as a parent layout instead of RelativeLayout</p>

Title: Custom Dialog Layout Issue

Body:
I have implemented a Custom Dialog with Relative layout as Parent.. The issue is that the layout height goes match_parent size even i use wrap_content on Relative Layout...................................................................................................................................

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/layoutPopup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:text="Standered Delvery"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="18dp"
        />

    <TextView
        android:id="@+id/item_count_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="6 Items"
        android:textAlignment="center" />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@color/bg_ash"
        >
    </View>
    <ListView
        android:id="@+id/listview_popup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="12dp">

    </ListView>
</LinearLayout>
<TextView
    android:id="@+id/popup_dismiss_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    android:layout_marginRight="10dp"
    android:text="DISMISS"
    android:textColor="@color/orange"
    />

This is the java code

totalCountTxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            customDialog = new Dialog(mContext);
            customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            customDialog.setContentView(R.layout.popup_item_details_delvery_options);
            customDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            ListView listView=(ListView)customDialog.findViewById(R.id.listview_popup) ;

            TextView count=(TextView)customDialog.findViewById(R.id.item_count_popup);
            count.setText(String.valueOf(arrayListCartModel.get(0).getItemCount())+" Items");

            PopupDelveryOptionsAdapter adapter=new PopupDelveryOptionsAdapter(mContext,arrayListCartModel);
            listView.setAdapter(adapter);
            customDialog.show();
        }
    });

Screenshot for a reference

Does Anyone have the answer


问:
What is the fastest method(s) for reading and writing a matrix of Float64 to file in julia
Let x = randn(100, 2). I want to write x to its own file. This file will contain x, and only x, and x will only ever be of type Matrix{Float64}. In the past, I have always used HDF5 for this, but it occurs to me that this is over-kill, since in this setup I will only have one array per file. Note that JLD uses HDF5, and so is also over-kill.

1) What is the fastest method for reading and writing x assuming I will only ever want to read the entire matrix?

2) What is the fastest method for reading and writing x assuming I might want to read a slice of the matrix?

3) What is the fastest method for reading and writing x assuming I might want to read a slice of the matrix, or over-write a slice of the matrix (but not change the matrix size)?

Body:
Julia has two build-in functions readdlm & writedlm for doing this:

julia> x = randn(5, 5)
5×5 Array{Float64,2}:
 -1.2837    -0.641382  0.611415   0.965762   -0.962764
  0.106015  -0.344429  1.40278    0.862094    0.324521
 -0.603751   0.515505  0.381738  -0.167933   -0.171438
 -1.79919   -0.224585  1.05507   -0.753046    0.0545622
 -0.110378  -1.16155   0.774612  -0.0796534  -0.503871

julia> writedlm("txtmat.txt", x, use_mmap=true)

julia> readdlm("txtmat.txt", use_mmap=true)
5×5 Array{Float64,2}:
 -1.2837    -0.641382  0.611415   0.965762   -0.962764
  0.106015  -0.344429  1.40278    0.862094    0.324521
 -0.603751   0.515505  0.381738  -0.167933   -0.171438
 -1.79919   -0.224585  1.05507   -0.753046    0.0545622
 -0.110378  -1.16155   0.774612  -0.0796534  -0.503871

Definitely not the fastest way(use Mmap.mmap directly as DanGetz suggested in the comment if performance is a big deal), but it seems this is the simplest way and the output file is human-readable.


问:
Full Height gmap in primefaces
I'm using primefaces ronin theme and I'm trying to make a full screen gmap no matter what the resolution of the screen is. how ever, unless I state the height in pixels, it won't work.

for example, if i set the height css attribute of the map to 100%, it doesn't show, and if I wrap the gmap with a div container with 100% height, it still doesn't work. how can I make a full screen responsive gmap?

答:
You can show a full screen responsive p:gmap on following way:

Lets assume that p:gmap is defined like this (no need for style attribute)

```<code><p:gmap id="gmap" center="41.381542, 2.122893" zoom="13" type="hybrid" />
</code>```

Place following JavaScript on your page that will do the trick

```<code>         <script>
            function resizeElement(elementId,width,height){
                console.log("Resizing element " + elementId + " W/H="+ width + "/" + height);

                var element = document.getElementById(elementId);

                element.style.width=width+"px";
                element.style.height=height+"px"
            }

            function resizePfGmapFullScreen() {
                var width = window.innerWidth - 20;
                var height = window.innerHeight - 20;

                resizeElement("gmap", width, height);
            }

            window.onload = function() {
                window.dispatchEvent(new Event('resize'));
            };

            window.onresize = function(event) {
                console.log("Screen is resized");

                resizePfGmapFullScreen();
            };
        </script>
</code>```

Advantage of this solution is that p:map will be automatically resized when screen is resized including screen orientation change on mobile devices.

It is tested running on the latest Primefaces version 6.1.

Title: Full Height gmap in primefaces

Body:
You can show a full screen responsive p:gmap on following way:

Lets assume that p:gmap is defined like this (no need for style attribute)

<p:gmap id="gmap" center="41.381542, 2.122893" zoom="13" type="hybrid" />

Place following JavaScript on your page that will do the trick

         <script>
            function resizeElement(elementId,width,height){
                console.log("Resizing element " + elementId + " W/H="+ width + "/" + height);

                var element = document.getElementById(elementId);

                element.style.width=width+"px";
                element.style.height=height+"px"
            }

            function resizePfGmapFullScreen() {
                var width = window.innerWidth - 20;
                var height = window.innerHeight - 20;

                resizeElement("gmap", width, height);
            }

            window.onload = function() {
                window.dispatchEvent(new Event('resize'));
            };

            window.onresize = function(event) {
                console.log("Screen is resized");

                resizePfGmapFullScreen();
            };
        </script>

Advantage of this solution is that p:map will be automatically resized when screen is resized including screen orientation change on mobile devices.

It is tested running on the latest Primefaces version 6.1.


问:
How to restructuring the data by the data's property in Django-Rest-Framework?
I have a Disk serializer, my Disk serializer is bellow :

```<code>class DiskSerializer(ModelSerializer):

    diskessencetype_name = serializers.ReadOnlyField(source='diskEssenceType.name')
    diskostype_name = serializers.ReadOnlyField(source='diskOsType.name')
    class Meta:
        model = Disk
        fields = [
            "id",
            "price",
            "diskessencetype_name",
            "diskostype_name",
        ]
</code>```

The views.py is bellow:

```<code>class DiskListAPIView(ListAPIView):
    serializer_class = DiskSerializer
    permission_classes = []
    queryset = Disk.objects.all()
</code>```

And  that generate the data like bellow:

```<code>[
    {
        "id": 4,
        "price": "5.00",
        "diskessencetype_name": "ssd",
        "diskostype_name": "系统盘"
    },
    {
        "id": 5,
        "price": "6.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "系统盘"
    },
    {
        "id": 6,
        "price": "5.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "数据盘"
    },
    {
        "id": 7,
        "price": "6.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "系统盘"
    },
    {
        "id": 8,
        "price": "6.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "系统盘"
    },
  .....
  ]
</code>```

But I want to search out and constraints to bellow data:

```<code>{
    "系统盘":[{"id":5, "diskessencetype_name":"sas", "price":5.00},.....]
    "数据盘":[{"id":7, "diskessencetype_name":"ssd", "price":7.00},.....]
}
</code>```

You see, they are restructuring by the instance's property(diskostype_name), is there a build-in method to realizer it?

How can I rebuild them?

答:
views.py

```<code>class Postlar(ListAPIView):
    permission_classes = []
    queryset = Disk.objects.all()
    serializer_class = DiskSerializer

    def list(self, request, *args, **kwargs):
        result = {}
        SerializerClass = self.get_serializer_class()
        for u in ["系统盘", "数据盘"]:
            serializer = SerializerClass(Disk.objects.filter(diskOsType__name=u), many=True)
            result[u] = serializer.data

        return Response(result)
</code>```

Body:
I have a Disk serializer, my Disk serializer is bellow :

class DiskSerializer(ModelSerializer):

    diskessencetype_name = serializers.ReadOnlyField(source='diskEssenceType.name')
    diskostype_name = serializers.ReadOnlyField(source='diskOsType.name')
    class Meta:
        model = Disk
        fields = [
            "id",
            "price",
            "diskessencetype_name",
            "diskostype_name",
        ]

The views.py is bellow:

class DiskListAPIView(ListAPIView):
    serializer_class = DiskSerializer
    permission_classes = []
    queryset = Disk.objects.all()

And  that generate the data like bellow:

[
    {
        "id": 4,
        "price": "5.00",
        "diskessencetype_name": "ssd",
        "diskostype_name": "系统盘"
    },
    {
        "id": 5,
        "price": "6.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "系统盘"
    },
    {
        "id": 6,
        "price": "5.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "数据盘"
    },
    {
        "id": 7,
        "price": "6.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "系统盘"
    },
    {
        "id": 8,
        "price": "6.00",
        "diskessencetype_name": "sas",
        "diskostype_name": "系统盘"
    },
  .....
  ]

But I want to search out and constraints to bellow data:

{
    "系统盘":[{"id":5, "diskessencetype_name":"sas", "price":5.00},.....]
    "数据盘":[{"id":7, "diskessencetype_name":"ssd", "price":7.00},.....]
}

You see, they are restructuring by the instance's property(diskostype_name), is there a build-in method to realizer it?

How can I rebuild them?

Body:
views.py

class Postlar(ListAPIView):
    permission_classes = []
    queryset = Disk.objects.all()
    serializer_class = DiskSerializer

    def list(self, request, *args, **kwargs):
        result = {}
        SerializerClass = self.get_serializer_class()
        for u in ["系统盘", "数据盘"]:
            serializer = SerializerClass(Disk.objects.filter(diskOsType__name=u), many=True)
            result[u] = serializer.data

        return Response(result)


问:
Visual Studio Code (1.18) plugin install
Is anyone could confirm that is not possible to install offline .visx plugins on recent VSC?

I'cant do that on 1.18, but on 1.17.2 it works properly.

答:
You should be able to use the cli code --install-extension <path to vsix file> to install any extension.

You obviously should have already downloaded the vsix before doing that and also have code in your path.


问:
Cabal with multiple Library sections
Is it possbile to write a Cabal configuration file, which contains multiple Library sections?

I found in the documentation the description of Library section and Executables sections, so it seems, that it is impossible to put more Library section in one Cabal configuration file.

But what should I do if I'm developing several Haskell libraries and several executables

simultaneously and want to compile and test them all?

答: This is possible in Cabal 2 with internal libraries, so called "convenience" libraries: https://github.com/haskell/cabal/pull/3022. This will not let you install these libraries though, they are just allowed to be composed into the final executables and public library exposed by a .cabal file. If you want to build multiple things in progress, you should use a cabal.project file - http://blog.ezyang.com/2016/05/announcing-cabal-new-build-nix-style-local-builds/ has some information on this.

Title: Cabal with multiple Library sections


问:
UIContainerView stops receiving touch after changing frame
UIContainerView to display a view controller:

Now I am tying to make it full screen when user tap full screen button with this code :

```<code>@IBAction func fullscreen(_ sender: Any) {
        view.goFullscreen()
    }

extension CGAffineTransform {

    static let ninetyDegreeRotation = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
}

extension UIView {

    var fullScreenAnimationDuration: TimeInterval {
        return 0.15
    }

    func minimizeToFrame(_ frame: CGRect) {
        UIView.animate(withDuration: fullScreenAnimationDuration) {
            self.layer.setAffineTransform(.identity)
            self.frame = frame
        }
    }

    func goFullscreen() {
        UIView.animate(withDuration: fullScreenAnimationDuration) {
            self.layer.setAffineTransform(.ninetyDegreeRotation)
            self.frame = UIScreen.main.bounds

        }
    }
}
</code>```

Making view full screen works fine but when viewcontroller is full screen the view stop receiving touch. This happens when I add constraints to the view controller, but when I remove it it works fine. Why this happens and how can I able to both set constraint and receiving touch?

答:
Here is a playground illustrating how you can apply the transform to detected touch point in the superview:</p>

```<code>import UIKit
import PlaygroundSupport

class ViewController: UIViewController {
    private let redView = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(redView)
        redView.translatesAutoresizingMaskIntoConstraints = false
        redView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        redView.heightAnchor.constraint(equalToConstant: 200).isActive = true
        redView.centerXAnchor.constraint(equalTo: redView.superview!.centerXAnchor).isActive = true
        redView.centerYAnchor.constraint(equalTo: redView.superview!.centerYAnchor).isActive = true
        redView.backgroundColor = .red
        redView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap))
        view.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc private func tap(tapGestureRecognizer: UITapGestureRecognizer) {
        let point = tapGestureRecognizer.location(in: redView).applying(redView.transform)
        if redView.bounds.applying(redView.transform).contains(point) {
            print ("You tapped inside")
        } else {
            print("You tapped outside)")
        }
    }
}

let v = ViewController()
PlaygroundPage.current.liveView = v.view
</code>```

Body:
UIContainerView to display a view controller:

Now I am tying to make it full screen when user tap full screen button with this code :

@IBAction func fullscreen(_ sender: Any) {
        view.goFullscreen()
    }

extension CGAffineTransform {

    static let ninetyDegreeRotation = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
}

extension UIView {

    var fullScreenAnimationDuration: TimeInterval {
        return 0.15
    }

    func minimizeToFrame(_ frame: CGRect) {
        UIView.animate(withDuration: fullScreenAnimationDuration) {
            self.layer.setAffineTransform(.identity)
            self.frame = frame
        }
    }

    func goFullscreen() {
        UIView.animate(withDuration: fullScreenAnimationDuration) {
            self.layer.setAffineTransform(.ninetyDegreeRotation)
            self.frame = UIScreen.main.bounds

        }
    }
}

Making view full screen works fine but when viewcontroller is full screen the view stop receiving touch. This happens when I add constraints to the view controller, but when I remove it it works fine. Why this happens and how can I able to both set constraint and receiving touch?

Body:
Here is a playground illustrating how you can apply the transform to detected touch point in the superview:

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {
    private let redView = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(redView)
        redView.translatesAutoresizingMaskIntoConstraints = false
        redView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        redView.heightAnchor.constraint(equalToConstant: 200).isActive = true
        redView.centerXAnchor.constraint(equalTo: redView.superview!.centerXAnchor).isActive = true
        redView.centerYAnchor.constraint(equalTo: redView.superview!.centerYAnchor).isActive = true
        redView.backgroundColor = .red
        redView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap))
        view.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc private func tap(tapGestureRecognizer: UITapGestureRecognizer) {
        let point = tapGestureRecognizer.location(in: redView).applying(redView.transform)
        if redView.bounds.applying(redView.transform).contains(point) {
            print ("You tapped inside")
        } else {
            print("You tapped outside)")
        }
    }
}

let v = ViewController()
PlaygroundPage.current.liveView = v.view


问:
Search Bar in a Navigation Item collapses and gets stuck under status bar upon navigation pop, on iOS 11
I am using the new iOS 11 searchContoller property of a UINavigationItem. I am running iOS 11.0 GM build.

When I perform a push segue whilst the search controller is active, it works fine. When I subsequently pop back, the search bar is collapsed and squashed up in the status bar. I cannot then cancel the search, or edit the search text.

See the following sequence of images:

The final image is showing the appearing of the table during the pop segue to return from a presented view controller back to the table with the search bar. Strangely, this doesn't always happen. It happens 90% of the time, but sometimes it behaves fine. I haven't yet worked out what I am doing differently to make it work. Once the search bar is squashed, I have to force close the app to get back to a sensible state.

The code which sets up the search controller is pretty standard. The relevant bit of viewDidLoad() is as follows:

```<code>searchController = UISearchController(searchResultsController: nil)
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.returnKeyType = .done
searchController.searchBar.placeholder = "Your Library"
searchController.searchBar.searchBarStyle = .minimal

// We will manage the clearing of selections ourselves.
clearsSelectionOnViewWillAppear = false

// Some search bar styles are slightly different on iOS 11
if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
    navigationController!.navigationBar.prefersLargeTitles = true
}
else {
    searchController.searchBar.backgroundColor = tableView.backgroundColor!
    searchController.hidesNavigationBarDuringPresentation = false
    tableView.tableHeaderView = searchController.searchBar
    tableView.setContentOffset(CGPoint(x: 0, y: searchController.searchBar.frame.height), animated: false)
}
</code>```

I've also noticed this issue in Apple's Messages app (see screenshot below), along with Settings, Notes and Mail, so presumably this is an iOS 11 bug.

This only seems to happen when using smaller than default Text Size in Settings -> General -> Accessibility -> Larger Text, and only seems to happen on a physical device (haven't reproduced it in the simulator). In viewDidAppear, searchController.searchBar.frame.height is equal to 0 (but not in viewDidDisappear, not viewWillAppear). The only workaround I have so far is:

```<code>override func viewDidAppear(_ animated: Bool) {
    if #available(iOS 11.0, *), searchController.searchBar.frame.height == 0 {
        navigationItem.searchController?.isActive = false
    }

    super.viewDidAppear(animated)
}
</code>```

Is there a better way to get around this problem?

答:
This bug can be reproduced in iOS 11.1:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.hidesSearchBarWhenScrolling = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if (@available(iOS 11.0, *)) {
        self.navigationItem.hidesSearchBarWhenScrolling = YES;
    }
}
</code>```

Avoiding mutate navigationItem on VC lifecycle events, fixed problem for me

Body:
I am using the new iOS 11 searchContoller property of a UINavigationItem. I am running iOS 11.0 GM build.

When I perform a push segue whilst the search controller is active, it works fine. When I subsequently pop back, the search bar is collapsed and squashed up in the status bar. I cannot then cancel the search, or edit the search text.

See the following sequence of images:

The final image is showing the appearing of the table during the pop segue to return from a presented view controller back to the table with the search bar. Strangely, this doesn't always happen. It happens 90% of the time, but sometimes it behaves fine. I haven't yet worked out what I am doing differently to make it work. Once the search bar is squashed, I have to force close the app to get back to a sensible state.

The code which sets up the search controller is pretty standard. The relevant bit of viewDidLoad() is as follows:

searchController = UISearchController(searchResultsController: nil)
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.returnKeyType = .done
searchController.searchBar.placeholder = "Your Library"
searchController.searchBar.searchBarStyle = .minimal

// We will manage the clearing of selections ourselves.
clearsSelectionOnViewWillAppear = false

// Some search bar styles are slightly different on iOS 11
if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
    navigationController!.navigationBar.prefersLargeTitles = true
}
else {
    searchController.searchBar.backgroundColor = tableView.backgroundColor!
    searchController.hidesNavigationBarDuringPresentation = false
    tableView.tableHeaderView = searchController.searchBar
    tableView.setContentOffset(CGPoint(x: 0, y: searchController.searchBar.frame.height), animated: false)
}

I've also noticed this issue in Apple's Messages app (see screenshot below), along with Settings, Notes and Mail, so presumably this is an iOS 11 bug.

This only seems to happen when using smaller than default Text Size in Settings -> General -> Accessibility -> Larger Text, and only seems to happen on a physical device (haven't reproduced it in the simulator). In viewDidAppear, searchController.searchBar.frame.height is equal to 0 (but not in viewDidDisappear, not viewWillAppear). The only workaround I have so far is:

override func viewDidAppear(_ animated: Bool) {
    if #available(iOS 11.0, *), searchController.searchBar.frame.height == 0 {
        navigationItem.searchController?.isActive = false
    }

    super.viewDidAppear(animated)
}

Is there a better way to get around this problem?

Body:
This bug can be reproduced in iOS 11.1:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.hidesSearchBarWhenScrolling = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if (@available(iOS 11.0, *)) {
        self.navigationItem.hidesSearchBarWhenScrolling = YES;
    }
}

Avoiding mutate navigationItem on VC lifecycle events, fixed problem for me