问:
send data from directive to controller
how can i send data from directive to controller ?
I've try that : http://jsfiddle.net/1xfvuotL/2/
But, i've got this error :

Uncaught TypeError: Cannot read property 'methodToCall' of undefined
  at formateData

My Directive:

```<code>search.directive('donutChartScope', function () {
return {
    restrict: 'E',
    template: '<div style="position:absolute"></div>',
    replace: true,
    scope: {
        title: '@',
        width: '@',
        height: '@',
        data: '=',
        objx: '='
    },
    link: function (scope, element) {

        formateData = function (data, scope) {
            var categorie = data.momsCategorie;
            if (categorie == 'Hors Production') {
                var obj = 'HorsProd';
            }
            else if (categorie == 'Production') {
                var obj = 'Prod';
            }
            else if (categorie == 'Enseigne') {
                var obj = 'Enseigne';
            }
            var array = [];
            var i = 0;
            $.each(scope[obj].Ok, function(idx, elm) {
                array.push([scope[obj].Ok[i].Hostname, scope[obj].Ok[i].NMON, scope[obj].Ok[i].ATR]);
                i++;
            });
            scope.objx.methodToCall(array);
            console.log(array);
        }
</code>```

[...]

```<code>scope.chart = Highcharts.chart(element[0],
                        {
                            chart: {
                                type: 'pie'
                            },
                            title: {
                                text: '',
                                style: {
                                    display: 'none'
                                }
                            },
                            subtitle: {
                                text: '',
                                style: {
                                    display: 'none'
                                }
                            },
                            plotOptions: {
                                pie: {
                                    shadow: false,
                                    center: ['50%', '50%'],
                                    point: {
                                        events: {
                                            click: function (event) {
                                                formateData(this, scope.data[0].drilldown.array);
                                            }
                                        }
                                    }
                                }
                            },
</code>```

And my Controller:

```<code>search.controller('NmonCustomController', function (config, $http, $compile, $q, $scope, query, $mdDialog, $timeout, $rootScope) {

$scope.objx = {};
$scope.objx.methodToCall = function(i) {
    console.log(i);
}
</code>```

Thank you in advance for helping me and sorry for my great english

答:
scope.objx.methodToCall(array);

scope variable in this line points to the argument passed to the formateData function, it does not refer to the scope variable in the link function.

Make sure you pass the correct scope variable in the formateData function call or change the variable names to a different one.

Title: send data from directive to controller

Body:
how can i send data from directive to controller ?
I've try that : http://jsfiddle.net/1xfvuotL/2/
But, i've got this error :

Uncaught TypeError: Cannot read property 'methodToCall' of undefined
  at formateData

My Directive:

