问:
Nancy, module not loaded
I'm fairly new to Nancy. What I'm trying to achieve, is to create a base class NancyBaseModule which inherits from the NancyModule class. This class is supposed to be responsible for "common stuff". I want to do it like this instead of hiding this sort of features in extension methods or static methods.

The problem I'm facing is that, by adding functionality to this base class, for registering a simple GET method, the Func of this registered method will never be called when tried accessed in an web-browser for instance. In fact the constructor of the class is never called, which make me thinking that I need to register at least on HTTP-method in the constructor. As you can see if I add the "dummy" path, it will all work.

This is how my Base class looks like:

```<code>public abstract class NancyBaseModule : NancyModule
{
        public NancyBaseModule(string prefix) : base(prefix)
        {
            //Get("/dummy", p =>
            //{
            //    return "Nothing interesting here, Cowboy.";
            //});

            var configurator = new NancyEndpointConfigurator()
            {
                RegisterWithReturnValue = (path, action) =>
                {
                    Get(path, action);
                }
            };

            RegisterEndpoints(configurator);
        }

        public abstract void RegisterEndpoints(INancyEndpointConfigurator configurator);
    }
</code>```

And my derived class:

```<code>  public class AckService : NancyBaseModule
    {
        public AckService() : base("AckService")
        {
        }

        public override void RegisterEndpoints(INancyEndpointConfigurator configurator)
        {
            configurator.WithReturnValue("/now", p =>
            {
                return $"Greetings. The time is: {DateTime.Now.ToString()}";
            });
        }
    }
</code>```

Due to my lack of knowledge using Nancy, I'm not quite sure if this is the right approach to take in terms of the design thoughts behind the framework. If anyone do understand want I'm trying to achieve, please pint-point me in the right direction.

答: I would stick with the normal registrations Get(path,Func<>) syntax,I cannot any benefit to the complexity of overriding methods.Also I would not register routes in the base class as that can cause route collisions down the road, only common functions should be in your base module.

Title: Nancy, module not loaded

Body:
I'm fairly new to Nancy. What I'm trying to achieve, is to create a base class NancyBaseModule which inherits from the NancyModule class. This class is supposed to be responsible for "common stuff". I want to do it like this instead of hiding this sort of features in extension methods or static methods.

The problem I'm facing is that, by adding functionality to this base class, for registering a simple GET method, the Func of this registered method will never be called when tried accessed in an web-browser for instance. In fact the constructor of the class is never called, which make me thinking that I need to register at least on HTTP-method in the constructor. As you can see if I add the "dummy" path, it will all work.

This is how my Base class looks like:

public abstract class NancyBaseModule : NancyModule
{
        public NancyBaseModule(string prefix) : base(prefix)
        {
            //Get("/dummy", p =>
            //{
            //    return "Nothing interesting here, Cowboy.";
            //});

            var configurator = new NancyEndpointConfigurator()
            {
                RegisterWithReturnValue = (path, action) =>
                {
                    Get(path, action);
                }
            };

            RegisterEndpoints(configurator);
        }

        public abstract void RegisterEndpoints(INancyEndpointConfigurator configurator);
    }

And my derived class:

  public class AckService : NancyBaseModule
    {
        public AckService() : base("AckService")
        {
        }

        public override void RegisterEndpoints(INancyEndpointConfigurator configurator)
        {
            configurator.WithReturnValue("/now", p =>
            {
                return $"Greetings. The time is: {DateTime.Now.ToString()}";
            });
        }
    }

Due to my lack of knowledge using Nancy, I'm not quite sure if this is the right approach to take in terms of the design thoughts behind the framework. If anyone do understand want I'm trying to achieve, please pint-point me in the right direction.


来源: stackexchange

问:
Forkjoin with empty (or not) array of observables
I'm trying to detect when all my observables have completed. I have the following Observables:

let observables:any[] = [];
if(valid){
    observables.push(new Observable((observer:any) => {
        async(()=>{
            observer.next();
            observer.complete();
        })
    }))
}
if(confirmed){
    observables.push(new Observable((observer:any) => {
        async(()=>{
            observer.next();
            observer.complete();
        })
    }))
}

Observable.forkJoin(observables).subscribe(
    data => {
        console.log('all completed');
    },
    error => {
        console.log(error);
    }
);
```

I need to do something whenever all my functions are completed. Forkjoin seems to work when the observables array is not empty. But when the array is empty, it never gets called. How can I solve this?

答:
you are missing the 3rd callback in subscribe. try this:

Rx.Observable.forkJoin([]).subscribe(
    val => {
        console.log('next');
    },
    err => {
        console.log('err');
    },
    () => {
        console.log('complete')
    }
);
```

<p>forkJoin on empty array completes immediately.</p>

<p><strong>Updated for RxJS 6:</strong></p>

```  let rep: Observable<any>[] = [];

  for (let i = 0; i < areas.length; i++) { // undetermined array length
      rep.push(this.httpService.GET('/areas/' + areas[i].name)); // example observable's being pushed to array
  }
  if (rep !== []) {
    forkJoin(rep).subscribe(({
      next: value => {
        console.log(value)
      }
    }));
  }
```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to detect when all my observables have completed. I have the following Observables:

let observables:any[] = [];
if(valid){
    observables.push(new Observable((observer:any) => {
        async(()=>{
            observer.next();
            observer.complete();
        })
    }))
}
if(confirmed){
    observables.push(new Observable((observer:any) => {
        async(()=>{
            observer.next();
            observer.complete();
        })
    }))
}

Observable.forkJoin(observables).subscribe(
    data => {
        console.log('all completed');
    },
    error => {
        console.log(error);
    }
);

I need to do something whenever all my functions are completed. Forkjoin seems to work when the observables array is not empty. But when the array is empty, it never gets called. How can I solve this?

Body:
you are missing the 3rd callback in subscribe. try this:

Rx.Observable.forkJoin([]).subscribe(
    val => {
        console.log('next');
    },
    err => {
        console.log('err');
    },
    () => {
        console.log('complete')
    }
);

forkJoin on empty array completes immediately.

Updated for RxJS 6:

  let rep: Observable<any>[] = [];

  for (let i = 0; i < areas.length; i++) { // undetermined array length
      rep.push(this.httpService.GET('/areas/' + areas[i].name)); // example observable's being pushed to array
  }
  if (rep !== []) {
    forkJoin(rep).subscribe(({
      next: value => {
        console.log(value)
      }
    }));
  }

ContentLicense: CC BY-SA 4.0


问:
Getting all branches from bitbucket
I need to hand off a visual studio project that has multiple branches. Bitbucket is being used as the repo. I am trying to find a way to download the entire repo with every branch. I'm not sure if there is a solution using GIT or some feature in bitbucket that I can't find. When I try to download directly from Bitbucket I only get the master branch</p>

答: Open Team Explorer => Open your repository => Select 'Branches' tab => Right click your repository => click 'Create local branch from' => choose source branch from dropdown with name /origin/branchname</p>

Title: Getting all branches from bitbucket


问:
Does Intel Math Kernel Library (MKL) utilise the integrated GPU in Intel CPUs?
I understand Intel MKL will interrogate the CPU for existence of extended instruction sets such as the various SSE to SSE 4.2, AVX, AVX2, etc. in order to select the best subroutine available for a given CPU.

Now that many of Intel's consumer CPUs contain an integrated GPU I was wondering if the Intel MKL utilises them?

答:
In Intel MKL system requirements page https://software.intel.com/en-us/articles/intel-math-kernel-library-intel-mkl-2017-system-requirements does not include any information about GPUs being supported. There is also no mention about it in the documentation.

The only accelerator they support is Xeon Phi. Therefore, there is no support for GPUs from MKL as of now.


问:
Masstransit. Handler doesn't acknowledge messages
I have publisher:

```<code> static void Main()
    {
        var bus = ServiceBusFactory.New(sbc =>
        {
            sbc.UseRabbitMq(r => r.ConfigureHost(new MessageUrn("rabbitmq://localhost/test123"), c => { }));
            sbc.UseJsonSerializer();
            sbc.EnableMessageTracing();
            sbc.ReceiveFrom(new MessageUrn("rabbitmq://localhost/test345"));
        });

        bus.WriteIntrospectionToConsole();
        Console.WriteLine("bus endpoint {0}", bus.Endpoint.Address);
        while(true)
        {
            Thread.Sleep(1000);
            var msg = new TestMessage {Text = DateTime.Now.ToString()};
            Console.WriteLine("Publishing {0}", msg);
            bus.Publish(msg);
        }
    }
</code>```

Publish queue test123, recieve queue test 345.

When I launch consumer with following code:

```<code> static void Main()
    {
        var bus = ServiceBusFactory.New(sbc =>
        {
            sbc.UseRabbitMq();
            sbc.UseJsonSerializer();
            sbc.EnableMessageTracing();
            sbc.ReceiveFrom("rabbitmq://localhost/test345");
            sbc.Subscribe(subs => { subs.Handler<TestMessage>(msg => { Console.WriteLine(msg.Text); }); });
        });
        bus.WriteIntrospectionToConsole();
        Console.ReadLine();
    }
</code>```

Consumer (subscriber) handles messages and write them on console. Everything is ok on this part. But messages in test123 not acknowledged.They quantity constantly increasing, they are in ready state. They some how are consumed but doesn't go away.

What I'm doing wrong?

Another problem I can't understand is that when I delete all queues, run publisher, it creates only test345 and test345_error queues. No test123 queue. If publisher works for some time, there are few messages in test345_error and no messages in test345. When I launch consumer (see code above) it starts consume messages and it looks like to be ok. Why there is no messages in test345 queue? But somehow they are consumed (handled)?

Masstransit v2.10.0.0, RabbitMQ.Client v3.4.3.0.

Thanks in advance.

答: Ok, seems to be solved by fixing both queues in publisher to be test123. No errors, no skips. </p>

Body:
I have publisher:

 static void Main()
    {
        var bus = ServiceBusFactory.New(sbc =>
        {
            sbc.UseRabbitMq(r => r.ConfigureHost(new MessageUrn("rabbitmq://localhost/test123"), c => { }));
            sbc.UseJsonSerializer();
            sbc.EnableMessageTracing();
            sbc.ReceiveFrom(new MessageUrn("rabbitmq://localhost/test345"));
        });

        bus.WriteIntrospectionToConsole();
        Console.WriteLine("bus endpoint {0}", bus.Endpoint.Address);
        while(true)
        {
            Thread.Sleep(1000);
            var msg = new TestMessage {Text = DateTime.Now.ToString()};
            Console.WriteLine("Publishing {0}", msg);
            bus.Publish(msg);
        }
    }