search.directive('donutChartScope', function () {
return {
    restrict: 'E',
    template: '

',
    replace: true,
    scope: {
        title: '@',
        width: '@',
        height: '@',
        data: '=',
        objx: '='
    },
    link: function (scope, element) {

        formateData = function (data, scope) {
            var categorie = data.momsCategorie;
            if (categorie == 'Hors Production') {
                var obj = 'HorsProd';
            }
            else if (categorie == 'Production') {
                var obj = 'Prod';
            }
            else if (categorie == 'Enseigne') {
                var obj = 'Enseigne';
            }
            var array = [];
            var i = 0;
            $.each(scope[obj].Ok, function(idx, elm) {
                array.push([scope[obj].Ok[i].Hostname, scope[obj].Ok[i].NMON, scope[obj].Ok[i].ATR]);
                i++;
            });
            scope.objx.methodToCall(array);
            console.log(array);
        }

[...]

scope.chart = Highcharts.chart(element[0],
                        {
                            chart: {
                                type: 'pie'
                            },
                            title: {
                                text: '',
                                style: {
                                    display: 'none'
                                }
                            },
                            subtitle: {
                                text: '',
                                style: {
                                    display: 'none'
                                }
                            },
                            plotOptions: {
                                pie: {
                                    shadow: false,
                                    center: ['50%', '50%'],
                                    point: {
                                        events: {
                                            click: function (event) {
                                                formateData(this, scope.data[0].drilldown.array);
                                            }
                                        }
                                    }
                                }
                            },

And my Controller:

search.controller('NmonCustomController', function (config, $http, $compile, $q, $scope, query, $mdDialog, $timeout, $rootScope) {

$scope.objx = {};
$scope.objx.methodToCall = function(i) {
    console.log(i);
}

Thank you in advance for helping me and sorry for my great english


来源: stackexchange

问:
FlowRouter.go(redirect) gets triggered, but does not actually redirect
```<code>FlowRouter.go(redirect); //gets triggered, but site does not actually redirect until refreshed.
</code>```

I followed this guide to structure my routes:

```<code>var authorised = FlowRouter.group();

var publicRoutes = FlowRouter.group();

FlowRouter.triggers.enter([isUserSignedIn]);

authorised.route('/',{
  name:'root',
  action(){
    BlazeLayout.render('App_body',{ main: 'App_home'});
  }
});

publicRoutes.route('/welcome',{
  name : 'welcome',
  action(){
    BlazeLayout.render('Unauthorised', { main: 'welcome' });
  }
});

function isUserSignedIn(){
  if (!Meteor.user() || Meteor.loggingIn()){
    var route = FlowRouter.current();
    if (route.path != "/welcome") {
      // Set Session to redirect path after login
      Session.set("redirectAfterLogin", route.path);
    }
    console.log("user is not signed in");
    FlowRouter.go('welcome');
  }
};

// Redirect After Login
Accounts.onLogin(function(){
  console.log("Accounts.onLogin()");
  var redirect = Session.get("redirectAfterLogin");
  if (redirect){
    console.log("redirect path exists")
    if(redirect != "/welcome"){
      console.log("redirect is not welcome path, redirect to ", redirect);
      FlowRouter.go(Session.get("redirectAfterLogin"));
    }
  }
  else{
    // if redirect doesn't exist, go "/"
    console.log("no redirection, go root");
    FlowRouter.go('root');
  }
})

// Not Found
FlowRouter.notFound = {
  action() {
    BlazeLayout.render('Unauthorised', { main: 'App_notFound' });
  },
};
</code>```

The code above does the following:

Case 1: Force Session.set("redirectAfterLogin", "/blah");

Logout of the app.

Enter in console Session.set("redirectAfterLogin", "/blah");

Login

Observe the following output in console:

Accounts.onLogin()

redirect path exists

redirect is not welcome path, redirect to  /blah

But I am still on the "Unauthorised" Layout, with "welcome" template".

Press refresh, I get redirected to "Not Found" - this is the correct result.

Case 2: Session.get("redirectAfterLogin") is undefined

Logout of the app.

Enter in console Session.set("redirectAfterLogin");

Login

Observe the following output in console:

Accounts.onLogin()

no redirection, go root

But I am still on the "Unauthorised" Layout, with "welcome" template".

Press refresh, I get redirected to "/" - this is the correct result.

What exactly is hindering the logic here? Please help!

答:
I had this problem when trying to redirect after logout in an event:

```<code>'click .js-logout'() {
    Meteor.logout();

    FlowRouter.go('signin');
},
</code>```

My quick solution was to add timeout for calling router:

```<code>'click .js-logout'() {
    Meteor.logout();

    // we have to do redirect a bit later because logout is interfering the redirection
    setTimeout(
      () => {
        FlowRouter.go('signin');
      }, 100
    );
 },
</code>```

You might want to increase the timeout.

ContentLicense: CC BY-SA 3.0

Body:
FlowRouter.go(redirect); //gets triggered, but site does not actually redirect until refreshed.

I followed this guide to structure my routes:

var authorised = FlowRouter.group();

var publicRoutes = FlowRouter.group();

FlowRouter.triggers.enter([isUserSignedIn]);

authorised.route('/',{
  name:'root',
  action(){
    BlazeLayout.render('App_body',{ main: 'App_home'});
  }
});

publicRoutes.route('/welcome',{
  name : 'welcome',
  action(){
    BlazeLayout.render('Unauthorised', { main: 'welcome' });
  }
});

function isUserSignedIn(){
  if (!Meteor.user() || Meteor.loggingIn()){
    var route = FlowRouter.current();
    if (route.path != "/welcome") {
      // Set Session to redirect path after login
      Session.set("redirectAfterLogin", route.path);
    }
    console.log("user is not signed in");
    FlowRouter.go('welcome');
  }
};

// Redirect After Login
Accounts.onLogin(function(){
  console.log("Accounts.onLogin()");
  var redirect = Session.get("redirectAfterLogin");
  if (redirect){
    console.log("redirect path exists")
    if(redirect != "/welcome"){
      console.log("redirect is not welcome path, redirect to ", redirect);
      FlowRouter.go(Session.get("redirectAfterLogin"));
    }
  }
  else{
    // if redirect doesn't exist, go "/"
    console.log("no redirection, go root");
    FlowRouter.go('root');
  }
})

// Not Found
FlowRouter.notFound = {
  action() {
    BlazeLayout.render('Unauthorised', { main: 'App_notFound' });
  },
};

The code above does the following:

Case 1: Force Session.set("redirectAfterLogin", "/blah");

Logout of the app.

Enter in console Session.set("redirectAfterLogin", "/blah");

Login

Observe the following output in console:

Accounts.onLogin()

redirect path exists

redirect is not welcome path, redirect to  /blah

But I am still on the "Unauthorised" Layout, with "welcome" template".

Press refresh, I get redirected to "Not Found" - this is the correct result.

Case 2: Session.get("redirectAfterLogin") is undefined

Logout of the app.

Enter in console Session.set("redirectAfterLogin");

Login

Observe the following output in console:

Accounts.onLogin()

no redirection, go root

But I am still on the "Unauthorised" Layout, with "welcome" template".

Press refresh, I get redirected to "/" - this is the correct result.

What exactly is hindering the logic here? Please help!

Body:
I had this problem when trying to redirect after logout in an event:

'click .js-logout'() {
    Meteor.logout();

    FlowRouter.go('signin');
},

My quick solution was to add timeout for calling router:

'click .js-logout'() {
    Meteor.logout();

    // we have to do redirect a bit later because logout is interfering the redirection
    setTimeout(
      () => {
        FlowRouter.go('signin');
      }, 100
    );
 },

You might want to increase the timeout.


问:
Batch file - rename folder within folder but do not know folder name
Hi hope someone can advise:

I extract a folder using 7-zip to a folder called xyz

Inside xyz it then holds the name of the folder I extracted but this changes based on each extraction so cannot hard code my batch file, this subfolder (call it abc [The extraction only every contains 1 folder]) then abc contains standard folders I need to copy to another location.

The problem I have is that I need to either rename the abc to a known items so I can set my path variable or I need to be able to access it regardless of its name and then copy sub folders out to where I need them

My attempts to copy the contents of abc or rename (move) folder abc have failed any suggestions appropriated, below is what I have already tried

Attempt to copy folder contents
c:\xyz>xcopy c:\xyz*\ c:\newlocation

c:\xyz>xcopy c:\xyz** c:\newlocation

Attempt to rename the abc folder
c:\xyz>dir /o-n move "*" c:\xyz\newname

Thanks
Andy

答:
Rename the subfolder of xyz with unknown name to a fixed name first:

```<code>for %%g in (xyz) do ren %%g fixed
</code>```

Body:
Rename the subfolder of xyz with unknown name to a fixed name first:

for %%g in (xyz) do ren %%g fixed


问:
Store object into array and group all array with the same value in PHP
I'm working on array right now and I need to arrange this based on value.

```<code>{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                },
            ]
        }
    }
</code>```

What I need to do is to store this object into array and group all question based on segment_name like this:

```<code>{
    "data":[
         {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role "
                    "question_collection": [
                        {
                            "id": 4,
                            "question": "How old are you?"
                        }
                    ]

                },
                {
                    "segment_name": "360 Segments",
                    "question_collection":[
                        {
                           "id": 1,
                           "question": "What is your food?"
                        },
                        {
                             "id": 2,
                            "question": "sample question"
                         }
                    ]
                },

            ]
        }
    ]
}
</code>```

And this is what I've tried to do:

```<code> $array_value =[];
        foreach ($query AS $key => &$data) {
            $array_value['id'] = $data['id'];
            $array_value['title'] = $data['title'];
            $array_value['emp_position'] = $data['position'];
            $array_value['rating'] = $data['rating_count'];

            if ( is_array($data) ) {
               $array_value['segments'][$key]['segment_name'] = $data['segment'];
               $array_value['segments'][$key]['question'] = $data['question'];
            }

        }
</code>```

答:
Here try my answer. I've just editted your existing code so you won't confuse that much. Nothing much to explain here. I included some explaination in my comment.

CODE

```<code>$array_value =[];
foreach ($query AS $key => &$data) {
    $array_value['id'] = $data['id'];
    $array_value['title'] = $data['title'];
    $array_value['emp_position'] = $data['position'];
    $array_value['rating'] = $data['rating_count'];

    if ( is_array($data) ) {

        // Check if segment is already added
        $has_segment = false;
        $segment_key = null;

        foreach($array_value['segments'] as $key2 => $val){
            //If segment is already added get the key
            if($val['segment_name'] == $data['segment']){
                $segment_key = $key2;
                $has_segment = true;
                break;
            }
        }
        // if segment does not exists. create a new array for new segment
        if(!$has_segment){
            $array_value['segments'] = array();
        }
        // If new segment, get the index
        $segment_key = count($array_value['segments']) - 1;

        // If new segment, create segment and question collection array
        if(!array_key_exists('question_collection', $array_value['segments'][$segment_key])){
            $array_value['segments'][$segment_key]['segment_name'] = $data['segment'];
            $array_value['segments'][$segment_key]['question_collection'] = array();
        }
        //Add the id for question collectiona rray
        $array_value['segments'][$segment_key]['question_collection'][] = array(
            "id" =>  $data['question_id'],
            "question" =>  $data['question']
        );
    }
}
</code>```

Body:
I'm working on array right now and I need to arrange this based on value.

{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                },
            ]
        }
    }

What I need to do is to store this object into array and group all question based on segment_name like this:

{
    "data":[
         {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role "
                    "question_collection": [
                        {
                            "id": 4,
                            "question": "How old are you?"
                        }
                    ]

                },
                {
                    "segment_name": "360 Segments",
                    "question_collection":[
                        {
                           "id": 1,
                           "question": "What is your food?"
                        },
                        {
                             "id": 2,
                            "question": "sample question"
                         }
                    ]
                },

            ]
        }
    ]
}

And this is what I've tried to do:

 $array_value =[];
        foreach ($query AS $key => &$data) {
            $array_value['id'] = $data['id'];
            $array_value['title'] = $data['title'];
            $array_value['emp_position'] = $data['position'];
            $array_value['rating'] = $data['rating_count'];

            if ( is_array($data) ) {
               $array_value['segments'][$key]['segment_name'] = $data['segment'];
               $array_value['segments'][$key]['question'] = $data['question'];
            }

        }

Body:
Here try my answer. I've just editted your existing code so you won't confuse that much. Nothing much to explain here. I included some explaination in my comment.

CODE

$array_value =[];
foreach ($query AS $key => &$data) {
    $array_value['id'] = $data['id'];
    $array_value['title'] = $data['title'];
    $array_value['emp_position'] = $data['position'];
    $array_value['rating'] = $data['rating_count'];

    if ( is_array($data) ) {

        // Check if segment is already added
        $has_segment = false;
        $segment_key = null;

        foreach($array_value['segments'] as $key2 => $val){
            //If segment is already added get the key
            if($val['segment_name'] == $data['segment']){
                $segment_key = $key2;
                $has_segment = true;
                break;
            }
        }
        // if segment does not exists. create a new array for new segment
        if(!$has_segment){
            $array_value['segments'] = array();
        }
        // If new segment, get the index
        $segment_key = count($array_value['segments']) - 1;

        // If new segment, create segment and question collection array
        if(!array_key_exists('question_collection', $array_value['segments'][$segment_key])){
            $array_value['segments'][$segment_key]['segment_name'] = $data['segment'];
            $array_value['segments'][$segment_key]['question_collection'] = array();
        }
        //Add the id for question collectiona rray
        $array_value['segments'][$segment_key]['question_collection'][] = array(
            "id" =>  $data['question_id'],
            "question" =>  $data['question']
        );
    }
}


问:
Code to use tab bar controller in iphone
i m new to iphone programming. can anybody tell me Code to use tab bar controller in iphone.
Thanks in advance.</p>

答:
http://icodeblog.com/2008/09/28/uitabbar-iphone-tutorial/

This one explains it better:
http://howtomakeiphoneapps.com/2010/07/how-can-i-add-tabs-programmatically-to-uitabbar/

ContentLicense: CC BY-SA 2.5


问:
KafkaStreams processor partition re-assignment behavior
Suppose I have a basic KafkaStreams application with one topic (having  multiple partitions) and one processor type handling the messages as follows:

```<code>    builder.stream(topic)
           .process(() -> new MyProcessor());
</code>```

Can the following scenario occur or not? For a particular instance of MyProcessor, say M (i.e. the particular java object obtained through invocation of the processor supplier), and for a particular partition of the topic, say P,

at some time t1, M receives messages from P

at a later point t2, P is revoked from M so M does not receive messages from P anymore (e.g. because an extra worker was started which handles P)

at a later point, t3, M receives messages again from P

I checked the documentation on how stream tasks relate to Kafka topic partitions but I did not find detailed information on how this relates to the construction and deletion of processor instances and/or (un-)assigment of topic partitions to existing processors when rebalancing occurs.

答:
In Kafka Streams, the "unit of processing" is called a stream task.

Tasks can be stateful and/or stateless.  When a rebalancing event happens, a task running on one instance (say, M) of your application may be moved to another instance of your application.

There's a 1-1 mapping between topic partitions and stream tasks, which guarantees that one and only one task will process data from a particular partition.  For example, if task 3 is responsible to read from and process in partition P, then when task 3 is moved from instance M to another instance M', then M will stop reading P (because it no longer runs the task 3), and M' (where task 3 runs now) will resume/continue to process P.

at some time t1, M receives messages from P

Let's say the stream task responsible for processing the topic partition P is called task(P).  At time t1, M happens to be the app instance that is running task(P).  This is the situation at point #1 above.

at a later point t2, P is revoked from M so M does not receive messages from P anymore (e.g. because an extra worker was started which handles P)

Here, another instance of the application (you referred to this instance as "extra worker") becomes responsible for running task(P).  Here, task(P) will be migrated automatically from the original app instance M to the new instance M'.  Any state that was managed by task(P) (e.g., when the task was doing a stateful operation such as a join or an aggregation) will of course be migrated together with the task.  When task(P) is being migrated, also the responsibility for reading from and processing the topic partition P will move from app instance M to M'.

Perhaps don't think too much in terms of "which app instance is handling topic partition P?"  Rather, a particular partition is always handled by a particular stream task, and stream tasks may move across app instances.  (Of course, Kafka's Streams API will prevent unnecessary task migrations to ensure the processing of your application stays efficient.)

at a later point, t3, M receives messages again from P

This means that, at time t3, M has been assigned the task task(P) again as a result of another rebalancing event -- perhaps because the other app instance M' was taken down, or something else happened that required task migration.

Asked in the comments to this answer: It would also be useful though to have a sentence or two about the state migration. It's not like the binary/physical data is taken from one RocksDB instance and passed over to another. Obviously, the state is re-built based on fault-tolerance mechanism.

Stateful tasks use state stores to, well, persistent state information. These state stores are fault-tolerant. The source of truth for these state stores is Kafka itself: any changes to a state store (e.g., incrementing a counter) are backed up to Kafka in a streaming manner—similar to storing the CDC stream of a database table into Kafka topics (these are normal topics but often called 'changelog topics'). Then, when a task dies or is migrated to another container/VM/machine, the task's state store(s) are restored in the task's new container/VM/machine by reading from Kafka (think: streaming-backup / streaming-restore). This restores the state store(s) to exactly how they looked like on the original container, without any data loss or duplication.

A stream task uses RocksDB to materialize a state store locally (like in the task's container) for optimization purposes. Think of these local RocksDB instances as caches that are ok to be lost with regards to data safety, because the durable storage of the state data is Kafka, as described above.

Body:
Suppose I have a basic KafkaStreams application with one topic (having  multiple partitions) and one processor type handling the messages as follows:

    builder.stream(topic)
           .process(() -> new MyProcessor());

Can the following scenario occur or not? For a particular instance of MyProcessor, say M (i.e. the particular java object obtained through invocation of the processor supplier), and for a particular partition of the topic, say P,

at some time t1, M receives messages from P

at a later point t2, P is revoked from M so M does not receive messages from P anymore (e.g. because an extra worker was started which handles P)

at a later point, t3, M receives messages again from P

I checked the documentation on how stream tasks relate to Kafka topic partitions but I did not find detailed information on how this relates to the construction and deletion of processor instances and/or (un-)assigment of topic partitions to existing processors when rebalancing occurs.

ContentLicense: CC BY-SA 4.0


问:
Can I use OpenGL GLES instead of full OpelGL on desktop?
I want to learn OpenGL to program a game in C language but I am a little confused about which library choose, the intention is to generate a C library with the game logic and using Android NDK to interface with the resources in phones.

I found an example that use GLESv2 library and this works well, I think I know that the GLES library was created because mobile devices can't use full OpenGL library.

but the real question is: Is GLES a subset of full OpelGL library in order that I can build and run my game app using GLES library on linux desktop?

Can you give me a clue if I'm going the right way with these library?

答:
Is GLES a subset of full OpelGL library in order that I can build and
  run my game app using GLES library on linux desktop?

No, it is not. OpenGLES is a separate spec.

That said, it's very close to being a subset of OpenGL. It would be a perfectly sensible approach to have shared OpenGL code that you compile into both your Linux and Android executables. You'd have to be careful to only use functionality supported by OpenGLES and you might find you need the odd #if to account for slight differences in the APIs, but 95%+ of the code could work across both APIs.

The alternative is to use the OpenGLES API on desktop. gzh's answer implies that Linux ships with GLES which would make life easy. But if it doesn't you could look at tools like PowerVR's emulator (pvrvframe) or Mali's emulator. My only experience is using pvrvframe on Windows, which worked very well for us - performance was noticeably worse than non-emulated codepaths, but it still managed to run a demanding mobile game at playable framerates.


问:
What does the "find" permission do in webextensions
On the docs: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/permissions I saw that one of the api permissions is find, but it gave no explanation of what it does.

I'm guessing that it allows me to retrieve the Ctrl-F find box searches, but I have no idea where to find the documentation on how to actually do that.

Any ideas?

答:
It lets you use this API: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/find. If you don't request the permission in manifest.json, you don't have access to the find API.

Functions:

find.find()

```<code>Find text in a web page.
</code>```

find.highlightResults()

```<code>Highlight the last set of matches found.
</code>```

find.removeHighlighting()

```<code>Remove any highlighting.
</code>```

Body:
It lets you use this API: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/find. If you don't request the permission in manifest.json, you don't have access to the find API.

Functions:

find.find()

Find text in a web page.

find.highlightResults()

Highlight the last set of matches found.

find.removeHighlighting()

Remove any highlighting.


问:
Handle Screen Orientation?
When the page loads, first it loads in LANDSCAPE_MODE and then after a few seconds the orientation changes to PORTRAIT_MODE the value </p>

```<code>protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate();

    setContentView(R.layout.layout);

    if(orientation.equals("true"))
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}
</code>```

答:
@Shainu set

```<code> android:screenOrientation = "user"
</code>```

and

update your preference of orientation before jumping to activity.
  The user's current preferred orientation.

For more info: https://developer.android.com/guide/topics/manifest/activity-element.html

Title: Handle Screen Orientation?

Body:
When the page loads, first it loads in LANDSCAPE_MODE and then after a few seconds the orientation changes to PORTRAIT_MODE the value

protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate();

    setContentView(R.layout.layout);

    if(orientation.equals("true"))
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}

Body:
@Shainu set

 android:screenOrientation = "user"

and

update your preference of orientation before jumping to activity.
  The user's current preferred orientation.

For more info: https://developer.android.com/guide/topics/manifest/activity-element.html


问:
XSLT (XPath 1.0) test last and second last character
I wish to make tests in an XPath. In my test I should exclude all values that end with a '9' where the second last character is not a number.

For example:

ABCD9 (should be excluded from the output)

ABC12 (should be included)

My current code is:

<xsl:when test="('9' = substring(sAMAccountName, string-length(sAMAccountName))) and (string(number(substring(sAMAccountName, string-length(sAMAccountName)-1,1))) = NaN)">

I'm pretty sure my first part '9' = substring(sAMAccountName, string-length(sAMAccountName))

is correct, but as soon as I add the second part, it's not working.

I'm not an expert in XSLT, so maybe it's not possible to create a second condition like this?

答: I would suggest to use string-length(translate(substring(sAMAccountName, string-length(sAMAccountName)-1,1)), '0123456789', '') = 0 to check it is a digit or string-length(translate(substring(sAMAccountName, string-length(sAMAccountName)-1,1)), '0123456789', '') = 1 to check the second to last character is not a digit.


问:
Mapboxgl click listener function in Angular2
I have a component in Angular2 in which I have mapboxgl map click listener and function which is called after click is fired. I suppose that it's the lack of my experience or it is mapboxgl specific issue, but I can't figure it out how to pick up variable outside of that function. this.something doesn't work. I guess that it's some kind of scope problem ... Here is the bare essential of the problem (console print out undefined) ...

```<code>public map: Map;
public test: string = 'test';

initialize() {
    this.map.on('click', clickListener);
}

clickListener() {
    console.log(this.test); // undefined
}
</code>```

答:
Try something like:</p>

```<code>public map: Map;
public test: string = 'test';

initialize() {
    this.map.on('click', clickListener.bind(this));
}

clickListener() {
    console.log(this.test); // undefined
}
</code>```

Body:
I have a component in Angular2 in which I have mapboxgl map click listener and function which is called after click is fired. I suppose that it's the lack of my experience or it is mapboxgl specific issue, but I can't figure it out how to pick up variable outside of that function. this.something doesn't work. I guess that it's some kind of scope problem ... Here is the bare essential of the problem (console print out undefined) ...

public map: Map;
public test: string = 'test';

initialize() {
    this.map.on('click', clickListener);
}

clickListener() {
    console.log(this.test); // undefined
}

Body:
Try something like:

public map: Map;
public test: string = 'test';

initialize() {
    this.map.on('click', clickListener.bind(this));
}

clickListener() {
    console.log(this.test); // undefined
}


问:
How do you generate a list of prime numbers using list comprehension from 1 to 10?
So, I've made this code:

```<code>y = 10
prime_num = [x for x in range(1,y) if y%x != 0]
</code>```

It's returned me:

[3, 4, 6, 7, 8, 9]

The purpose of this code is to generate prime numbers within 1 to 10, it returned me an odd number which I do not quiet get. I was expecting this to work since my list comprehension was an attempted replica of:

```<code>def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
        return True
</code>```

Which I've created from codecademy, I've simply changed "x%n == 0" to "x%n != 0".

答:
From your question it is unclear what the problem is and what kind of tools are you expecting to be used.

If you want to get to a list of the first n with a list comprehension only, I am afraid this is not extremely efficient as there is no straightforward way to get to know how many objects are going to be generated beforehand.

If instead you want to obtain the primes in a given range, say below some number num, this can be achieved (more or less efficiently) by:

```<code>num = 10
primes = [
    x for x in range(2, num)
    if all([x % f != 0 for f in range(2, x - 1)])]
</code>```

However, if you define a function for primality test (like is_prime()), you can achieve better performances for large numbers.

In that case, the code would read:

```<code>num = 10
primes = [x for x in range(2, num) if is_prime(x)]
</code>```

Note though that the is_prime() implementation you provide is not particularly efficient.

Also, there are might be more efficient ways of achieving this with list comprehension by addressing some corner cases directly, e.g.:

```<code>num = 10
primes = ([] if num < 2 else [2]) + [x for x in range(3, num, 2) if is_prime(x)]
</code>```

Body:
So, I've made this code:

y = 10
prime_num = [x for x in range(1,y) if y%x != 0]

It's returned me:

[3, 4, 6, 7, 8, 9]

The purpose of this code is to generate prime numbers within 1 to 10, it returned me an odd number which I do not quiet get. I was expecting this to work since my list comprehension was an attempted replica of:

def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
        return True

Which I've created from codecademy, I've simply changed "x%n == 0" to "x%n != 0".

Body:
From your question it is unclear what the problem is and what kind of tools are you expecting to be used.

If you want to get to a list of the first n with a list comprehension only, I am afraid this is not extremely efficient as there is no straightforward way to get to know how many objects are going to be generated beforehand.

If instead you want to obtain the primes in a given range, say below some number num, this can be achieved (more or less efficiently) by:

num = 10
primes = [
    x for x in range(2, num)
    if all([x % f != 0 for f in range(2, x - 1)])]

However, if you define a function for primality test (like is_prime()), you can achieve better performances for large numbers.

In that case, the code would read:

num = 10
primes = [x for x in range(2, num) if is_prime(x)]

Note though that the is_prime() implementation you provide is not particularly efficient.

Also, there are might be more efficient ways of achieving this with list comprehension by addressing some corner cases directly, e.g.:

num = 10
primes = ([] if num < 2 else [2]) + [x for x in range(3, num, 2) if is_prime(x)]


问:
Building android source code error
When i try to building android source code using command make -j4 , i get error :

```<code>*** Done with the cleaning, now starting the real build.
Checking build tools versions...
build/core/base_rules.mk:130:
*** Android/android-ndk-r8d/sources//android/cpufeatures:
MODULE.TARGET.STATIC_LIBRARIES.cpufeatures already defined by Android/android-ndk-r8d/sources/android/cpufeatures。stoped。
</code>```

What is that meaning ,what is the problem ?

答: I had the same problem. It turned out to be because I put NDK in the AOSP directory. One of AOSP's build script tried to do a directory travelsal and included some NDK's config files. After I moved out NDK, problem disappeared.</p>

Title: Building android source code error

Body:
When i try to building android source code using command make -j4 , i get error :

*** Done with the cleaning, now starting the real build.
Checking build tools versions...
build/core/base_rules.mk:130:
*** Android/android-ndk-r8d/sources//android/cpufeatures:
MODULE.TARGET.STATIC_LIBRARIES.cpufeatures already defined by Android/android-ndk-r8d/sources/android/cpufeatures。stoped。

What is that meaning ,what is the problem ?


问:
Jquery: What's faster? .text() or .attr('id')?
just wondering, which of these would be faster?

```<code>if ( $(this).text() == 'Test' )
{
    ...
}
</code>```

or

```<code>if ( $(this).attr('id') == 'Test' )
{
    ...
}
</code>```

or is there a faster way?

or are they both the same?

thanks

答:
By far the fastest would be this.id === 'Test', an optimised version of $(this).attr('id') == 'Test'.

Note that this uses an object property, not attr, and the exact equality operator ===.

NB that checking for the ID will be far, far faster, because text() (depending on your browser's capabilities) internally loops over every single child node and extracts its text value.  Checking for the ID requires only checking for one single attribute.

Body:
just wondering, which of these would be faster?

if ( $(this).text() == 'Test' )
{
    ...
}

or

if ( $(this).attr('id') == 'Test' )
{
    ...
}

or is there a faster way?

or are they both the same?

thanks


问:
SVN Merging a branch to another branch and the trunk
Some background:
I have a project trunk and two branches.  Branch A has changes to it and is waiting for others to review it before I can merge it back to the trunk. In the meantime I'm working on refactoring and cleaning up all of the code in general with Branch B.  I want the changes from Branch A on Branch B so I don't refactor anything that was changed in the Branch A and have weird conflicts.  I plan on merging Branch A back to the trunk in the meantime.

My Question:
If I merge Branch A to Branch B, then I merge Branch A to the trunk, will it cause problems with Branch B when I merge from the trunk to Branch B?  It seems like it would because both the trunk and Branch B at that point will have code that is the same, but was pulled in from Branch A.  Is svn able to handle such a case without it causing conflicts since both Branch B and the trunk were modified independently of one another?

答:
With "cyclic merge" weird (and almost not predictable) results are still very expectable (at least for SVN 1.9.*)

Another additional weighty argument in favor of migration to the Mercurial (where Merge-Hell is just unknown reality)


问:
Post a JSON Array into Spring Boot RestController
I am posting something like this:

```<code>{
  "stuff": [
    {
      "thingId": 1,
      "thingNumber": "abc",
      "countryCode": "ZA"
    },
    {
      "thingId": 2,
      "thingNumber": "xyz",
      "countryCode": "US"
    }
  ]
}
</code>```

I can retrieve the data in the controller as follows:

```<code>@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody Map<String, List <Stuff>> stuffs) {

    return "Hooray";
}
</code>```

What I'd really like to do is to only pass in a List of Stuff into the controller; ie:

```<code>@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody List <Stuff> stuffs) {

    return "I'm sad that this won't work.";
}
</code>```

However, Jackson does not like this. The error I get is the following:

Could not read JSON document: Can not deserialize instance of
  java.util.ArrayList out of START_OBJECT token\n at [Source:
  java.io.PushbackInputStream@2a30a2f4; line: 1, column: 1]; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException: Can
  not deserialize instance of java.util.ArrayList out of START_OBJECT
  token\n at [Source: java.io.PushbackInputStream@2a30a2f4; line: 1,
  column: 1]

I cannot send in the following (since it's not valid JSON):

```<code>    {
      [
        {
          "thingId": 1,
          "thingNumber": "abc",
          "countryCode": "ZA"
        },
        {
          "thingId": 2,
          "thingNumber": "xyz",
          "countryCode": "US"
        }
      ]
    }
</code>```

I am sure that this is something simple, but I cannot distil an answer from my StackOverflow and Google searches.

Any help would be appreciated! :)

答:
Note that if you're trying to get an array of JSON without a Java Class (the Class being "Stuff" in the OP's question) you will need to set up the Spring Boot Controller like this:</p>

```<code>@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody Map<String, Object> [] stuffs) {

    return "Hooray";
}
</code>```

Body:
I am posting something like this:

{
  "stuff": [
    {
      "thingId": 1,
      "thingNumber": "abc",
      "countryCode": "ZA"
    },
    {
      "thingId": 2,
      "thingNumber": "xyz",
      "countryCode": "US"
    }
  ]
}

I can retrieve the data in the controller as follows:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody Map<String, List <Stuff>> stuffs) {

    return "Hooray";
}

What I'd really like to do is to only pass in a List of Stuff into the controller; ie:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody List <Stuff> stuffs) {

    return "I'm sad that this won't work.";
}

However, Jackson does not like this. The error I get is the following:

Could not read JSON document: Can not deserialize instance of
  java.util.ArrayList out of START_OBJECT token\n at [Source:
  java.io.PushbackInputStream@2a30a2f4; line: 1, column: 1]; nested
  exception is com.fasterxml.jackson.databind.JsonMappingException: Can
  not deserialize instance of java.util.ArrayList out of START_OBJECT
  token\n at [Source: java.io.PushbackInputStream@2a30a2f4; line: 1,
  column: 1]

I cannot send in the following (since it's not valid JSON):

    {
      [
        {
          "thingId": 1,
          "thingNumber": "abc",
          "countryCode": "ZA"
        },
        {
          "thingId": 2,
          "thingNumber": "xyz",
          "countryCode": "US"
        }
      ]
    }

I am sure that this is something simple, but I cannot distil an answer from my StackOverflow and Google searches.

Any help would be appreciated! :)

Body:
Note that if you're trying to get an array of JSON without a Java Class (the Class being "Stuff" in the OP's question) you will need to set up the Spring Boot Controller like this:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody Map<String, Object> [] stuffs) {

    return "Hooray";
}


问:
Select query does not complete when using offset-fetch
I have implemented pagination in a web application using Linq, the query generated by Linq looks similar to this one:

```<code>SELECT
    [Extent1].[ID_PLAZO] AS [ID_PLAZO],
    LTRIM(RTRIM([Extent1].[ID_EXPEDIENTE])) AS [ID_EXPEDIENTE],
    [Extent1].[ID_TIPO_PLAZO] AS [ID_TIPO_PLAZO],
    [Extent1].[FECHA_INICIO] AS [FECHA_INICIO],
    [Extent1].[FECHA_FIN] AS [FECHA_FIN],
    [Extent1].[FECHA_EJECUCION_INICIO] AS [FECHA_EJECUCION_INICIO],
    [Extent1].[FECHA_EJECUCION_FIN] AS [FECHA_EJECUCION_FIN]
    FROM   [dbo].[AESEG_PLAZO] AS [Extent1]
    INNER JOIN [dbo].[AESEG_EXPEDIENTE] AS [Extent2] ON [Extent1].[ID_EXPEDIENTE] = [Extent2].[ID_EXPEDIENTE]
    INNER JOIN [dbo].[SAS_CONVOCATORIA] AS [Extent3] ON [Extent2].[ID_CONVOCATORIA] = [Extent3].[CONV_ID_CONVOCATORIA]
    WHERE ([Extent3].[CONV_PREFIJO_EXP] LIKE '%AC15%' ESCAPE '~') OR ([Extent3].[CONV_DESCRIPCION] LIKE '%AC15%' ESCAPE '~')
ORDER BY [Extent1].[ID_PLAZO] ASC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY
</code>```