Publish queue test123, recieve queue test 345.

When I launch consumer with following code:

 static void Main()
    {
        var bus = ServiceBusFactory.New(sbc =>
        {
            sbc.UseRabbitMq();
            sbc.UseJsonSerializer();
            sbc.EnableMessageTracing();
            sbc.ReceiveFrom("rabbitmq://localhost/test345");
            sbc.Subscribe(subs => { subs.Handler<TestMessage>(msg => { Console.WriteLine(msg.Text); }); });
        });
        bus.WriteIntrospectionToConsole();
        Console.ReadLine();
    }

Consumer (subscriber) handles messages and write them on console. Everything is ok on this part. But messages in test123 not acknowledged.They quantity constantly increasing, they are in ready state. They some how are consumed but doesn't go away.

What I'm doing wrong?

Another problem I can't understand is that when I delete all queues, run publisher, it creates only test345 and test345_error queues. No test123 queue. If publisher works for some time, there are few messages in test345_error and no messages in test345. When I launch consumer (see code above) it starts consume messages and it looks like to be ok. Why there is no messages in test345 queue? But somehow they are consumed (handled)?

Masstransit v2.10.0.0, RabbitMQ.Client v3.4.3.0.

Thanks in advance.


问:
Unexpected block condition with Control.Invoke
The following code is a simplified proof of concept.
In a windows forms application there is a FormClosing event handler to perform some cleanup. The application launches some threads which write on the Form using Control.Invoke. I know I could use Control.BeginInvoke but I would like to understand better what happens and find another solution.

```<code>List<Thread> activeThreadlist;
volatile bool goOnPolling = true;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        goOnPolling = false;
        Thread.Sleep(1000);
        foreach (Thread element in activeThreadlist)
            if (element.IsAlive)
                element.Abort();

    }
</code>```

A flag is set to false in order to stop the loop on the threads, they have time to terminate and if one is still alive it is terminated with abort.

Here is the code executed by the other threads:

```<code>while (goOnPolling)
{
    //some long elaboration here
    if (!goOnPolling) continue;
    aControl.Invoke(new Action(() =>
    {
        //display some result about the elaboration
    }));
    if (!goOnPolling) continue;
    //some long elaboration here

}
</code>```

In about 50% of the cases when the form is closed the threads blocks on Control.Invoke so they don't terminate during the sleep time and Abort is called. I thought checking the flag goOnPolling before calling Invoke would have been sufficient in 99.999% of the cases, but I was wrong. As stated in the code the threads do long elaborations (at least 100ms) so I expected goOnPolling was likely to change during them. Why am I wrong ? Is there another easy solution without recurring to BeginInvoke which creates an additional thread ?

Update

After reading the comments I realized the title was wrong. I initially wrote deadlock but it is only an unexpected (for me) block condition. In the beginning I couldn't understand why my threads were still alive after having waited their terminations for 1000ms, so I put an Abort to find out. I completely misunderstood the difference between Invoke and BeginInvoke, thanks for clarifying it.

@Jon B

I agree break is better suited than continue but that code is inside while (goOnPolling) block, so I could save only some cpu cycles, nothing more.

Any idea why so often goOnPolling changes during the early stages of Invoke ? If I perform a long elaboration it should happen there most of the time.

答:
We know that these other threads want to get onto the UI thread through Invoke, and we know that you're tying up the UI thread in a Sleep.

This may be one of the few times where Application.DoEvents is the least-bad option here:

```<code>private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    goOnPolling = false;
    for(int i=0;i<10;i++)
    {
        Application.DoEvents();
        Thread.Sleep(50);
    }
    //foreach (Thread element in activeThreadlist)
    //    if (element.IsAlive)
    //        element.Abort();
}
</code>```

And also change the threads to cope with exceptions being thrown if they try to Invoke after the form has already been closed, rather than nastily trying to tear them down with an Abort.

As for why so many threads are in the state where they're wanting to Invoke, it's unclear from the code posted so far - but bear in mind that Invoke is serializing access to the UI thread. It's possible that all of the threads asked to Invoke well before the UI thread got to processing the windows message that translates to the "form closing" event, if access to the thread is heavily congested.

Body:
The following code is a simplified proof of concept.
In a windows forms application there is a FormClosing event handler to perform some cleanup. The application launches some threads which write on the Form using Control.Invoke. I know I could use Control.BeginInvoke but I would like to understand better what happens and find another solution.

List<Thread> activeThreadlist;
volatile bool goOnPolling = true;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        goOnPolling = false;
        Thread.Sleep(1000);
        foreach (Thread element in activeThreadlist)
            if (element.IsAlive)
                element.Abort();

    }

A flag is set to false in order to stop the loop on the threads, they have time to terminate and if one is still alive it is terminated with abort.

Here is the code executed by the other threads:

while (goOnPolling)
{
    //some long elaboration here
    if (!goOnPolling) continue;
    aControl.Invoke(new Action(() =>
    {
        //display some result about the elaboration
    }));
    if (!goOnPolling) continue;
    //some long elaboration here

}

In about 50% of the cases when the form is closed the threads blocks on Control.Invoke so they don't terminate during the sleep time and Abort is called. I thought checking the flag goOnPolling before calling Invoke would have been sufficient in 99.999% of the cases, but I was wrong. As stated in the code the threads do long elaborations (at least 100ms) so I expected goOnPolling was likely to change during them. Why am I wrong ? Is there another easy solution without recurring to BeginInvoke which creates an additional thread ?

Update

After reading the comments I realized the title was wrong. I initially wrote deadlock but it is only an unexpected (for me) block condition. In the beginning I couldn't understand why my threads were still alive after having waited their terminations for 1000ms, so I put an Abort to find out. I completely misunderstood the difference between Invoke and BeginInvoke, thanks for clarifying it.

@Jon B

I agree break is better suited than continue but that code is inside while (goOnPolling) block, so I could save only some cpu cycles, nothing more.

Any idea why so often goOnPolling changes during the early stages of Invoke ? If I perform a long elaboration it should happen there most of the time.

Body:
We know that these other threads want to get onto the UI thread through Invoke, and we know that you're tying up the UI thread in a Sleep.

This may be one of the few times where Application.DoEvents is the least-bad option here:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    goOnPolling = false;
    for(int i=0;i<10;i++)
    {
        Application.DoEvents();
        Thread.Sleep(50);
    }
    //foreach (Thread element in activeThreadlist)
    //    if (element.IsAlive)
    //        element.Abort();
}

And also change the threads to cope with exceptions being thrown if they try to Invoke after the form has already been closed, rather than nastily trying to tear them down with an Abort.

As for why so many threads are in the state where they're wanting to Invoke, it's unclear from the code posted so far - but bear in mind that Invoke is serializing access to the UI thread. It's possible that all of the threads asked to Invoke well before the UI thread got to processing the windows message that translates to the "form closing" event, if access to the thread is heavily congested.


问:
PHP MySQLi Pagination LIMIT, WHERE and ORDER BY `date` DESC problems
I am creating project not for profit and have problems with pagination. First idea was "Load more" <- but it's in dreams only. Maybe MySQL syntax is wrong. How to fix this code? Maybe there's a better solution? I tried all combinations "..",'..', ``. This can also be exploited by using SQL injections?</p>

```<code>  MySQLi connection:

$mysqli = new mysqli('localhost','root','','tablename');
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
/* Change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
}

  Paggination:

  $items_per_page = 5;
  $login = $_SESSION['login'];
  $per_page = $items_per_page;
  if (isset($_GET['page'])) {
  $page = $_GET['page'];
  }else {
  $page = 1;
  }
  $start_from = ($page-1) * $per_page;
  //Selecting the data from db
  $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page");
  while($row = $date->fetch_array()){
  echo $row["post_id"];
  }
  //

  //Select all from DB
  $query = $mysqli->query("SELECT post_id FROM posts WHERE posts_author='$login' ORDER BY date DESC");
  $result = mysqli_query($mysqli, $query);
  $total_records = mysqli_num_rows($result);
  $total_pages = ceil($total_records / $per_page);
  //Going to first page
  echo '<a href="' .ABSOLUTE_URL. '/post/1">first page</a> ';
  for ($i=1; $i<=$total_pages; $i++){
  echo '<a href="' .ABSOLUTE_URL. '/post/'.$i.'">'.$i.'</a> ';
  };
  // Going to last page
  echo '<a href="' .ABSOLUTE_URL. '/post/'.$total_pages.'">last page</a> ';
</code>```

答:
Your code can be exploited,
you should consider of using mysqli_real_escape_string: http://php.net/manual/en/mysqli.real-escape-string.php

For bugs, i see it here:

```<code>//Selecting the data from db
  $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page");
  while($row = $date->fetch_array()){
  echo $row["post_id"];
  }
</code>```

You were used single quotes with dots for '.$login.' instead of using double quotes and your query should execute fine.

If you got some other problems, update answer where did you stuck, what's not working and what have you tried.

Body:
I am creating project not for profit and have problems with pagination. First idea was "Load more" <- but it's in dreams only. Maybe MySQL syntax is wrong. How to fix this code? Maybe there's a better solution? I tried all combinations "..",'..', ``. This can also be exploited by using SQL injections?

  MySQLi connection:

$mysqli = new mysqli('localhost','root','','tablename');
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
/* Change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
}

  Paggination:

  $items_per_page = 5;
  $login = $_SESSION['login'];
  $per_page = $items_per_page;
  if (isset($_GET['page'])) {
  $page = $_GET['page'];
  }else {
  $page = 1;
  }
  $start_from = ($page-1) * $per_page;
  //Selecting the data from db
  $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page");
  while($row = $date->fetch_array()){
  echo $row["post_id"];
  }
  //

  //Select all from DB
  $query = $mysqli->query("SELECT post_id FROM posts WHERE posts_author='$login' ORDER BY date DESC");
  $result = mysqli_query($mysqli, $query);
  $total_records = mysqli_num_rows($result);
  $total_pages = ceil($total_records / $per_page);
  //Going to first page
  echo 'first page ';
  for ($i=1; $i<=$total_pages; $i++){
  echo ''.$i.' ';
  };
  // Going to last page
  echo 'last page ';

Body:
Your code can be exploited,
you should consider of using mysqli_real_escape_string: http://php.net/manual/en/mysqli.real-escape-string.php

For bugs, i see it here:

//Selecting the data from db
  $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page");
  while($row = $date->fetch_array()){
  echo $row["post_id"];
  }

You were used single quotes with dots for '.$login.' instead of using double quotes and your query should execute fine.

If you got some other problems, update answer where did you stuck, what's not working and what have you tried.


问:
Call function for each route in $routeProvider
I have got a little challenge and didn't find the solution yet. As I tried serveral things I'm asking your help so probably someone can lead me to the right direction.

I've got a routes.js in AngularJS. There am I using a $routeProvider. In each .when() I need to call a function (as I need to do something with the name).

```<code>$routeProvider
.when('/url', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url1', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url2', { templateUrl: '', /* callMyFunction('/url'); */ }) ....
</code>```

This is just an example, I know this won't work. But to give you an idea what I'm trying to do. As you can see this will mess up my code (you need much more to get this working, so you'll get a lot of extra code for each .when() and this code is in every statement exactly the same (except for the argument).

So I'm looking for some function that can be called before or after (doesn't make sense as long as it's getting called) .when().

I've read plenty of questions here on Stack Overflow but didn't find the right answer. Most questions answered to put this in the controller. How ever, this function I've to call is for each route exactly the same. Because of this I don't want to put it in all my controllers but just in the routes.js and called for/after every when().

答:
If you're willing to change to ui-router this all becomes much easier. ui-router is far superior to the built-in routing supplied with base Angular. Here is a simple example of how to execute a function with ui-router. In this example I set the value of a variable which is then injected in the controller as well as just call a simple function.

angular.module('app', ['ui.router'])
  .config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider.state('main', {
      url: '/',
      template: '
This is the main state - mainValue: {{vm.mainValue}}
',
      controller: 'MainController',
      controllerAs: 'vm',
      resolve: {
        mainValue: function() {
          return 2 + 2;
        },
        function() {
          console.log('this is just calling a function with no return');
        }
      }
    });
  })
  .controller('MainController', function(mainValue) {
    this.mainValue = mainValue;
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<div ng-app="app">
  <div ui-view></div>
</div></code>```

Body:
I have got a little challenge and didn't find the solution yet. As I tried serveral things I'm asking your help so probably someone can lead me to the right direction.

I've got a routes.js in AngularJS. There am I using a $routeProvider. In each .when() I need to call a function (as I need to do something with the name).

$routeProvider
.when('/url', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url1', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url2', { templateUrl: '', /* callMyFunction('/url'); */ }) ....