The query does work and returns 10 results in less than a second, but if I fetch 5 rows it does not end.

I have noticed that the execution plan is a bit different in those cases but I am not an SQL expert. Do you know how to solve this or why is this happening?

fetch 10 rows

fetch 5 rows

答:
It seems that the problem is in the ESCAPE '~' part. Finally, i used this approach to generate a query without that, and it works fine and faster.

http://jendaperl.blogspot.com.es/2011/02/like-in-linq-to-entities.html

Body:
I have implemented pagination in a web application using Linq, the query generated by Linq looks similar to this one:

SELECT
    [Extent1].[ID_PLAZO] AS [ID_PLAZO],
    LTRIM(RTRIM([Extent1].[ID_EXPEDIENTE])) AS [ID_EXPEDIENTE],
    [Extent1].[ID_TIPO_PLAZO] AS [ID_TIPO_PLAZO],
    [Extent1].[FECHA_INICIO] AS [FECHA_INICIO],
    [Extent1].[FECHA_FIN] AS [FECHA_FIN],
    [Extent1].[FECHA_EJECUCION_INICIO] AS [FECHA_EJECUCION_INICIO],
    [Extent1].[FECHA_EJECUCION_FIN] AS [FECHA_EJECUCION_FIN]
    FROM   [dbo].[AESEG_PLAZO] AS [Extent1]
    INNER JOIN [dbo].[AESEG_EXPEDIENTE] AS [Extent2] ON [Extent1].[ID_EXPEDIENTE] = [Extent2].[ID_EXPEDIENTE]
    INNER JOIN [dbo].[SAS_CONVOCATORIA] AS [Extent3] ON [Extent2].[ID_CONVOCATORIA] = [Extent3].[CONV_ID_CONVOCATORIA]
    WHERE ([Extent3].[CONV_PREFIJO_EXP] LIKE '%AC15%' ESCAPE '~') OR ([Extent3].[CONV_DESCRIPCION] LIKE '%AC15%' ESCAPE '~')
ORDER BY [Extent1].[ID_PLAZO] ASC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

The query does work and returns 10 results in less than a second, but if I fetch 5 rows it does not end.

I have noticed that the execution plan is a bit different in those cases but I am not an SQL expert. Do you know how to solve this or why is this happening?

fetch 10 rows

fetch 5 rows


问:
Why searchBar "textDidChange" get server request and got error and crash
Sorry ,I'm beginner of swift.

I have a searchBar and tableView which showing the data.

I also call the Api to server in func "textDidChange".

But when I input or delete text very quickly, my app crashed and I get error message like following row.

How can I prevent this situation?

Thanks.

fatal error: Index out of range

```<code>override func viewDidLoad() {

  self.subscribe = contacts.notifySubject.subscribe({ json in
        self.tableView.reloadData()
    })
}

func doSearch() {
    if let word = searchBar.text {
        if word.isEmpty == false {
            contacts.searchFriend(word)
        }
    } else {
        tableView.reloadData()
    }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchText.isEmpty == true {

        contacts.friends.removeAll(keepingCapacity: false)
        tableView.reloadData()
        return
    }else{

        doSearch()
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if contacts.friends.isEmpty == false {
        return contacts.friends.count
    }
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if contacts.friends.isEmpty == false {

        guard contacts.friends.count != 0 else { return UITableViewCell() } // don't prevent crash

        let cell: SearchTableViewCell = SearchTableViewCell(style: .default, reuseIdentifier: "SearchTableViewCell")
        let user:User = contacts.friends[indexPath.row]
        cell.labelName.text = user.name
        return cell
    }

    let cell = UITableViewCell()

    return cell
}
</code>```

```<code>class Contacts:Model {

   var friends:[User] = [User]()

   func searchFriend(_ word:String) {
    if word.isEmpty {
        return
    }
    self.friends.removeAll(keepingCapacity: false)
    var params:[String:Any] = [String:Any]()
    params["value"] = keyword
    api.searchUser.get( params, { json in

        json.forEach({ (index,data) in

            let user = User(data)
            if user.isExist {
                self.friends.append(user)
            }
        })
        self.notifySubject.onNext(json)
    })
}

}
</code>```

答:
if you are searching on server on text change means you are calling API continuously. before first request completes you are making next request. so when you got response of first request and reloading tableview same time another request completed again reload of table view called. here you removing objects from array when table view reloading was in process hence your app is crashing.
You Should cancel previous api call before making new one.
use NSOperation & NSOperationQueue to achieve this functionality.

Edit

here is example i am using to Search Bus Stop from server
API Call using AFNetworking

```<code> func getStops(sessionManager:AFHTTPSessionManager, parameters:[AnyHashable:Any],completionHandler:@escaping (_ status:Bool, _ responseObject:Any)->()){

        if !ReachabilityManager.shared.isReachable {
            let error = WSError()
            error.errorTitle = "Network error"
            error.errorDescription = "Unable to connect, please check your internet connectivity."
            completionHandler(false,error)
            return
        }

        self.showNetworkActivity()

        if let deviceId = SSKeychain.uniqueDeviceId(){
            sessionManager.requestSerializer.setValue(deviceId, forHTTPHeaderField: X_DEVICE_ID)
        }

        if let accessToken = DBManager.logged?.accessToken{
            sessionManager.requestSerializer.setValue(accessToken, forHTTPHeaderField: X_ACCESS_TOKEN)
        }

        if let simulatedContextId = self.simulatedContextId {
            sessionManager.requestSerializer.setValue(simulatedContextId, forHTTPHeaderField: X_SIMULATE_CONTEXT)
        }
        if let languageCode = NSLocale.current.languageCode{
            sessionManager.requestSerializer.setValue(languageCode, forHTTPHeaderField: X_LOCALE_ID)
        }
        let urlPath =  WSApi.apiVersion + "stops"

        sessionManager.get(urlPath, parameters: parameters, progress: { progress in

        }, success: {[unowned self] task, responseObject in
            self.hideNetworkActivity()
            self.getCurretnContext(task: task)

            var stops = [Stop]()

            if let array = responseObject as? [[AnyHashable:Any]]{
                stops.append(contentsOf: Stop.GetSports(array: array))
            }

            completionHandler(true,stops)

            }, failure: {[unowned self] operation, err in
                self.hideNetworkActivity()
                self.getCurretnContext(task: operation)
                let error = WSError(error: err as NSError)
                error.getStatusCode(operation: operation)
                if error.isUnauthorised{
                    AppDelegate.shared.handleUnAuthorised(error: error)
                    return
                }
                completionHandler(false,error)

        })
    }
</code>```

ViewController Implementation

```<code> protocol StopSearchViewControllerDelegate : NSObjectProtocol {

    /**
     * Called when a place has been selected from the available autocomplete predictions.
     * @param viewController The |StopSearchViewController| that generated the event.
     * @param stop The |Stop| that was returned.
     */
    func viewController(_ viewController: StopSearchViewController, didAutocompleteWith stop: Stop)

    /**
     * Called when a non-retryable error occurred when retrieving autocomplete predictions or place
     * details. A non-retryable error is defined as one that is unlikely to be fixed by immediately
     * retrying the operation.
     * All other error codes are non-retryable.
     * @param viewController The |StopSearchViewController| that generated the event.
     * @param error The |WSError| that was returned.
     */
    func viewController(_ viewController: StopSearchViewController, didFailAutocompleteWithWSError error: WSError)

    /**
     * Called when the user taps the Cancel button in a |StopSearchViewController|.
     * @param viewController The |StopSearchViewController| that generated the event.
     */
    func autocompleteWasCancelled(_ viewController: StopSearchViewController)
}

class StopSearchViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

    weak var delegate:StopSearchViewControllerDelegate?

    fileprivate var stops = [Stop]()

    fileprivate var isNavigationBarHidden = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.tableView.tableHeaderView = UIView()
        self.searchBar.becomeFirstResponder()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.isNavigationBarHidden = self.navigationController?.isNavigationBarHidden ?? false
        self.navigationController?.isNavigationBarHidden = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.isNavigationBarHidden = isNavigationBarHidden
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    fileprivate func loadStops(parameters:[AnyHashable:Any]){
        WSApi.sharedManager.operationQueue.cancelAllOperations()
        WSApi.shared.getStops(sessionManager: WSApi.sharedManager, parameters: parameters) {[weak self] (status, responseObject) in
            if let strongSelf = self {
                strongSelf.stops.removeAll()
                if let stops = responseObject as? [Stop]{
                    if !strongSelf.searchBar.text!.isEmpty{
                        strongSelf.stops.append(contentsOf: stops)
                    }
                }
                strongSelf.tableView.reloadData()
            }
        }
    }

    fileprivate func closeViewController(){
        if let navigationController = self.navigationController{
            navigationController.popViewController(animated: true)
        }else{
            self.dismiss(animated: true, completion: nil)
        }
    }

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }

    override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation{
        return .none
    }

    override var prefersStatusBarHidden: Bool{
        return false
    }

}

extension StopSearchViewController :UITableViewDataSource{

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return stops.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: StopSearchCell.reuseIdentifier, for: indexPath) as! StopSearchCell
        let stop = stops[indexPath.row]
        cell.configureCell(stop: stop)
        return cell
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 20
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let attrs = [NSFontAttributeName : UIFont(name: "Helvetica", size: 14)!, NSForegroundColorAttributeName:UIColor.lightGray]
        let attributedString = NSMutableAttributedString(string:"powered by ", attributes:attrs)
        let bAttrs = [NSFontAttributeName : UIFont(name: "Helvetica", size: 15)!, NSForegroundColorAttributeName:UIColor.darkGray]
        let boldString = NSMutableAttributedString(string:"Change Transit", attributes:bAttrs)
        attributedString.append(boldString)
        let frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 44)
        let label = UILabel(frame: frame)
        label.textAlignment = .center
        label.attributedText = attributedString
        return label
    }

}

extension StopSearchViewController :UITableViewDelegate{

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let stop = stops[indexPath.row]
        self.delegate?.viewController(self, didAutocompleteWith: stop)
       // self.closeViewController()
    }

}

extension StopSearchViewController :UISearchBarDelegate{

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//        guard !searchText.isEmpty else {
//            WSApi.sharedManager.operationQueue.cancelAllOperations()
//            self.stops.removeAll()
//            self.tableView.reloadData()
//            return
//        }
        let parameters = ["data_set_id":WSApi.shared.currentContextId ?? "","search_text": searchText]
        self.loadStops(parameters: parameters)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.delegate?.autocompleteWasCancelled(self)
       // self.closeViewController()
    }

}
</code>```

Body:
Sorry ,I'm beginner of swift.

I have a searchBar and tableView which showing the data.

I also call the Api to server in func "textDidChange".

But when I input or delete text very quickly, my app crashed and I get error message like following row.

How can I prevent this situation?

Thanks.

fatal error: Index out of range

override func viewDidLoad() {

  self.subscribe = contacts.notifySubject.subscribe({ json in
        self.tableView.reloadData()
    })
}

func doSearch() {
    if let word = searchBar.text {
        if word.isEmpty == false {
            contacts.searchFriend(word)
        }
    } else {
        tableView.reloadData()
    }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchText.isEmpty == true {

        contacts.friends.removeAll(keepingCapacity: false)
        tableView.reloadData()
        return
    }else{

        doSearch()
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if contacts.friends.isEmpty == false {
        return contacts.friends.count
    }
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if contacts.friends.isEmpty == false {

        guard contacts.friends.count != 0 else { return UITableViewCell() } // don't prevent crash

        let cell: SearchTableViewCell = SearchTableViewCell(style: .default, reuseIdentifier: "SearchTableViewCell")
        let user:User = contacts.friends[indexPath.row]
        cell.labelName.text = user.name
        return cell
    }

    let cell = UITableViewCell()

    return cell
}

class Contacts:Model {

   var friends:[User] = [User]()

   func searchFriend(_ word:String) {
    if word.isEmpty {
        return
    }
    self.friends.removeAll(keepingCapacity: false)
    var params:[String:Any] = [String:Any]()
    params["value"] = keyword
    api.searchUser.get( params, { json in

        json.forEach({ (index,data) in

            let user = User(data)
            if user.isExist {
                self.friends.append(user)
            }
        })
        self.notifySubject.onNext(json)
    })
}

}

Body:
if you are searching on server on text change means you are calling API continuously. before first request completes you are making next request. so when you got response of first request and reloading tableview same time another request completed again reload of table view called. here you removing objects from array when table view reloading was in process hence your app is crashing.
You Should cancel previous api call before making new one.
use NSOperation & NSOperationQueue to achieve this functionality.

Edit

here is example i am using to Search Bus Stop from server
API Call using AFNetworking

 func getStops(sessionManager:AFHTTPSessionManager, parameters:[AnyHashable:Any],completionHandler:@escaping (_ status:Bool, _ responseObject:Any)->()){

        if !ReachabilityManager.shared.isReachable {
            let error = WSError()
            error.errorTitle = "Network error"
            error.errorDescription = "Unable to connect, please check your internet connectivity."
            completionHandler(false,error)
            return
        }

        self.showNetworkActivity()

        if let deviceId = SSKeychain.uniqueDeviceId(){
            sessionManager.requestSerializer.setValue(deviceId, forHTTPHeaderField: X_DEVICE_ID)
        }

        if let accessToken = DBManager.logged?.accessToken{
            sessionManager.requestSerializer.setValue(accessToken, forHTTPHeaderField: X_ACCESS_TOKEN)
        }

        if let simulatedContextId = self.simulatedContextId {
            sessionManager.requestSerializer.setValue(simulatedContextId, forHTTPHeaderField: X_SIMULATE_CONTEXT)
        }
        if let languageCode = NSLocale.current.languageCode{
            sessionManager.requestSerializer.setValue(languageCode, forHTTPHeaderField: X_LOCALE_ID)
        }
        let urlPath =  WSApi.apiVersion + "stops"

        sessionManager.get(urlPath, parameters: parameters, progress: { progress in

        }, success: {[unowned self] task, responseObject in
            self.hideNetworkActivity()
            self.getCurretnContext(task: task)

            var stops = [Stop]()

            if let array = responseObject as? [[AnyHashable:Any]]{
                stops.append(contentsOf: Stop.GetSports(array: array))
            }

            completionHandler(true,stops)

            }, failure: {[unowned self] operation, err in
                self.hideNetworkActivity()
                self.getCurretnContext(task: operation)
                let error = WSError(error: err as NSError)
                error.getStatusCode(operation: operation)
                if error.isUnauthorised{
                    AppDelegate.shared.handleUnAuthorised(error: error)
                    return
                }
                completionHandler(false,error)

        })
    }

ViewController Implementation

 protocol StopSearchViewControllerDelegate : NSObjectProtocol {

    /**
     * Called when a place has been selected from the available autocomplete predictions.
     * @param viewController The |StopSearchViewController| that generated the event.
     * @param stop The |Stop| that was returned.
     */
    func viewController(_ viewController: StopSearchViewController, didAutocompleteWith stop: Stop)

    /**
     * Called when a non-retryable error occurred when retrieving autocomplete predictions or place
     * details. A non-retryable error is defined as one that is unlikely to be fixed by immediately
     * retrying the operation.
     * All other error codes are non-retryable.
     * @param viewController The |StopSearchViewController| that generated the event.
     * @param error The |WSError| that was returned.
     */
    func viewController(_ viewController: StopSearchViewController, didFailAutocompleteWithWSError error: WSError)

    /**
     * Called when the user taps the Cancel button in a |StopSearchViewController|.
     * @param viewController The |StopSearchViewController| that generated the event.
     */
    func autocompleteWasCancelled(_ viewController: StopSearchViewController)
}

class StopSearchViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

    weak var delegate:StopSearchViewControllerDelegate?

    fileprivate var stops = [Stop]()

    fileprivate var isNavigationBarHidden = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.tableView.tableHeaderView = UIView()
        self.searchBar.becomeFirstResponder()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.isNavigationBarHidden = self.navigationController?.isNavigationBarHidden ?? false
        self.navigationController?.isNavigationBarHidden = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.isNavigationBarHidden = isNavigationBarHidden
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    fileprivate func loadStops(parameters:[AnyHashable:Any]){
        WSApi.sharedManager.operationQueue.cancelAllOperations()
        WSApi.shared.getStops(sessionManager: WSApi.sharedManager, parameters: parameters) {[weak self] (status, responseObject) in
            if let strongSelf = self {
                strongSelf.stops.removeAll()
                if let stops = responseObject as? [Stop]{
                    if !strongSelf.searchBar.text!.isEmpty{
                        strongSelf.stops.append(contentsOf: stops)
                    }
                }
                strongSelf.tableView.reloadData()
            }
        }
    }

    fileprivate func closeViewController(){
        if let navigationController = self.navigationController{
            navigationController.popViewController(animated: true)
        }else{
            self.dismiss(animated: true, completion: nil)
        }
    }

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }

    override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation{
        return .none
    }

    override var prefersStatusBarHidden: Bool{
        return false
    }

}

extension StopSearchViewController :UITableViewDataSource{

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return stops.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: StopSearchCell.reuseIdentifier, for: indexPath) as! StopSearchCell
        let stop = stops[indexPath.row]
        cell.configureCell(stop: stop)
        return cell
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 20
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let attrs = [NSFontAttributeName : UIFont(name: "Helvetica", size: 14)!, NSForegroundColorAttributeName:UIColor.lightGray]
        let attributedString = NSMutableAttributedString(string:"powered by ", attributes:attrs)
        let bAttrs = [NSFontAttributeName : UIFont(name: "Helvetica", size: 15)!, NSForegroundColorAttributeName:UIColor.darkGray]
        let boldString = NSMutableAttributedString(string:"Change Transit", attributes:bAttrs)
        attributedString.append(boldString)
        let frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 44)
        let label = UILabel(frame: frame)
        label.textAlignment = .center
        label.attributedText = attributedString
        return label
    }

}

extension StopSearchViewController :UITableViewDelegate{

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let stop = stops[indexPath.row]
        self.delegate?.viewController(self, didAutocompleteWith: stop)
       // self.closeViewController()
    }

}

extension StopSearchViewController :UISearchBarDelegate{

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//        guard !searchText.isEmpty else {
//            WSApi.sharedManager.operationQueue.cancelAllOperations()
//            self.stops.removeAll()
//            self.tableView.reloadData()
//            return
//        }
        let parameters = ["data_set_id":WSApi.shared.currentContextId ?? "","search_text": searchText]
        self.loadStops(parameters: parameters)
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.delegate?.autocompleteWasCancelled(self)
       // self.closeViewController()
    }

}