This is just an example, I know this won't work. But to give you an idea what I'm trying to do. As you can see this will mess up my code (you need much more to get this working, so you'll get a lot of extra code for each .when() and this code is in every statement exactly the same (except for the argument).

So I'm looking for some function that can be called before or after (doesn't make sense as long as it's getting called) .when().

I've read plenty of questions here on Stack Overflow but didn't find the right answer. Most questions answered to put this in the controller. How ever, this function I've to call is for each route exactly the same. Because of this I don't want to put it in all my controllers but just in the routes.js and called for/after every when().

Body:
If you're willing to change to ui-router this all becomes much easier. ui-router is far superior to the built-in routing supplied with base Angular. Here is a simple example of how to execute a function with ui-router. In this example I set the value of a variable which is then injected in the controller as well as just call a simple function.

angular.module('app', ['ui.router'])
  .config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider.state('main', {
      url: '/',
      template: '<div>This is the main state - mainValue: {{vm.mainValue}}</div>',
      controller: 'MainController',
      controllerAs: 'vm',
      resolve: {
        mainValue: function() {
          return 2 + 2;
        },
        function() {
          console.log('this is just calling a function with no return');
        }
      }
    });
  })
  .controller('MainController', function(mainValue) {
    this.mainValue = mainValue;
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<div ng-app="app">
  <div ui-view></div>
</div>


问:
How to bind a click event to the document so that it fires only when no object is clicked
I would like an event to fire whenever something other than a DOM element is clicked, and a separate event when an image is clicked.

Right now I have:

```<code>$( document ).click( function() { /*do whatev*/ } );
</code>```

and in another place:

```<code>$( "img" ).click( function( e ) {
  e.stopPropagation();
  /*do whatev*/
} );
</code>```

it does not work. both events are fired. any other ideas?

答:
something like this:

```<code>$('*').click(function(ev) {
    ev.stopPropagation();
    if ($(this).is('img')) alert('img');
    else if($(this).is('div')) alert('div');
    else alert('something else');
});
</code>```

http://www.jsfiddle.net/U2Szn/ ?

ContentLicense: CC BY-SA 2.5

Body:
I would like an event to fire whenever something other than a DOM element is clicked, and a separate event when an image is clicked.

Right now I have:

$( document ).click( function() { /*do whatev*/ } );

and in another place:

$( "img" ).click( function( e ) {
  e.stopPropagation();
  /*do whatev*/
} );

it does not work. both events are fired. any other ideas?

Body:
something like this:

$('*').click(function(ev) {
    ev.stopPropagation();
    if ($(this).is('img')) alert('img');
    else if($(this).is('div')) alert('div');
    else alert('something else');
});

http://www.jsfiddle.net/U2Szn/ ?


问:
predicate with Prolog
I have to write a program which has a predicate p(A,B,C,D,E,F). A,B,C,D,E,F are lists.

A contains D, E and F. (Something like A and B is D, A and C is E) F contains A without D and E.

And also elements in list F are in pairs (example if A contains [a,b,c] then F would contain [a,a,b,b,c,c].)

So.. I can't get where to start. I have read tutorial and still.. I don't quite get it.

example:

```<code>A is [a,b,c,d,e,f,g]
B is [a,c,d,q,w]
C is [e,d,g,m,n]
D is [a,c,d]
E is [e,d,g]
F is [b,b,f,f]
</code>```

答:
In addition to aioobe's answer :

Something like A and B is D, A and C is E

```<code>p(A,B,C,D,E,_F):-
    intersection(A,B,D),
    intersection(A,C,E).
</code>```

You would eventually need to order the lists but intersection/3 seems more accurate.

Title: predicate with Prolog

Body:
I have to write a program which has a predicate p(A,B,C,D,E,F). A,B,C,D,E,F are lists.

A contains D, E and F. (Something like A and B is D, A and C is E) F contains A without D and E.

And also elements in list F are in pairs (example if A contains [a,b,c] then F would contain [a,a,b,b,c,c].)

So.. I can't get where to start. I have read tutorial and still.. I don't quite get it.

example:

A is [a,b,c,d,e,f,g]
B is [a,c,d,q,w]
C is [e,d,g,m,n]
D is [a,c,d]
E is [e,d,g]
F is [b,b,f,f]

Body:
In addition to aioobe's answer :

Something like A and B is D, A and C is E

p(A,B,C,D,E,_F):-
    intersection(A,B,D),
    intersection(A,C,E).

You would eventually need to order the lists but intersection/3 seems more accurate.


问:
flask production and development mode
I have developed an application with flask, and I want to publish it for production, but I do not know how to make a separation between the production and development environment (database and code), have you documents to help me or  code.
I specify in the config.py file the two environment but I do not know how to do with.</p>

```<code>class DevelopmentConfig(Config):
    """
    Development configurations
    """
    DEBUG = True
    SQLALCHEMY_ECHO = True
    ASSETS_DEBUG = True
    DATABASE = 'teamprojet_db'
    print('THIS APP IS IN DEBUG MODE. YOU SHOULD NOT SEE THIS IN PRODUCTION.')

class ProductionConfig(Config):
    """
    Production configurations
    """
    DEBUG = False
    DATABASE = 'teamprojet_prod_db'
</code>```

答:
To add onto Daniel's answer:

Flask has a page in its documentation that discusses this very issue.

Since you've specified your configuration in classes, you would load your configuration with app.config.from_object('configmodule.ProductionConfig')

Title: flask production and development mode

Body:
I have developed an application with flask, and I want to publish it for production, but I do not know how to make a separation between the production and development environment (database and code), have you documents to help me or  code.
I specify in the config.py file the two environment but I do not know how to do with.

class DevelopmentConfig(Config):
    """
    Development configurations
    """
    DEBUG = True
    SQLALCHEMY_ECHO = True
    ASSETS_DEBUG = True
    DATABASE = 'teamprojet_db'
    print('THIS APP IS IN DEBUG MODE. YOU SHOULD NOT SEE THIS IN PRODUCTION.')

class ProductionConfig(Config):
    """
    Production configurations
    """
    DEBUG = False
    DATABASE = 'teamprojet_prod_db'


问:
How to sum and count in attendance using pivot in SQL Server
I have a table Mark_Attendance and it contains:

```<code>Class | [Status] | [DateTime]  | S_Adm_No  | Gender
------+----------+-------------+-----------+--------
NUR   | P        | 2017-04-19  | 1101      | Male
NUR   | A        | 2017-04-19  | 1102      | Male
NUR   | P        | 2017-04-19  | 1103      | Female
NUR   | A        | 2017-04-19  | 1104      | Female
KG    | P        | 2017-04-19  | 1105      | Male
KG    | A        | 2017-04-19  | 1106      | Male
KG    | P        | 2017-04-19  | 1107      | Female
KG    | A        | 2017-04-19  | 1108      | Female
</code>```

Now I want to show my result like

```<code>Class|ttl|total_male|ttl_FeMale|Ttl_Pr|Pr_Male|Pr_Female|Ttl_Ab|Ab_Female|Ab_Mal2
NUR  |4  |  2       |   2      | 2    |2      | 2       |2     |2        |2
KG   |4  |  2       |   2      | 2    |2      | 2       |2     |2        |2
</code>```

For getting this result what query should I use in SQL Server.

答:
Certainly your output is wrong

Proper query and output should be :

```<code>select Class, Count(Class) as ttl,
Sum(Case when Gender = 'Male' Then 1 Else 0 End) as Total_Male,
Sum(Case when Gender = 'Female' Then 1 Else 0 End) as Total_Female,
Sum(Case when Status = 'P' Then 1 Else 0 End) as Total_Present,
Sum(Case when Status = 'P' and Gender = 'Male' Then 1 Else 0 End) as Total_Male_Present,
Sum(Case when Status = 'P' and Gender = 'Female' Then 1 Else 0 End) as Total_Female_Present,
Sum(Case when Status = 'A' Then 1 Else 0 End) as Total_Absent,
Sum(Case when Status = 'A' and Gender = 'Male' Then 1 Else 0 End) as Total_Male_Absent,
Sum(Case when Status = 'A' and Gender = 'Female' Then 1 Else 0 End) as Total_Female_Absent
from  Mark_Attendance
group by Class;
</code>```

and output should be :

```<code>Class  ttl         Total_Male  Total_Female Total_Present Total_Male_Present Total_Female_Present Total_Absent Total_Male_Absent Total_Female_Absent
------ ----------- ----------- ------------ ------------- ------------------ -------------------- ------------ ----------------- -------------------
KG     4           2           2            2             1                  1                    2            1                 1
NUR    4           2           2            2             1                  1                    2            1                 1
</code>```

If you want to understand how did I achieve this result read about

Group by clause

Sum over case statement

I strongly discourage people who post questions without showing their efforts.

Body:
I have a table Mark_Attendance and it contains:

Class | [Status] | [DateTime]  | S_Adm_No  | Gender
------+----------+-------------+-----------+--------
NUR   | P        | 2017-04-19  | 1101      | Male
NUR   | A        | 2017-04-19  | 1102      | Male
NUR   | P        | 2017-04-19  | 1103      | Female
NUR   | A        | 2017-04-19  | 1104      | Female
KG    | P        | 2017-04-19  | 1105      | Male
KG    | A        | 2017-04-19  | 1106      | Male
KG    | P        | 2017-04-19  | 1107      | Female
KG    | A        | 2017-04-19  | 1108      | Female

Now I want to show my result like

Class|ttl|total_male|ttl_FeMale|Ttl_Pr|Pr_Male|Pr_Female|Ttl_Ab|Ab_Female|Ab_Mal2
NUR  |4  |  2       |   2      | 2    |2      | 2       |2     |2        |2
KG   |4  |  2       |   2      | 2    |2      | 2       |2     |2        |2

For getting this result what query should I use in SQL Server.

Body:
Certainly your output is wrong

Proper query and output should be :

select Class, Count(Class) as ttl,
Sum(Case when Gender = 'Male' Then 1 Else 0 End) as Total_Male,
Sum(Case when Gender = 'Female' Then 1 Else 0 End) as Total_Female,
Sum(Case when Status = 'P' Then 1 Else 0 End) as Total_Present,
Sum(Case when Status = 'P' and Gender = 'Male' Then 1 Else 0 End) as Total_Male_Present,
Sum(Case when Status = 'P' and Gender = 'Female' Then 1 Else 0 End) as Total_Female_Present,
Sum(Case when Status = 'A' Then 1 Else 0 End) as Total_Absent,
Sum(Case when Status = 'A' and Gender = 'Male' Then 1 Else 0 End) as Total_Male_Absent,
Sum(Case when Status = 'A' and Gender = 'Female' Then 1 Else 0 End) as Total_Female_Absent
from  Mark_Attendance
group by Class;

and output should be :

Class  ttl         Total_Male  Total_Female Total_Present Total_Male_Present Total_Female_Present Total_Absent Total_Male_Absent Total_Female_Absent
------ ----------- ----------- ------------ ------------- ------------------ -------------------- ------------ ----------------- -------------------
KG     4           2           2            2             1                  1                    2            1                 1
NUR    4           2           2            2             1                  1                    2            1                 1

If you want to understand how did I achieve this result read about

Group by clause

Sum over case statement

I strongly discourage people who post questions without showing their efforts.


问:
How to manually set p and q in tbats() in r?
I am using the tbats() function in r to create a forecasting model.

I was wondering if anyone knew how to manually pass the ARMA(p,q) directly into the tbats() function?

edit: I apologize if the question was vague. In the docs for the package, the following argument explanation is printed:

"Additional arguments to be passed to auto.arima when choose an ARMA(p, q) model for the errors. (Note that xreg will be ignored, as will any arguments concerning seasonality and differencing, but arguments controlling the values of p and q will be used.)"

It clearly states that manually controlling the ARMA(p,q) can be done with an argument passed directly into the tbats() function. Does anyone know how to do this?

https://www.rdocumentation.org/packages/forecast/versions/7.3/topics/tbats

答:
The ... argument of tbats will be passed to auto.arima, from the documentation (?tbats)

```<code>...: Additional arguments to be passed to ‘auto.arima’ when
      choose an ARMA(p, q) model for the errors. (Note that
      xreg will be ignored, as will any arguments concerning
      seasonality and differencing, but arguments controlling
      the values of p and q will be used.)
</code>```

Looking at the documentation for auto.arima we see that there are arguments for setting values for p and q.

```<code> auto.arima(y, d = NA, D = NA, max.p = 5, max.q = 5, max.P = 2,
   max.Q = 2, max.order = 5, max.d = 2, max.D = 1, start.p = 2,
   start.q = 2, start.P = 1, start.Q = 1, stationary = FALSE,
   seasonal = TRUE, ic = c("aicc", "aic", "bic"), stepwise = TRUE,
   trace = FALSE, approximation = (length(x) > 150 | frequency(x) > 12),
   truncate = NULL, xreg = NULL, test = c("kpss", "adf", "pp"),
   seasonal.test = c("ocsb", "ch"), allowdrift = TRUE, allowmean = TRUE,
   lambda = NULL, biasadj = FALSE, parallel = FALSE, num.cores = 2,
   x = y, ...)
</code>```

So, for the work you're doing, added the arguments start.p, start.q, and trace to the tbats call to control the starting values and see the search.

The best model, in this example, is ARIMA(0, 0, 0) with zero mean.  The BATS(0, {0,0}, 0.979, -) tells us the values of {p, q} = {0, 0} were selected.

```<code>library(forecast)

omega <- USJudgeRatings[,1]

tbats(y                = omega,
      use.box.cox      = TRUE,
      use.trend        = TRUE,
      use.damped.trend = TRUE,
      use.arma.errors  = TRUE,
      start.p = 3,
      start.q = 2,
      trace = TRUE)
#
#  ARIMA(3,0,2) with non-zero mean : Inf
#  ARIMA(0,0,0) with non-zero mean : -55.63664
#  ARIMA(1,0,0) with non-zero mean : -53.50348
#  ARIMA(0,0,1) with non-zero mean : -53.47905
#  ARIMA(0,0,0) with zero mean     : -57.75828
#  ARIMA(1,0,1) with non-zero mean : -51.19495
#
#  Best model: ARIMA(0,0,0) with zero mean
#
# BATS(0, {0,0}, 0.979, -)
#
# Call: tbats(y = omega, use.box.cox = TRUE, use.trend = TRUE, use.damped.trend = TRUE,
#     use.arma.errors = TRUE, start.p = 3, start.q = 2, trace = TRUE)
#
# Parameters
#   Lambda: 0
#   Alpha: -0.04239053
#   Beta: 0.04362955
#   Damping Parameter: 0.978616
#
# Seed States:
#          [,1]
# [1,] 1.917976
# [2,] 0.017468
#
# Sigma: 0.1206409
# AIC: 163.774
</code>```

Body:
The ... argument of tbats will be passed to auto.arima, from the documentation (?tbats)

...: Additional arguments to be passed to ‘auto.arima’ when
      choose an ARMA(p, q) model for the errors. (Note that
      xreg will be ignored, as will any arguments concerning
      seasonality and differencing, but arguments controlling
      the values of p and q will be used.)

Looking at the documentation for auto.arima we see that there are arguments for setting values for p and q.

 auto.arima(y, d = NA, D = NA, max.p = 5, max.q = 5, max.P = 2,
   max.Q = 2, max.order = 5, max.d = 2, max.D = 1, start.p = 2,
   start.q = 2, start.P = 1, start.Q = 1, stationary = FALSE,
   seasonal = TRUE, ic = c("aicc", "aic", "bic"), stepwise = TRUE,
   trace = FALSE, approximation = (length(x) > 150 | frequency(x) > 12),
   truncate = NULL, xreg = NULL, test = c("kpss", "adf", "pp"),
   seasonal.test = c("ocsb", "ch"), allowdrift = TRUE, allowmean = TRUE,
   lambda = NULL, biasadj = FALSE, parallel = FALSE, num.cores = 2,
   x = y, ...)

So, for the work you're doing, added the arguments start.p, start.q, and trace to the tbats call to control the starting values and see the search.

The best model, in this example, is ARIMA(0, 0, 0) with zero mean.  The BATS(0, {0,0}, 0.979, -) tells us the values of {p, q} = {0, 0} were selected.

library(forecast)

omega <- USJudgeRatings[,1]

tbats(y                = omega,
      use.box.cox      = TRUE,
      use.trend        = TRUE,
      use.damped.trend = TRUE,
      use.arma.errors  = TRUE,
      start.p = 3,
      start.q = 2,
      trace = TRUE)
#
#  ARIMA(3,0,2) with non-zero mean : Inf
#  ARIMA(0,0,0) with non-zero mean : -55.63664
#  ARIMA(1,0,0) with non-zero mean : -53.50348
#  ARIMA(0,0,1) with non-zero mean : -53.47905
#  ARIMA(0,0,0) with zero mean     : -57.75828
#  ARIMA(1,0,1) with non-zero mean : -51.19495
#
#  Best model: ARIMA(0,0,0) with zero mean
#
# BATS(0, {0,0}, 0.979, -)
#
# Call: tbats(y = omega, use.box.cox = TRUE, use.trend = TRUE, use.damped.trend = TRUE,
#     use.arma.errors = TRUE, start.p = 3, start.q = 2, trace = TRUE)
#
# Parameters
#   Lambda: 0
#   Alpha: -0.04239053
#   Beta: 0.04362955
#   Damping Parameter: 0.978616
#
# Seed States:
#          [,1]
# [1,] 1.917976
# [2,] 0.017468
#
# Sigma: 0.1206409
# AIC: 163.774


问:
How to display 4 HTML elements on 2 lines (two elements each)?
I want to figure out how to have a phone icon and a phone number in one line. The same goes for an email icon and an email address. I want to have two lines.

body {
  font-family: 'Open Sans', sans-serif;
  background: #20b2aa;
}

h1 {
  font-size: 40px;
  color: white;
  background: black;
  width: 600px;
  margin: auto;
}

.info {
  background: white;
  width: 600px;
  height: 150px;
  margin: auto;
}

#phoneNumber, #emailAddress {
  padding-top: 5px;
  padding-bottom: 5px;
}

img {
  background: red;
}

p {
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Contact Me</h1>
<div class="info">
  <h3>Eugene</h3>
  <img id="phoneImage" src="img/phone.png">
  <p id="phoneNumber">(800) 123-4000</p>
  <img id="envelopeImage" src="img/envelope.png" alt="">
  <p id="emailAddress">someaddress@gmail.com</p>
</div></code>```

Here's the screenshot of what I have so far:

答:
You could use an un-ordered list and add the icon and text to the list item in some way. That could be a img inside the li with text next to it or you could go a more CSS route with the icons as pseudo elements. This way, if you need to re-use the icons/contact format elsewhere you only need to add a class to the li.

.contact-info {
  margin: 0;
  padding: 0;
  list-style: none;
}

.contact-info .phone::before,
.contact-info .email::before {
  content: '';
  display: inline-block;
  width: 15px;
  height: 15px;
  margin-right: 0.25rem;
  vertical-align: middle;
}

.contact-info .phone::before {
  background-image: url( 'http://placehold.it/10x10/fc0' );
}

.contact-info .email::before {
  background-image: url( 'http://placehold.it/10x10/' );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Contact Me</h1>

<h3>Eugene</h3>
<ul class="contact-info">
  <li class="phone">(800) 123-4000</li>
  <li class="email">someaddress@gmail.com</li>
</ul></code>```

Body:
I want to figure out how to have a phone icon and a phone number in one line. The same goes for an email icon and an email address. I want to have two lines.

body {
  font-family: 'Open Sans', sans-serif;
  background: #20b2aa;
}

h1 {
  font-size: 40px;
  color: white;
  background: black;
  width: 600px;
  margin: auto;
}

.info {
  background: white;
  width: 600px;
  height: 150px;
  margin: auto;
}

#phoneNumber, #emailAddress {
  padding-top: 5px;
  padding-bottom: 5px;
}

img {
  background: red;
}

p {
  background: green;
}

Contact Me

Eugene

(800) 123-4000

someaddress@gmail.com

Here's the screenshot of what I have so far:

Body:
You could use an un-ordered list and add the icon and text to the list item in some way. That could be a img inside the li with text next to it or you could go a more CSS route with the icons as pseudo elements. This way, if you need to re-use the icons/contact format elsewhere you only need to add a class to the li.

.contact-info {
  margin: 0;
  padding: 0;
  list-style: none;
}

.contact-info .phone::before,
.contact-info .email::before {
  content: '';
  display: inline-block;
  width: 15px;
  height: 15px;
  margin-right: 0.25rem;
  vertical-align: middle;
}

.contact-info .phone::before {
  background-image: url( 'http://placehold.it/10x10/fc0' );
}

.contact-info .email::before {
  background-image: url( 'http://placehold.it/10x10/' );
}

<h1>Contact Me</h1>

<h3>Eugene</h3>
<ul class="contact-info">
  <li class="phone">(800) 123-4000</li>
  <li class="email">someaddress@gmail.com</li>
</ul>


问:
EOleException with message 'Syntax error in FROM clause' delphi
Hi I'm trying to get SQL to select from a table which the user has chosen from a list box

Heres my code

```<code>activity := cmbActivity.Text; //this is where the user selects a table to choose from
qryStudents.SQL.Text := 'SELECT * FROM :activity WHERE CompNo = :iCompNo'; //error here
qryStudents.Parameters.ParamByName('activity').Value:= activity;
qryStudents.Parameters.ParamByName('iCompNo').Value := iCompNo;
qryStudents.Open;
</code>```

I keep getting a syntax error after FROM in the SQL code (:activity)
Any help will be appreciated

答:
You can't define the table part of your select as a parameter, you'll need to dynamically build that part of the select statement.

```<code>activity := cmbActivity.Text;
qryStudents.Close;
qryStudents.SQL.Text := 'SELECT * FROM '  + activity + ' WHERE CompNo = :iCompNo';
qryStudents.Parameters.ParamByName('iCompNo').Value := iCompNo;
qryStudents.Open;
</code>```

:iCompNo OTOH is fine to be defined as a parameter, in order to prevent SQL injection.

Body:
Hi I'm trying to get SQL to select from a table which the user has chosen from a list box

Heres my code

activity := cmbActivity.Text; //this is where the user selects a table to choose from
qryStudents.SQL.Text := 'SELECT * FROM :activity WHERE CompNo = :iCompNo'; //error here
qryStudents.Parameters.ParamByName('activity').Value:= activity;
qryStudents.Parameters.ParamByName('iCompNo').Value := iCompNo;
qryStudents.Open;

I keep getting a syntax error after FROM in the SQL code (:activity)
Any help will be appreciated

Body:
You can't define the table part of your select as a parameter, you'll need to dynamically build that part of the select statement.

activity := cmbActivity.Text;
qryStudents.Close;
qryStudents.SQL.Text := 'SELECT * FROM '  + activity + ' WHERE CompNo = :iCompNo';
qryStudents.Parameters.ParamByName('iCompNo').Value := iCompNo;
qryStudents.Open;

:iCompNo OTOH is fine to be defined as a parameter, in order to prevent SQL injection.


问:
Angular2 Hot to get all parameters from url?
I currently try to get nice routes in my application but in my current implementation I have to get and check all parameters in my route subscription. Is there any way I can get a 'static' parameter as employees or departments from the route that I can make a difference earlier instead of checking all parameter values for every possibility?

I am also open for improvements if any of my routes is unlogical or just wrong.

```<code>export const EmployeeManagementRoutes: RouterConfig = [
{
path: 'employee-management',
component: EmployeeManagementComponent,
children: [
  //display all employees
  {
    path: '',
    //is there any way to make this redirict relative to the component the router is for?
    redirectTo: '/employee-management/employees/department/all',
    pathMatch: 'full'
  },
  //display all employees from a specific department
  {
    path: 'employees//department/:department',
    component: EmployeeManagementTableComponent
  },
  //open dialog for deleting or creating a new employee or
  if option is 'show' and id is not undefined show a specific employee
  {
    path: 'employees/action/:option/:id',
    component: EmployeeManagementTableComponent
  },
  //display all departments
  {
    path: 'departments',
    component: EmployeeManagementTableComponent
  },
  //open dialog for deleting or creating a new department
  {
    path: 'departments/action/:option',
    component: EmployeeManagementTableComponent
  },

]
}
];
</code>```

答:
Parse your url like this:

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";

export class TopNavigationComponent implements OnInit {
  constructor(
    private router: Router
  ) {}
  ngOnInit() {
    let parsedUrl = this.router.parseUrl(this.router.url);
    console.log(parsedUrl);
  }
}
</code>```

In the received object the parsed url is located under:
root->children->primary->segments

You can read more right here

Body:
I currently try to get nice routes in my application but in my current implementation I have to get and check all parameters in my route subscription. Is there any way I can get a 'static' parameter as employees or departments from the route that I can make a difference earlier instead of checking all parameter values for every possibility?

I am also open for improvements if any of my routes is unlogical or just wrong.

export const EmployeeManagementRoutes: RouterConfig = [
{
path: 'employee-management',
component: EmployeeManagementComponent,
children: [
  //display all employees
  {
    path: '',
    //is there any way to make this redirict relative to the component the router is for?
    redirectTo: '/employee-management/employees/department/all',
    pathMatch: 'full'
  },
  //display all employees from a specific department
  {
    path: 'employees//department/:department',
    component: EmployeeManagementTableComponent
  },
  //open dialog for deleting or creating a new employee or
  if option is 'show' and id is not undefined show a specific employee
  {
    path: 'employees/action/:option/:id',
    component: EmployeeManagementTableComponent
  },
  //display all departments
  {
    path: 'departments',
    component: EmployeeManagementTableComponent
  },
  //open dialog for deleting or creating a new department
  {
    path: 'departments/action/:option',
    component: EmployeeManagementTableComponent
  },

]
}
];

Body:
Parse your url like this:

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";

export class TopNavigationComponent implements OnInit {
  constructor(
    private router: Router
  ) {}
  ngOnInit() {
    let parsedUrl = this.router.parseUrl(this.router.url);
    console.log(parsedUrl);
  }
}

In the received object the parsed url is located under:
root->children->primary->segments

You can read more right here


问:
Conversion failed when converting the varchar value '0%' to data type int
I'm facing a problem with SQL Server.

I've created a table like this:

```<code>create table Components
(
    pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
    id VARCHAR(50),
    descr VARCHAR(50),
    in_m INT,
    in_iy INT,
    p_fw VARCHAR(5000)
);
</code>```

and I'm trying to insert a couple of values:

```<code>insert into Components (id, descr, in_m, in_iy, p_fw)
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
       ('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');
</code>```

I get the following error:

Msg 245, Level 16, State 1, Line 111

  Conversion failed when converting the varchar value '0%' to data type int.

even though the column descr is correctly defined as varchar(50).

Can anybody help me please? Why is SQL Server trying to convert my strings to int values?

答:
run this and verify the data types;

```<code>  sp_columns Components
</code>```

Looks like 'descr' is really an integer

Body:
I'm facing a problem with SQL Server.

I've created a table like this:

create table Components
(
    pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
    id VARCHAR(50),
    descr VARCHAR(50),
    in_m INT,
    in_iy INT,
    p_fw VARCHAR(5000)
);

and I'm trying to insert a couple of values:

insert into Components (id, descr, in_m, in_iy, p_fw)
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
       ('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');

I get the following error:

Msg 245, Level 16, State 1, Line 111

  Conversion failed when converting the varchar value '0%' to data type int.

even though the column descr is correctly defined as varchar(50).

Can anybody help me please? Why is SQL Server trying to convert my strings to int values?

Body:
run this and verify the data types;

  sp_columns Components

Looks like 'descr' is really an integer


问:
Can an Azure NIC be pointed to records one created in an Azure DNS zone?
Is there a way to point an Azure NIC to the records one created in an Azure DNS zone?

答: At present Azure DNS doesn't support private DNS zones, i.e. those only available to your vnet.  Also, the DNS servers specified in the "Add DNS server" box needs to be a recursive resolver, Azure DNS is an Authoritative DNS service, i.e. it will only serve answers for the zones it hosts.</p>


问:
Protected and private methods in Rails
Method visibility in Ruby (public, protected, and private methods) has been well explained in places like this blog post. But in Ruby on Rails it seems slightly different than it would be in a regular Ruby application because of the way the framework is set up. So, in Rails models, controllers, helpers, tests, etc., when is/isn't it appropriate to use protected or private methods?

Edit: Thanks for the answers so far. I understand the concept of protected and private in Ruby, but I'm looking more for an explanation of the typical way those types of visibility are used within the context of the various pieces of a Rails app (models, controllers, helpers, tests). For example, public controller methods are action methods, protected methods in the application controller are used for "helper methods" that need to be accessed by multiple controllers, etc.

答:
You use a private method if you want no one else but self to use a method. You use a protected method if you want something only self and is_a?(self) s can call.

A good use of protected might be if you had a "virtual" initialization method.

```<code>class Base
    def initialize()
        set_defaults()
        #other stuff
    end

    protected
    def set_defaults()
        # defaults for this type
        @foo = 7
        calculate_and_set_baz()
    end

    private
    def calculate_and_set_baz()
        @baz = "Something that only base classes have like a file handle or resource"
    end
end

class Derived < Base
    protected
    def set_defaults()
        @foo = 13
    end
end
</code>```

@foo will have different values. and the Derived instances will not have @baz

Update:
Since I wrote this, some things have changed in Ruby 2.0+ Aaron Patterson has an excellent write up http://tenderlovemaking.com/2012/09/07/protected-methods-and-ruby-2-0.html

Title: Protected and private methods in Rails

Body:
You use a private method if you want no one else but self to use a method. You use a protected method if you want something only self and is_a?(self) s can call.

A good use of protected might be if you had a "virtual" initialization method.

class Base
    def initialize()
        set_defaults()
        #other stuff
    end

    protected
    def set_defaults()
        # defaults for this type
        @foo = 7
        calculate_and_set_baz()
    end

    private
    def calculate_and_set_baz()
        @baz = "Something that only base classes have like a file handle or resource"
    end
end

class Derived < Base
    protected
    def set_defaults()
        @foo = 13
    end
end

@foo will have different values. and the Derived instances will not have @baz

Update:
Since I wrote this, some things have changed in Ruby 2.0+ Aaron Patterson has an excellent write up http://tenderlovemaking.com/2012/09/07/protected-methods-and-ruby-2-0.html


问:
VBA Macro can't find the last used cell with ActiveCell
I would like to copy paste some values from one (src)Workbook to my (dst)workbook by finding the last not empty cell.

In my case, the copy paste is working fine until the the src Workbook has no entry.

Outcome of my macro looks like:

```<code>Header - |email   |Name  |origin
1.row  - |email3  |Name2 |CH3
2.row  - |email2  |empty |ch2
</code>```

What I expected is:

```<code>Header - email  |Name    |origin
1.row  - email3 |x       |CH3
2.row  - email2 |Name2   |ch2
</code>```

My code block:

```<code>Workbooks.Open (Filepath & MyFile)
Range("A2").Copy
ActiveWorkbook.Close savechanges:=False

erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("AP217").Range(Cells(erow, 1), Cells(erow, 1))

If ActiveCell.Value = "" Then
ActiveCell.Value = "x"
End If
</code>```

It would be great, if someone could advise.

Cheers

答:
I would simply handle the error, something like this:</p>

```<code>erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

On Error Resume Next ' ADD THIS LINE

ActiveSheet.Paste Destination:=Worksheets("AP217").Range(Cells(erow, 1), Cells(erow, 1))

On Error GoTo 0 ' ADD THIS LINE -- this cancels the "Resume next", just in case...
</code>```

Body:
I would like to copy paste some values from one (src)Workbook to my (dst)workbook by finding the last not empty cell.

In my case, the copy paste is working fine until the the src Workbook has no entry.

Outcome of my macro looks like:

Header - |email   |Name  |origin
1.row  - |email3  |Name2 |CH3
2.row  - |email2  |empty |ch2

What I expected is:

Header - email  |Name    |origin
1.row  - email3 |x       |CH3
2.row  - email2 |Name2   |ch2

My code block:

Workbooks.Open (Filepath & MyFile)
Range("A2").Copy
ActiveWorkbook.Close savechanges:=False

erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("AP217").Range(Cells(erow, 1), Cells(erow, 1))

If ActiveCell.Value = "" Then
ActiveCell.Value = "x"
End If

It would be great, if someone could advise.

Cheers

Body:
I would simply handle the error, something like this:

erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

On Error Resume Next ' ADD THIS LINE

ActiveSheet.Paste Destination:=Worksheets("AP217").Range(Cells(erow, 1), Cells(erow, 1))

On Error GoTo 0 ' ADD THIS LINE -- this cancels the "Resume next", just in case...


问:
If else model not responsive
I am building a model in R and I have a data frame of daily temperature data in Kelvin (.csv file). I will run the model individually for each station. The literature I am basing the model off of states: when the temperature rises above 285.15, spawning is induced and ER or effective reproduction reserve, is reduced to 0, meaning my graphical output should fall to zero and start climbing again after the temperature decreases.

My question is this: How would I write this command into R?

Thus far I have written:

```<code>spawn <- ER
spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-ER', 0)
</code>```

I have also tried:

```<code>if(temperature > 285.15) {ER-ER}
</code>```

My parameters look like this:

```<code>param <- list(Temperature = Mussel_Daily_Temp$AS_TEMP, etc....)
</code>```

Any help would be most appreciated!

Best,

J

答:
Without a data example this is a bit of a challenge...

Right now you are simply creating a 0 for anything at a temp > 285.15

```<code>spawn <- ER
spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-ER', 0)
</code>```

My limited understanding of math says that ER-ER will equal zero - so your TRUE or FALSE results in your ifelse statement are both 0.

If you set spawn to the temperature

```<code>spawn <- ER[Mussel_Daily_Temp$AS_TEMP == 285.15]
</code>```

Then adjust your ifelse statement

```<code>spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-spawn', 0)
</code>```

I think you will get something close to what you are looking for.

Title: If else model not responsive

Body:
I am building a model in R and I have a data frame of daily temperature data in Kelvin (.csv file). I will run the model individually for each station. The literature I am basing the model off of states: when the temperature rises above 285.15, spawning is induced and ER or effective reproduction reserve, is reduced to 0, meaning my graphical output should fall to zero and start climbing again after the temperature decreases.

My question is this: How would I write this command into R?

Thus far I have written:

spawn <- ER
spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-ER', 0)

I have also tried:

if(temperature > 285.15) {ER-ER}

My parameters look like this:

param <- list(Temperature = Mussel_Daily_Temp$AS_TEMP, etc....)

Any help would be most appreciated!

Best,

J

Body:
Without a data example this is a bit of a challenge...

Right now you are simply creating a 0 for anything at a temp > 285.15

spawn <- ER
spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-ER', 0)

My limited understanding of math says that ER-ER will equal zero - so your TRUE or FALSE results in your ifelse statement are both 0.

If you set spawn to the temperature

spawn <- ER[Mussel_Daily_Temp$AS_TEMP == 285.15]

Then adjust your ifelse statement

spawning <- ifelse(Mussel_Daily_Temp$AS_TEMP > 285.15, 'ER-spawn', 0)

I think you will get something close to what you are looking for.


问:
javascript eventElement.resizable is not a function
I have looked around and although I have found similar questions to this one, none of them had any solutions that worked for me.

my fullcalendar.js gets an error : eventElement.resizable is not a function

```<code>function resizableSlotEvent(event, eventElement, timeElement) {
    var snapDelta, prevSnapDelta;
    var snapHeight = getSnapHeight();
    var snapMinutes = getSnapMinutes();
    eventElement.resizable({             <----get error
        handles: {
            s: '.ui-resizable-handle'
        },
     ...
</code>```

my html

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

<link rel="stylesheet" href="{% static 'css/main.css' %}">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css"/>

<link href='{% static "css/fullcalendar.css" %}' rel='stylesheet' />
<link href='{% static "css/fullcalendar.print.css" %}' rel='stylesheet' media='print' />

<!-- JS-->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script>

<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery.min.js'></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/moment.min.js'></script>
<script src="http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery-ui.custom.min.js"></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/fullcalendar.min.js'></script>

<script type="text/javascript" src="{% static 'js/fullcalendar.js'%}"></script>
<script type="text/javascript" src="{% static 'js/main.js' %}"></script>
</code>```

I tried a lot of answers of stackoverflow. But I can't solved the problem. Anyone help?

答:
That custom jqueryui js doesn't seem to include the resizable plugin, and the code you're showing relies on it.

Try it with the full js of a recent jQuery ui instead.

Body:
I have looked around and although I have found similar questions to this one, none of them had any solutions that worked for me.

my fullcalendar.js gets an error : eventElement.resizable is not a function

function resizableSlotEvent(event, eventElement, timeElement) {
    var snapDelta, prevSnapDelta;
    var snapHeight = getSnapHeight();
    var snapMinutes = getSnapMinutes();
    eventElement.resizable({             <----get error
        handles: {
            s: '.ui-resizable-handle'
        },
     ...

my html

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

<link rel="stylesheet" href="{% static 'css/main.css' %}">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css"/>

<link href='{% static "css/fullcalendar.css" %}' rel='stylesheet' />
<link href='{% static "css/fullcalendar.print.css" %}' rel='stylesheet' media='print' />

I tried a lot of answers of stackoverflow. But I can't solved the problem. Anyone help?


问:
File does not end with a newline [NewlineAtEndOfFile]
When trying to use mvn clean install on my project I'm getting those errors:

```<code>[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\eclipse-code-formatter-js.xml:0: File does not end with a newline. [NewlineAtEndOfFile]
[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\eclipse-code-formatter.xml:0: File does not end with a newline. [NewlineAtEndOfFile]
[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\pom.xml:0: File does not end with a newline. [NewlineAtEndOfFile]
[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\README.txt:0: File does not end with a newline. [NewlineAtEndOfFile]
Audit done.
[INFO] There are 4 errors reported by Checkstyle 7.2 with zanata-build-tools/checkstyle.xml ruleset.
[ERROR] eclipse-code-formatter-js.xml:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.
[ERROR] eclipse-code-formatter.xml:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.
[ERROR] pom.xml:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.
[ERROR] README.txt:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.
</code>```

Putting paragraphs or \n at the end of those files does not solve this issue.
In Eclipse under     Window >> Preferences >> Checkstyle >> Select the configuration file >> those files aren't listed.

Using:

Windows 10

Java 8

Eclipse Neon.1 (4.6.1)

Maven 3.0.4

答:
The cause is a checkstyle rule called NewlineAtEndOfFile which prevents a successful build if any of the project's files does not have a new line at its end.

The rule says:

Rationale: Any source files and text files in general should end with
  a line separator to let other easily add new content at the end of
  file and "diff" command does not show previous lines as changed.

So what must be done, is simply to add a new line at the end of each of the files mentioned in the above logs:

. eclipse-code-formatter-js.xml

. eclipse-code-formatter.xml

. pom.xml

. README.txt

For more infos on this rule: checkstyle-NewlineAtEndOfFile-rule

Body:
When trying to use mvn clean install on my project I'm getting those errors:

[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\eclipse-code-formatter-js.xml:0: File does not end with a newline. [NewlineAtEndOfFile]
[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\eclipse-code-formatter.xml:0: File does not end with a newline. [NewlineAtEndOfFile]
[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\pom.xml:0: File does not end with a newline. [NewlineAtEndOfFile]
[ERROR] C:\Users\lob\Downloads\zanata-platform-platform-4.0.0\zanata-platform-platform-4.0.0\parent\README.txt:0: File does not end with a newline. [NewlineAtEndOfFile]
Audit done.
[INFO] There are 4 errors reported by Checkstyle 7.2 with zanata-build-tools/checkstyle.xml ruleset.
[ERROR] eclipse-code-formatter-js.xml:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.
[ERROR] eclipse-code-formatter.xml:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.
[ERROR] pom.xml:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.
[ERROR] README.txt:[0] (misc) NewlineAtEndOfFile: File does not end with a newline.

Putting paragraphs or \n at the end of those files does not solve this issue.
In Eclipse under     Window >> Preferences >> Checkstyle >> Select the configuration file >> those files aren't listed.

Using:

Windows 10

Java 8

Eclipse Neon.1 (4.6.1)

Maven 3.0.4


问:
Laravel 5 error message if keywords not exist
I am receiving this message as it is.
I want an error message when I call something that is not databased.

I am new at laravel, i know i have to write elseif condition, but i don't know how.

FatalErrorException

Method Illuminate\View\View::__toString() must not throw an exception,
  caught ErrorException: Undefined variable: yyy (View:
  /Users/xxx/Work/yyy/resources/views/yyy/index.blade.php)

```<code>    <?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;

class SearchController extends Controller {

public function getSearch(Request $request) {

    $search = $request->input('search');

    if(empty($search)) {
        return "please search something!";
    }

    $searchResult = DB::table('yyy')->where('dateOfReport', 'LIKE', "%$search%")->get()->toArray();

    return view('search.searchResult', ['searchResult' => $searchResult, 'search' => $search]);
}

}
</code>```

Also here is my view.blade file:

```<code>@extends('layout')

@section('content')

<h1>Detaily yyy Reports</h1>

<h2>{{$yyy->temperature }}°C</h2>

<p>{{$yyy->dateOfReport}}

    <a href="/yyy/{{$yyy->id}}/delete" onclick="return confirm('Are you sure to delete?');"><font color="red">Delete</font></a>

    Report created at: {{$yyy->created_at}}

    @if($yyy->created_at != $yyy->updated_at)

    Report updated at: {{$yyy->updated_at}}

    {{ csrf_field() }}

    @endif

@endsection
</code>```

thank you for your time!

答:
this error seems to originate in your view code, not the controller.

you probably use a $yyy variable in your view, while you didn't assign it in the controller.
i.e.

```<code>return view('search.searchResult', ['searchResult' => $searchResult, 'search' => $search, 'yyy' => 'this is your assigned variable value']);
</code>```

Body:
I am receiving this message as it is.
I want an error message when I call something that is not databased.

I am new at laravel, i know i have to write elseif condition, but i don't know how.

FatalErrorException

Method Illuminate\View\View::__toString() must not throw an exception,
  caught ErrorException: Undefined variable: yyy (View:
  /Users/xxx/Work/yyy/resources/views/yyy/index.blade.php)

    <?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;

class SearchController extends Controller {

public function getSearch(Request $request) {

    $search = $request->input('search');

    if(empty($search)) {
        return "please search something!";
    }

    $searchResult = DB::table('yyy')->where('dateOfReport', 'LIKE', "%$search%")->get()->toArray();

    return view('search.searchResult', ['searchResult' => $searchResult, 'search' => $search]);
}

}

Also here is my view.blade file:

@extends('layout')

@section('content')

Detaily yyy Reports

{{$yyy->temperature }}°C

{{$yyy->dateOfReport}}

    id}}/delete" onclick="return confirm('Are you sure to delete?');">Delete

    Report created at: {{$yyy->created_at}}

    @if($yyy->created_at != $yyy->updated_at)

    Report updated at: {{$yyy->updated_at}}

    {{ csrf_field() }}

    @endif

@endsection

thank you for your time!

Body:
this error seems to originate in your view code, not the controller.

you probably use a $yyy variable in your view, while you didn't assign it in the controller.
i.e.

return view('search.searchResult', ['searchResult' => $searchResult, 'search' => $search, 'yyy' => 'this is your assigned variable value']);


问:
Specified cast is not valid on listview item c#
I basically have a listview, with this function when i click on a listview-item.

When i run this and click on the item, i get the following display alerts before my app crashes.

DisplayAlert 1, then DisplayAlert 2, then DisplayAlert 1 and right after this one my app crashes. With "Specified cast is not valid".

I dont know why i get the DisplayAlert 1 again, and why this crashes.

```<code>public async void OnSelection(object sender, SelectedItemChangedEventArgs e)
    {
        await DisplayAlert("1", "1", "1");
        if (e.SelectedItem == null)
        {
            return; // ItemSelected is called on deselection, which results in SelectedItem being set to null
        }

        //((ListView)sender).SelectedItem = null;

        await DisplayAlert("2", "2", "2");
        // Cast to zoneviewmodel type
        var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem;

        await DisplayAlert("3", "3", "3");
        // Redirect to login
        await Navigation.PushAsync(new LoginPage(selectedZone.Address));

        await DisplayAlert("4", "4", "4");
        // send message containing information to fill loginpage information
        MessagingCenter.Send<MainPage, ViewModel.ZoneViewModel>(this, "loginInfo", selectedZone);
    }
</code>```

答: In this line: var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem; you're trying to cast whatever is in your list to ViewModel.ZoneViewModel. The error is telling you this list item is not assignable to this type. If you're not sure what type the item is, step through or print out e.SelectedItem.GetType().

Body:
I basically have a listview, with this function when i click on a listview-item.

When i run this and click on the item, i get the following display alerts before my app crashes.

DisplayAlert 1, then DisplayAlert 2, then DisplayAlert 1 and right after this one my app crashes. With "Specified cast is not valid".

I dont know why i get the DisplayAlert 1 again, and why this crashes.

public async void OnSelection(object sender, SelectedItemChangedEventArgs e)
    {
        await DisplayAlert("1", "1", "1");
        if (e.SelectedItem == null)
        {
            return; // ItemSelected is called on deselection, which results in SelectedItem being set to null
        }

        //((ListView)sender).SelectedItem = null;

        await DisplayAlert("2", "2", "2");
        // Cast to zoneviewmodel type
        var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem;

        await DisplayAlert("3", "3", "3");
        // Redirect to login
        await Navigation.PushAsync(new LoginPage(selectedZone.Address));

        await DisplayAlert("4", "4", "4");
        // send message containing information to fill loginpage information
        MessagingCenter.Send<MainPage, ViewModel.ZoneViewModel>(this, "loginInfo", selectedZone);
    }


问:
Setting Android Privacy Policy
I am using AdMob in my android application. Do i need to create a Privacy Policy in my application to inform users about cookies that Google uses?

If yes where do i need to put it?

Do i must write it in descriptions on Google Play? Or on fist run do I must show a fragment window? Or can I write the Privacy Policy just in section "About App"?

What do I write?

I read the Google Documents, but i didn't understand clearly.

https://support.google.com/googleplay/android-developer/answer/2519872?hl=en

答:
I made a public gist and posted the url here is the gist
you can check here
play store</p>

Title: Setting Android Privacy Policy


问:
How to re-rank documents based on their attributes rather than just their field relevance?
I'm trying to use Solr to re-rank document results based relevance to the user searching. For example, if I search joann*this could return documents where the Name field is anything from joanna to joanne. What I'm trying to do is to return documents that match on certain attributes that I have as well-- this could be something like us both having the field Location = "NYC".

So my question is two fold- is there a way to grab and handle a users information when they are making a query and also is there a way to re-rank based on these additional field values? Would this look more like writing some code or just an expanded query?

答: it looks to me like you are talking about functionality that Query Reranking exactly provides. Did you check that out?</p>


问:
Use both Microsoft Office365 (Outlook) API and Graph API with the same token
I've been working with Office365(Outlook)  API for a while (https://outlook.office.com)

Now I need to be able to upload files. I found that it can only be done with using other service. (e.x. Microsoft Graph).

e.g. https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createuploadsession

The problem is that with my current authentication I can't access both services at the same time:

https://outlook.office.com

https://graph.microsoft.com

Now I use scope:

```<code>openid offline_access profile
https://outlook.office.com/calendars.readwrite.shared
</code>```

When I add Files.ReadWrite.All to it, I'm no longer able to access outlook end-points. I get the following error:

```<code>The audience claim value is invalid 'https://graph.microsoft.com'
</code>```

Is there a way to be able to invoke both services with the same token? Maybe any workaround?

答:
No, you can't use the same token. Access tokens are scoped to a particular API via the audience claim. The Outlook API rejects your token because the audience claim inside the token is set for Graph.

The easiest solution for you would be to just use Graph for your Outlook-related stuff. They are pretty close in terms of what is supported (see https://learn.microsoft.com/en-us/outlook/rest/compare-graph-outlook).

If there's something you're using that's only available on the Outlook endpoint, then you'll need to use a separate token.

Body:
I've been working with Office365(Outlook)  API for a while (https://outlook.office.com)

Now I need to be able to upload files. I found that it can only be done with using other service. (e.x. Microsoft Graph).

e.g. https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createuploadsession

The problem is that with my current authentication I can't access both services at the same time:

https://outlook.office.com

https://graph.microsoft.com

Now I use scope:

openid offline_access profile
https://outlook.office.com/calendars.readwrite.shared

When I add Files.ReadWrite.All to it, I'm no longer able to access outlook end-points. I get the following error:

The audience claim value is invalid 'https://graph.microsoft.com'

Is there a way to be able to invoke both services with the same token? Maybe any workaround?


问:
Deleting service via terminal in Grails
I know I can do it manually but is there any grails create-service counterpart for removing a service?

答: No, there is not.  As others have said, removal is more dangerous than creation.  Either use an IDE, or remove the service manually after checking for any usages.</p>

Title: Deleting service via terminal in Grails


问:
error package android.support.design.widget does not exist
when i try to build my android project i get this errors

Error:(8, 37) error: package android.support.design.widget does not
  exist Error:(18, 9) error: cannot find symbol class TabLayout
  Error:(18, 32) error: cannot find symbol class TabLayout Error:(21,
  33) error: cannot find symbol variable TabLayout Error:(27, 56) error:
  package TabLayout does not exist Error:(48, 36) error: cannot find
  symbol variable menu Error:(28, 57) error: package TabLayout does not
  exist Error:Execution failed for task
  ':app:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details. Error:(55, 23) error: cannot find symbol variable action_settings

and this is my code

```<code>package com.chaos.creativo;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.design.widget.TabLayout;

/**
 * Created by ahmed on 3/7/2016.
 */
public class Signin_up extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signing_up);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("SIGN IN"));
        tabLayout.addTab(tabLayout.newTab().setText("SIGN UP"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

my build.gradle

```<code>> apply plugin: 'com.android.application'
>
> android {
>     compileSdkVersion 23
>     buildToolsVersion "23.0.2"
>
>     defaultConfig {
>         applicationId "com.chaos.creativo"
>         minSdkVersion 18
>         targetSdkVersion 23
>         versionCode 1
>         versionName "1.0"
>     }
>     buildTypes {
>         release {
>             minifyEnabled false
>             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
>         }
>     } }
>
> dependencies {
>     compile fileTree(dir: 'libs', include: ['*.jar'])
>     testCompile 'junit:junit:4.12'
>     compile 'com.android.support:appcompat-v7:23.1.1'
>     compile 'com.google.android.gms:play-services-ads:8.4.0'
>     compile 'com.google.android.gms:play-services-identity:8.4.0'
>     compile 'com.firebase:firebase-client-android:2.3.1'
>     compile 'com.google.android.gms:play-services-gcm:8.4.0'
>     compile 'com.android.support:support-v4:23.2'
>     compile 'com.android.support:design:23.2' }
</code>```

答:
For API 25 this worked for me:</p>

```<code>compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:design:25.2.0'
</code>```

Body:
when i try to build my android project i get this errors

Error:(8, 37) error: package android.support.design.widget does not
  exist Error:(18, 9) error: cannot find symbol class TabLayout
  Error:(18, 32) error: cannot find symbol class TabLayout Error:(21,
  33) error: cannot find symbol variable TabLayout Error:(27, 56) error:
  package TabLayout does not exist Error:(48, 36) error: cannot find
  symbol variable menu Error:(28, 57) error: package TabLayout does not
  exist Error:Execution failed for task
  ':app:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details. Error:(55, 23) error: cannot find symbol variable action_settings

and this is my code

package com.chaos.creativo;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.design.widget.TabLayout;

/**
 * Created by ahmed on 3/7/2016.
 */
public class Signin_up extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signing_up);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("SIGN IN"));
        tabLayout.addTab(tabLayout.newTab().setText("SIGN UP"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

my build.gradle

> apply plugin: 'com.android.application'
>
> android {
>     compileSdkVersion 23
>     buildToolsVersion "23.0.2"
>
>     defaultConfig {
>         applicationId "com.chaos.creativo"
>         minSdkVersion 18
>         targetSdkVersion 23
>         versionCode 1
>         versionName "1.0"
>     }
>     buildTypes {
>         release {
>             minifyEnabled false
>             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
>         }
>     } }
>
> dependencies {
>     compile fileTree(dir: 'libs', include: ['*.jar'])
>     testCompile 'junit:junit:4.12'
>     compile 'com.android.support:appcompat-v7:23.1.1'
>     compile 'com.google.android.gms:play-services-ads:8.4.0'
>     compile 'com.google.android.gms:play-services-identity:8.4.0'
>     compile 'com.firebase:firebase-client-android:2.3.1'
>     compile 'com.google.android.gms:play-services-gcm:8.4.0'
>     compile 'com.android.support:support-v4:23.2'
>     compile 'com.android.support:design:23.2' }

Body:
For API 25 this worked for me:

compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:design:25.2.0'


问:
Using HOCs on Generic Typescript React Components
I have a React component which is typed with a generic. That component in turn is extended with a higher order component (in this case, redux-form). Here's a stripped back version of my class and the HOC being applied:

```<code>import * as React from "react";

interface MyFormProps<D> {
    prop: D;
    form: string;
}

class MyForm<D> extends React.Component<MyFormProps<D>, {}> {
    render(): JSX.Element {
        return (
            <form>
                {this.props.prop}
            </form>
        );
    }
}

export const ConnectedMyForm = reduxForm({} as Config<any, {}, {}>)(MyForm);
</code>```

Then I try to create a typed version of my component in another component.

```<code>import { ConnectedMyForm } from "./my-form";

interface FormType {
    // Form props here
}

type TypedForm = new () => ConnectedMyForm<FormType>;
const TypedForm = ConnectedMyForm as TypedForm;
</code>```

In order to be able to use it in TSX as follows:

```<code><TypedForm />
</code>```

This method works absolutely fine on another Component I've built which doesn't have HOC applied but here I get the following error:

error TS2304: Cannot find name 'ConnectedMyForm'.

on the type TypedForm = new () => ConnectedMyForm<FormType>; line.

This only happens when I apply the HOC function to my component. I'm guessing it's because I've not specified the generic typing on the connected version of the form. But how would I specify that typing?

答:
Why not just create a hoc/EnhancedForm like:

```<code>import * as React from 'react';

interface EnhancedProps {
    name: string;
}

export default <T extends {}>(Component: React.StatelessComponent<T> | React.ComponentClass<T>):
    React.StatelessComponent<T & EnhancedProps> =>
    (props: T & EnhancedProps) => {
        return <Component { ...props } />
    }
</code>```

And then just use that HoC in your SimpleForm like:

```<code>const SimpleForm = props => {

  const handleSubmit = () => { alert("Validated"); }

  const { pristine, reset, submitting } = props
  return (
    <form onSubmit={ handleSubmit }>
      <div>
        <label>First Name</label>
        ....
    </form>
  )
}

export default EnhancedForm(reduxForm({
  form: 'simple' // a unique identifier for this form
})(SimpleForm))
</code>```

And finally use it as you describe:

```<code>render() {
    return (
      <SimpleForm name="SimpleName" />
    );
  }
</code>```

Body:
I have a React component which is typed with a generic. That component in turn is extended with a higher order component (in this case, redux-form). Here's a stripped back version of my class and the HOC being applied:

import * as React from "react";

interface MyFormProps<D> {
    prop: D;
    form: string;
}

class MyForm<D> extends React.Component<MyFormProps<D>, {}> {
    render(): JSX.Element {
        return (
            <form>
                {this.props.prop}
            </form>
        );
    }
}

export const ConnectedMyForm = reduxForm({} as Config<any, {}, {}>)(MyForm);

Then I try to create a typed version of my component in another component.

import { ConnectedMyForm } from "./my-form";

interface FormType {
    // Form props here
}

type TypedForm = new () => ConnectedMyForm<FormType>;
const TypedForm = ConnectedMyForm as TypedForm;

In order to be able to use it in TSX as follows:

<TypedForm />

This method works absolutely fine on another Component I've built which doesn't have HOC applied but here I get the following error:

error TS2304: Cannot find name 'ConnectedMyForm'.

on the type TypedForm = new () => ConnectedMyForm<FormType>; line.

This only happens when I apply the HOC function to my component. I'm guessing it's because I've not specified the generic typing on the connected version of the form. But how would I specify that typing?

Body:
Why not just create a hoc/EnhancedForm like:

import * as React from 'react';

interface EnhancedProps {
    name: string;
}

export default <T extends {}>(Component: React.StatelessComponent<T> | React.ComponentClass<T>):
    React.StatelessComponent<T & EnhancedProps> =>
    (props: T & EnhancedProps) => {
        return <Component { ...props } />
    }

And then just use that HoC in your SimpleForm like:

const SimpleForm = props => {

  const handleSubmit = () => { alert("Validated"); }

  const { pristine, reset, submitting } = props
  return (
    <form onSubmit={ handleSubmit }>
      <div>
        <label>First Name</label>
        ....
    </form>
  )
}

export default EnhancedForm(reduxForm({
  form: 'simple' // a unique identifier for this form
})(SimpleForm))

And finally use it as you describe:

render() {
    return (
      <SimpleForm name="SimpleName" />
    );
  }


问:
getline error, reading every line
```<code>#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;

int main() {
  char input;

  while (true) {
    input = _getch();
    cout << "The input is: " << input << "\n";
  }
  ifstream level1;

  level1.open("level1.txt");

  string str[255];
  while (true) {
    getline(level1 , str );
    cout << str;
  }

   system("PAUSE");
}
</code>```

error im getting:

no no instance of overloaded function "getline" matches the argument list

what im trying to do is real every line inside the text file

答: getline take a string as second parameter, not an array of string.</p>

Title: getline error, reading every line

Body:
#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;

int main() {
  char input;

  while (true) {
    input = _getch();
    cout << "The input is: " << input << "\n";
  }
  ifstream level1;

  level1.open("level1.txt");

  string str[255];
  while (true) {
    getline(level1 , str );
    cout << str;
  }

   system("PAUSE");
}

error im getting:

no no instance of overloaded function "getline" matches the argument list

what im trying to do is real every line inside the text file


问:
difference between wtpwebapps and webapps II
I am new to the Eclipse wtpwebapps thing and am learning this practice in my new project. What I found out is that, if I directly copy project folders under wtpwebapps into traditional installed tomcat webapps folder, then startup tomcat .bat file, the application does not start as I expected it to. I am trying to start the server directly use the "target" folder content after "mvn clean install".  </p>

答: I managed to resolve this by going to Eclipse severs tab, expand the server, then choose the "Modules" tab, then "add external web module", over there, I point the document base to the physical path of mvn target folder. run the server and the app starts. </p>