问:
Using CSS to hide the last row conditionally
```<code><table>
<tbody>
<tr class = "row">
  <td class = "A"> </td>
  <td class = "A"> </td>
  <td class = "A B"> </td>
</tr>

<tr class = "row">
  <td class = "A B"> </td>
  <td class = "A B"> </td>
  <td class = "A B"> </td>
</tr>
</tbody>
</table>
</code>```

How to hide the last row if all of its children td contains class B.

I have a calendar that dynamically generate the row and I want to hide the  cell that does not belong to this current month (indicate by class "B"). I want to hide the entire row if all of its children satisfy this condition.

Currently I have

```<code>  tbody {
    tr:last-child {
      display: none;
    }
  }
</code>```

But this will not work as sometimes the last row is partially filled and I dont want to hide it.

Not sure if it is possible with pure CSS selector.

答:
You can do it with javascript

let rows = document.querySelectorAll('.row');
rows.forEach((row) => {
  let cols = row.querySelectorAll('td');
  let colsB = row.querySelectorAll('td.B');

  if (cols.length == colsB.length) {
    row.style = "display: none;";
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

    <table>
    <tbody>
    <tr class = "row row1">
      <td class = "A">a </td>
      <td class = "A">a </td>
      <td class = "A B">b </td>
    </tr>

    <tr class = "row row2">
      <td class = "A B">b </td>
      <td class = "A B">b </td>
      <td class = "A B">b </td>
    </tr>
    </tbody>
    </table></code>```

It checks if the total number of td's is equal to total number of td's with the class B then hides the row if so.

Body:
How to hide the last row if all of its children td contains class B.

I have a calendar that dynamically generate the row and I want to hide the  cell that does not belong to this current month (indicate by class "B"). I want to hide the entire row if all of its children satisfy this condition.

Currently I have

  tbody {
    tr:last-child {
      display: none;
    }
  }

But this will not work as sometimes the last row is partially filled and I dont want to hide it.

Not sure if it is possible with pure CSS selector.

Body:
You can do it with javascript

let rows = document.querySelectorAll('.row');
rows.forEach((row) => {
  let cols = row.querySelectorAll('td');
  let colsB = row.querySelectorAll('td.B');

  if (cols.length == colsB.length) {
    row.style = "display: none;";
  }
})

    <table>
    <tbody>
    <tr class = "row row1">
      <td class = "A">a </td>
      <td class = "A">a </td>
      <td class = "A B">b </td>
    </tr>

    <tr class = "row row2">
      <td class = "A B">b </td>
      <td class = "A B">b </td>
      <td class = "A B">b </td>
    </tr>
    </tbody>
    </table>

It checks if the total number of td's is equal to total number of td's with the class B then hides the row if so.


问:
Delphi inheritance and constructor create, override base class create
Lets say I have the following (example) classes:

```<code>TMyClass1 = class(TThread)
  constructor Create(CreateSuspended: Boolean);
end;

TMyClass2 = class(TMyClass1)
  constructor Create(CreateSuspended: Boolean);
end;
</code>```

code:

```<code>constructor TMyClass1.Create(CreateSuspended: Boolean);
begin
  inherited;
end;

constructor TMyClass2.Create(CreateSuspended: Boolean);
begin
  inherited;
end;
</code>```

How can I prevent that TMyClass2.Create does not call the constructor of TMyClass1, but the class is still created properly?

In the real code, create of TMyClass1 does something which should not happen in TMyClass2.create. The TMyClass1 has a lot of functions and procedures, which I do not want to duplicate for TMyClass2.

答:
There are much ways to do this. Just for example, you can use more than one constructors:

```<code>TMyClass1 = class(TThread)
protected
  constructor CreateInternal(CreateSuspended: boolean);
public
  constructor Create(CreateSuspended: boolean);
end;

....

constructor TMyClass1.Create(CreateSuspended: boolean);
begin
  CreateInternal(CreateSuspended);
  ... do other things which shouldn't be in Class2 ...
end;

constructor TMyClass2.Create(CreateSuspended: boolean);
begin
  inherited CreateInternal(CreateSuspended);
  ...
end;
</code>```

But generally it looks like design error. Maybe you should make TMyClass0 = class(TThread), TMyClass1 = class(TMyClass0), TMyClass2 = class(TMyClass0), maybe other, but you description is suspicious.

Body:
Lets say I have the following (example) classes:

TMyClass1 = class(TThread)
  constructor Create(CreateSuspended: Boolean);
end;

TMyClass2 = class(TMyClass1)
  constructor Create(CreateSuspended: Boolean);
end;

code:

constructor TMyClass1.Create(CreateSuspended: Boolean);
begin
  inherited;
end;

constructor TMyClass2.Create(CreateSuspended: Boolean);
begin
  inherited;
end;

How can I prevent that TMyClass2.Create does not call the constructor of TMyClass1, but the class is still created properly?

In the real code, create of TMyClass1 does something which should not happen in TMyClass2.create. The TMyClass1 has a lot of functions and procedures, which I do not want to duplicate for TMyClass2.

Body:
There are much ways to do this. Just for example, you can use more than one constructors:

TMyClass1 = class(TThread)
protected
  constructor CreateInternal(CreateSuspended: boolean);
public
  constructor Create(CreateSuspended: boolean);
end;

....

constructor TMyClass1.Create(CreateSuspended: boolean);
begin
  CreateInternal(CreateSuspended);
  ... do other things which shouldn't be in Class2 ...
end;

constructor TMyClass2.Create(CreateSuspended: boolean);
begin
  inherited CreateInternal(CreateSuspended);
  ...
end;

But generally it looks like design error. Maybe you should make TMyClass0 = class(TThread), TMyClass1 = class(TMyClass0), TMyClass2 = class(TMyClass0), maybe other, but you description is suspicious.


答:
Your code only cares if the possible prime x evenly divides 10. That's not a test of primality.

```<code>cap = 10
prime_nums = [2] + [x for x in range(3, cap+1, 2) if
                    all(x%z!=0 for z in range(2, int(x**(0.5))+1))]
</code>```

Your prime testing here is:

```<code>all(x % z != 0 for z in range(2, int(x**(0.5))+1))
#   ^ not divisible by anything in the range of...
#                       ^ [2..sqrt(x)]
</code>```

Title: How do you generate a list of prime numbers using list comprehension from 1 to 10?

Body:
Your code only cares if the possible prime x evenly divides 10. That's not a test of primality.

cap = 10
prime_nums = [2] + [x for x in range(3, cap+1, 2) if
                    all(x%z!=0 for z in range(2, int(x**(0.5))+1))]

Your prime testing here is:

all(x % z != 0 for z in range(2, int(x**(0.5))+1))
#   ^ not divisible by anything in the range of...
#                       ^ [2..sqrt(x)]


问:
Open activity on firebase notification received in foreground
When my application is open and I receive a notification I want to be able to open the activity associated immediately without the need of the user to tap on the notification.

This question is very similar: Open app on firebase notification received (FCM)

But it opens the app when it is in background, I need to do it when my app is in foreground.

From the firebase documentation:

Notifications delivered when your app is in the background. In this
  case, the notification is delivered to the device’s system tray. A
  user tap on a notification opens the app launcher by default. Messages
  with both notification and data payload, both background and
  foreground. In this case, the notification is delivered to the
  device’s system tray, and the data payload is delivered in the extras
  of the intent of your launcher Activity.

This is my implmentation of onMessageReceived

```<code>@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

       // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification( remoteMessage);
        }
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param remoteMessage FCM message message received.
     */
    private void sendNotification(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, MyActivity.class);

        Map<String, String> hmap ;
        hmap = remoteMessage.getData();
        hmap.get("data_info");
        intent.putExtra("data_info", hmap.get("data_info"));
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

    }
</code>```

I am able to get the notification correctly but the activity only starts once I tap the notification on the system tray.

Is there a way to start the activity without tapping the notification while in foreground?

The method onMessageReceived() from the class MyFirebaseMessagingService that extends FirebaseMessagingService is getting called correctly while in foreground, but the activity is not getting started. I have also tried with the flag FLAG_ACTIVITY_NEW_TASK also with no luck. Thanks in advance.

答:
Creating BroadcastReceiver is the best way of handling for your scenario. But you need to know which activity is being used by the user.

Creating BroadcastReceiver in every activity gives odd look. So Create one BaseActivity which extends Activity. BaseActivity will have the BroadcastReceiver code, and All other activity extends this BaseActivity.

```<code>open class BaseActivity : AppCompatActivity() {

private lateinit var broadcastReceiver: BroadcastReceiver

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            if (p1 != null) {
                handleBroadcastActions(p1)
            }
        }

    }
}

private fun handleBroadcastActions(intent: Intent) {
    when (intent.action) {
        Constants.ACTIVITY_STUFF -> {
            onHandleActivity()
        }
    }
}

protected open fun onHandleActivity() {
    startActivity(intentFor<YourActivity>())
}

override fun onResume() {
    super.onResume()
    registerReceiver(broadcastReceiver, IntentFilter(Constants.ACTIVITY_STUFF))

}

override fun onPause() {
    super.onPause()
    unregisterReceiver(broadcastReceiver)
}}
</code>```

I have added my kotlin code. Hope you can understand :)

Finally you can call this BroadcastReceiver from onMessageReceived() in FirebaseMessagingService.

```<code>override fun onMessageReceived(message: RemoteMessage) {
    sendBroadcast(Intent(Constants.ACTIVITY_STUFF))
}
</code>```

Body:
When my application is open and I receive a notification I want to be able to open the activity associated immediately without the need of the user to tap on the notification.

This question is very similar: Open app on firebase notification received (FCM)

But it opens the app when it is in background, I need to do it when my app is in foreground.

From the firebase documentation:

Notifications delivered when your app is in the background. In this
  case, the notification is delivered to the device’s system tray. A
  user tap on a notification opens the app launcher by default. Messages
  with both notification and data payload, both background and
  foreground. In this case, the notification is delivered to the
  device’s system tray, and the data payload is delivered in the extras
  of the intent of your launcher Activity.

This is my implmentation of onMessageReceived

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

       // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification( remoteMessage);
        }
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param remoteMessage FCM message message received.
     */
    private void sendNotification(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, MyActivity.class);

        Map<String, String> hmap ;
        hmap = remoteMessage.getData();
        hmap.get("data_info");
        intent.putExtra("data_info", hmap.get("data_info"));
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

    }

I am able to get the notification correctly but the activity only starts once I tap the notification on the system tray.

Is there a way to start the activity without tapping the notification while in foreground?

The method onMessageReceived() from the class MyFirebaseMessagingService that extends FirebaseMessagingService is getting called correctly while in foreground, but the activity is not getting started. I have also tried with the flag FLAG_ACTIVITY_NEW_TASK also with no luck. Thanks in advance.

Body:
Creating BroadcastReceiver is the best way of handling for your scenario. But you need to know which activity is being used by the user.

Creating BroadcastReceiver in every activity gives odd look. So Create one BaseActivity which extends Activity. BaseActivity will have the BroadcastReceiver code, and All other activity extends this BaseActivity.

open class BaseActivity : AppCompatActivity() {

private lateinit var broadcastReceiver: BroadcastReceiver

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            if (p1 != null) {
                handleBroadcastActions(p1)
            }
        }

    }
}

private fun handleBroadcastActions(intent: Intent) {
    when (intent.action) {
        Constants.ACTIVITY_STUFF -> {
            onHandleActivity()
        }
    }
}

protected open fun onHandleActivity() {
    startActivity(intentFor<YourActivity>())
}

override fun onResume() {
    super.onResume()
    registerReceiver(broadcastReceiver, IntentFilter(Constants.ACTIVITY_STUFF))

}

override fun onPause() {
    super.onPause()
    unregisterReceiver(broadcastReceiver)
}}

I have added my kotlin code. Hope you can understand :)

Finally you can call this BroadcastReceiver from onMessageReceived() in FirebaseMessagingService.

override fun onMessageReceived(message: RemoteMessage) {
    sendBroadcast(Intent(Constants.ACTIVITY_STUFF))
}


问:
Angular2 - Conditioning loadChildren to load specified modules but using the same route url
Example: www.example.com/dashboard

I want to detect if user is Customer, it will load CustomerDashboardModule, if user is Staff, it's StaffDashboardModule, if user is Admin, it's AdminDashboardModule but the url is still /dashboard

Example code:

```<code>export const routes: Routes = [
{
    path: '',
    component: DashboardComponent,
    children: [
        {
            path: '',
            loadChildren: condition ? 'x' : 'y'
        }
    ]
}];
</code>```

But it doesn't work.

Second problem is

How to detech User? Call an service of CoreModule. A solution is create a static property Injector in CoreModule and inject Injector in its constructor but I don't know if it's a good practice?

答:
You can use a Guard that only when you have access to the route, you can navigate to the URL, when not, you can redirect to another URL.

Angular Router goto 'Milestone 5: Route guards'

Example define a guard in router config:

```<code>const routes: Routes = [
  {
    path: 'adminDashboard',
    component: AdminComponent,
    canActivate: [AdminAuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: '', component: AdminDashboardComponent }
        ],
      }
    ]
  },
  {
    path: 'userDashboard',
    component: UserComponent,
    canActivate: [UserAuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: '', component: UserDashboardComponent }
        ],
      }
    ]
  },
];
</code>```

Guard example with redirect:

```<code>@Injectable()
export class AdminAuthGuard implements CanActivate {

auth: any = {};

constructor(private authService: AuthService, private router: Router) {}

canActivate() {
    if (/*user has privileges check*/) {
        this.router.navigate(['/adminDashboard']);
        return true;
    }
    else {
        this.router.navigate(['/userDashboard']);
    }
    return false;
  }
}
</code>```

About your second problem, use a login to detect the logged in user and put the logic in a service for login handle and another service to check the user privileges that you have configured on the backend. If your application goes over the internet use https to send secure the user credentials.

Body:
Example: www.example.com/dashboard

I want to detect if user is Customer, it will load CustomerDashboardModule, if user is Staff, it's StaffDashboardModule, if user is Admin, it's AdminDashboardModule but the url is still /dashboard

Example code:

export const routes: Routes = [
{
    path: '',
    component: DashboardComponent,
    children: [
        {
            path: '',
            loadChildren: condition ? 'x' : 'y'
        }
    ]
}];

But it doesn't work.

Second problem is

How to detech User? Call an service of CoreModule. A solution is create a static property Injector in CoreModule and inject Injector in its constructor but I don't know if it's a good practice?

Body:
You can use a Guard that only when you have access to the route, you can navigate to the URL, when not, you can redirect to another URL.

Angular Router goto 'Milestone 5: Route guards'

Example define a guard in router config:

const routes: Routes = [
  {
    path: 'adminDashboard',
    component: AdminComponent,
    canActivate: [AdminAuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: '', component: AdminDashboardComponent }
        ],
      }
    ]
  },
  {
    path: 'userDashboard',
    component: UserComponent,
    canActivate: [UserAuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: '', component: UserDashboardComponent }
        ],
      }
    ]
  },
];

Guard example with redirect:

@Injectable()
export class AdminAuthGuard implements CanActivate {

auth: any = {};

constructor(private authService: AuthService, private router: Router) {}

canActivate() {
    if (/*user has privileges check*/) {
        this.router.navigate(['/adminDashboard']);
        return true;
    }
    else {
        this.router.navigate(['/userDashboard']);
    }
    return false;
  }
}

About your second problem, use a login to detect the logged in user and put the logic in a service for login handle and another service to check the user privileges that you have configured on the backend. If your application goes over the internet use https to send secure the user credentials.


问:
Updating data in UITableView is not smooth
I am using NSFetchedResultsController to display the already saved data in the tableView. At the same time, I am checking for new data by a web service. When I receive data from the network, my database gets updated with the new data. The tableView automatically gets updated.
But the update in tableView is not smooth. Please offer a suitable solution for swift 4.
Please watch this video which I have uploaded for the better explanation.
https://www.youtube.com/watch?v=XhSEykQcP5A&feature=youtu.be

This is my NSFetchedResultsController delegate implementation

```<code>extension CoreDataTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
    let set = IndexSet(integer: sectionIndex)
    switch (type) {
    case .insert:
        tableView.insertSections(set, with: .fade)
    case .delete:
        tableView.deleteSections(set, with: .fade)
    default:
        break
    }
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch(type) {
    case .insert:
        tableView.insertRows(at: [newIndexPath!], with: .fade)
    case .delete:
        tableView.deleteRows(at: [indexPath!], with: .fade)
    case .update:
        tableView.reloadRows(at: [indexPath!], with: .fade)
    case .move:
        tableView.deleteRows(at: [indexPath!], with: .fade)
        tableView.insertRows(at: [newIndexPath!], with: .fade)
    }
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}
</code>```

答:
You can try this:

```<code>   tableView.beginUpdates()
   tableView.endUpdates()
</code>```

Apple says:

Call this method if you want subsequent insertions, deletion, and
  selection operations.

...

You should not call reloadData() within the group; if you call this
  method within the group, you must perform any animations yourself.

Body:
I am using NSFetchedResultsController to display the already saved data in the tableView. At the same time, I am checking for new data by a web service. When I receive data from the network, my database gets updated with the new data. The tableView automatically gets updated.
But the update in tableView is not smooth. Please offer a suitable solution for swift 4.
Please watch this video which I have uploaded for the better explanation.
https://www.youtube.com/watch?v=XhSEykQcP5A&feature=youtu.be

This is my NSFetchedResultsController delegate implementation

extension CoreDataTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
    let set = IndexSet(integer: sectionIndex)
    switch (type) {
    case .insert:
        tableView.insertSections(set, with: .fade)
    case .delete:
        tableView.deleteSections(set, with: .fade)
    default:
        break
    }
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch(type) {
    case .insert:
        tableView.insertRows(at: [newIndexPath!], with: .fade)
    case .delete:
        tableView.deleteRows(at: [indexPath!], with: .fade)
    case .update:
        tableView.reloadRows(at: [indexPath!], with: .fade)
    case .move:
        tableView.deleteRows(at: [indexPath!], with: .fade)
        tableView.insertRows(at: [newIndexPath!], with: .fade)
    }
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}

Body:
You can try this:

   tableView.beginUpdates()
   tableView.endUpdates()

Apple says:

Call this method if you want subsequent insertions, deletion, and
  selection operations.

...

You should not call reloadData() within the group; if you call this
  method within the group, you must perform any animations yourself.