问:
Select value from different row based on value of certain column
For example I have data like this like this

```<code>    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   null    |   a
 20022   |   2    |   a     |   null    |   a
 20023   |   3    |   a     |   null    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b
</code>```

what I need is when value in Col_3 is null and Col_1 is not 4,
then select value in Col_3 where Col_1 = 4, that have the same

I tried using this case statement:

```<code>select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 1
     then (select col_3 from table s where s.date = 4
           and s.col_1= seg.col_1 and s.col_4= seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3
  end as col_3
from table seg
</code>```

but for some reason it's not doing what I need it to do
I need it to change the results of the table above to become like this:

```<code>    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   4.5    |   a
 20022   |   2    |   a     |   4.5    |   a
 20023   |   3    |   a     |   4.5    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b
</code>```

答:
Maybe use an OUTER APPLY (or CROSS APPLY if you can guarantee quarter 4 is there) to always have quarter 4 available per year per col4 then just use it where you have to.

```<code>select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 4
     then backfill.col_3
    else seg.col_3
  end as col_3
from table seg
outer apply (select col_3 from table where col_1 = 4 and left(date,4) = left(seg.date,4)) and col_4 = seg.col_4) backfill
</code>```

If you'd rather stick with CASE, this should work.

```<code>case when col_3 is null and col_1 != 4
     then (select col_3 from table s where s.col_1 = 4
           and s.col_4 = seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3
</code>```

Body:
For example I have data like this like this

    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   null    |   a
 20022   |   2    |   a     |   null    |   a
 20023   |   3    |   a     |   null    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b

what I need is when value in Col_3 is null and Col_1 is not 4,
then select value in Col_3 where Col_1 = 4, that have the same

I tried using this case statement:

select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 1
     then (select col_3 from table s where s.date = 4
           and s.col_1= seg.col_1 and s.col_4= seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3
  end as col_3
from table seg

but for some reason it's not doing what I need it to do
I need it to change the results of the table above to become like this:

    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   4.5    |   a
 20022   |   2    |   a     |   4.5    |   a
 20023   |   3    |   a     |   4.5    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b

Body:
Maybe use an OUTER APPLY (or CROSS APPLY if you can guarantee quarter 4 is there) to always have quarter 4 available per year per col4 then just use it where you have to.

select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 4
     then backfill.col_3
    else seg.col_3
  end as col_3
from table seg
outer apply (select col_3 from table where col_1 = 4 and left(date,4) = left(seg.date,4)) and col_4 = seg.col_4) backfill

If you'd rather stick with CASE, this should work.

case when col_3 is null and col_1 != 4
     then (select col_3 from table s where s.col_1 = 4
           and s.col_4 = seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3


来源: stackexchange

问:
Is there a way to DeserializeObject without empty constructor?
I am currently in the progress of enabling non-nullable reference types for my .net core api.

The problem is that the integrationtest fails when trying to deserializeObject because it has no empty constructor. I can't have an empty constructor because that will make property: possible null.

The problem:

JsonConvert.DeserializeObject<ViewModel>(result); calls the constructor which has a constructor with an object argument ViewModel(Model model). In the test this is null.

I have made a simple sample:

The api:

```<code>public class Dog
    {
        public string Name { get; set; } = null!;
    }

    public class DogViewModel
    {

        public DogViewModel(Dog dog)
        {
            Name = dog.Name;
        }

        public string Name { get; set; }
    }

    [HttpGet]
    [Route("dog")]
    public DogViewModel GetDog()
    {
        var dog = new Dog
        {
            Name = "Fido"
        };
        return new DogViewModel(dog);
    }
</code>```

This works when I use a client to call the api, but it fails from the tests:

Test

```<code>    [Fact]
    public async Task GetDog()
    {

        var response = await Client.GetAsync("dog");

        var result = response.Content.ReadAsStringAsync().Result;
        Assert.True(response.IsSuccessStatusCode, result);
        var responeseAsObject = JsonConvert.DeserializeObject<DogViewModel>(result); <----- this is where it breaks
        Assert.IsType<string>(responeseAsObject.Name);
        Assert.NotNull(responeseAsObject);
    }
</code>```

JsonConvert.DeserializeObject calls the constructor of DogViewModel;  DogViewModel(Dog dog), but dog is null.

答:
The question is, as @CodeCaster points out, nonsensical- But i found a non-optimal solution.

In the test project i created this:

```<code>  public class TestDogViewModel : DogViewModel
    {

        public TestDogViewModel() : base(new Dog {Name = ""})
        {
        }

    }
</code>```

When deserializing i used this:

```<code>var responeseAsObject = JsonConvert.DeserializeObject<TestDogViewModel>(result);
</code>```

Developers won't use this viewModel by mistake since the project doesn't have a reference to the test project,

So now if you want to have a DogViewModel you would need to have a dog. It kinda makes more sense in my real project :S.

ContentLicense: CC BY-SA 4.0

Body:
I am currently in the progress of enabling non-nullable reference types for my .net core api.

The problem is that the integrationtest fails when trying to deserializeObject because it has no empty constructor. I can't have an empty constructor because that will make property: possible null.

The problem:

JsonConvert.DeserializeObject<ViewModel>(result); calls the constructor which has a constructor with an object argument ViewModel(Model model). In the test this is null.

I have made a simple sample:

The api:

public class Dog
    {
        public string Name { get; set; } = null!;
    }

    public class DogViewModel
    {

        public DogViewModel(Dog dog)
        {
            Name = dog.Name;
        }

        public string Name { get; set; }
    }

    [HttpGet]
    [Route("dog")]
    public DogViewModel GetDog()
    {
        var dog = new Dog
        {
            Name = "Fido"
        };
        return new DogViewModel(dog);
    }

This works when I use a client to call the api, but it fails from the tests:

Test

    [Fact]
    public async Task GetDog()
    {

        var response = await Client.GetAsync("dog");

        var result = response.Content.ReadAsStringAsync().Result;
        Assert.True(response.IsSuccessStatusCode, result);
        var responeseAsObject = JsonConvert.DeserializeObject<DogViewModel>(result); <----- this is where it breaks
        Assert.IsType<string>(responeseAsObject.Name);
        Assert.NotNull(responeseAsObject);
    }

JsonConvert.DeserializeObject calls the constructor of DogViewModel;  DogViewModel(Dog dog), but dog is null.

Body:
The question is, as @CodeCaster points out, nonsensical- But i found a non-optimal solution.

In the test project i created this:

  public class TestDogViewModel : DogViewModel
    {

        public TestDogViewModel() : base(new Dog {Name = ""})
        {
        }

    }

When deserializing i used this:

var responeseAsObject = JsonConvert.DeserializeObject<TestDogViewModel>(result);

Developers won't use this viewModel by mistake since the project doesn't have a reference to the test project,

So now if you want to have a DogViewModel you would need to have a dog. It kinda makes more sense in my real project :S.


问:
Add event to Google's calendar in Flutter
I've found this official package: https://pub.dev/packages/googleapis#-readme-tab-

I'm looking to add events to Google's calendar but the plugin doesn't have too much information about it. It points to Google documentation but inside that link doesn't mention anything about Flutter or any examples.

Does anyone have some experience with this?

答:
Using add_2_calendar will add the event to Google's calendar directly:

```<code>final Event newEvent = Event(
        title: "title",
        description: "description",
        location: address,
        startDate: eventDate,
        endDate: eventDate.add(
          Duration(minutes: 30),
        ),
      );

      addEvent2Cal(newEvent);
</code>```

Body:
Using add_2_calendar will add the event to Google's calendar directly:

final Event newEvent = Event(
        title: "title",
        description: "description",
        location: address,
        startDate: eventDate,
        endDate: eventDate.add(
          Duration(minutes: 30),
        ),
      );

      addEvent2Cal(newEvent);


答:
You can do like this, tuning envelope as you wish:

```<code>import numpy as np
import matplotlib.pyplot as plot

x = np.array([ 33.5 , ...])

mean = np.mean(x)
envelope = 0.1

for i in range(len(x)-1, -1, -1):
    if abs(x[i]-mean) > envelope:
        i -= 1
        break

plot.plot(x, '.')
plot.axvline(i)
plot.show()
</code>```

With envelope = 0.5

With envelope = 0.1

Title: Python to determine when array is not significantly increasing or decreasing anymore

Body:
Given an array like the following:

array([ 33.5 , -12.17,  -1.58,  -6.15,   4.73,  -5.62,  -5.59,  -0.79,
        -4.73,   0.58,   1.07,  -1.33,   1.22,   2.72,  -3.24,  -3.33,
         0.65,   0.79,   2.66,  -1.45,   2.  ,   3.52,  -0.6 ,   1.36,
        -0.51,  -1.25,  -0.37,   0.55,   2.01,  -0.25,   0.08,  -0.38,
         0.94,   0.4 ,  -1.15,  -1.2 ,  -1.11,   1.33,  -1.11,   1.02,
        -0.55,   0.59,  -0.8 ,  -0.28,  -0.61,   0.48,  -1.94,   0.14,
        -0.79,  -1.34,   0.46,   0.69,  -0.08,  -0.2 ,   0.16,  -1.42,
        -0.29,  -0.48,  -0.03,  -0.03,  -0.39,   0.74,   0.04,   0.5 ,
         0.2 ,   0.09,   1.53,  -0.98,   0.22,   0.86,  -0.05,   0.06,
         0.08,  -0.69,  -0.54,  -0.77,   0.35,   0.45,  -0.16,  -0.07,
        -0.32,   1.01,   0.21,  -0.24,   0.06,  -0.54,  -0.2 ,  -0.36,
         0.27,   0.36,   0.16,  -0.29,   0.04,  -0.53,   0.46,   0.37,
         0.14,  -0.41,   0.3 ,  -0.09,  -0.49,  -0.26,  -0.16,  -0.33,
        -0.03,  -0.46,   0.14,   0.01,  -0.41,   0.29,  -0.17,  -0.16,
        -0.09,   0.1 ,   0.04,  -0.08,  -0.33,  -0.06,  -0.09,  -0.21,
         0.06,  -0.31,  -0.23,  -0.15,   0.02,  -0.11,  -0.49,   0.22,
         0.49,  -0.22,   0.07,  -0.02,  -0.07,  -0.47,  -0.22,  -0.13,
         0.22,   0.23,   0.17,  -0.18,  -0.09,  -0.22,  -0.29,   0.19,
         0.01,   0.13,   0.22,  -0.29,   0.01,  -0.11,  -0.33,   0.1 ,
         0.1 ,   0.14,  -0.09,  -0.33,  -0.01,   0.29,   0.07,   0.1 ,
         0.09,   0.24,  -0.07,   0.2 ,  -0.13,  -0.04,  -0.39,  -0.12,
        -0.27,   0.01,   0.12,   0.05,  -0.02,  -0.1 ,   0.21,  -0.13,
        -0.02,  -0.11,  -0.03,  -0.19,   0.16,   0.14,   0.06,  -0.12,
         0.04,  -0.47,  -0.06,   0.2 ,   0.13,   0.11,  -0.17,  -0.14,
        -0.02,  -0.33,  -0.21,  -0.22,  -0.1 ,   2.72,   0.03,  -0.09,
         0.03,  -0.07,  -0.14,  -0.03,  -0.16,   0.03,  -0.08,   0.02,
         0.04,  -0.1 ,  -0.04,  -0.05,   0.13,  -0.39,   0.01,  -0.16,
         0.2 ,   0.13,  -0.24,  -0.27,  -0.08,  -0.62,  -0.04,  -0.31,
         0.02,   0.25,   0.23,   0.05,  -0.12,  -0.02,   0.1 ,  -0.02,
        -0.09,   0.27,  -0.14,   0.15,  -0.14,   0.03,  -0.13,  -0.09,
        -0.12,  -0.07,  -0.1 ,   0.06,  -0.13,  -0.05,  -0.07,  -0.17,
        -0.03,  -0.  ,   0.25,   0.1 ,   0.06,   0.16,  -0.01,   0.28,
         0.  ,  -0.07,   0.19,   0.24,   0.02,   0.09,  -0.05,  -0.06,
        -0.05,   0.08,  -0.01,   0.05,  -0.12,  -0.  ,   0.01,  -0.13,
        -0.1 ,   0.05,  -0.18,  -0.13,   0.3 ,   0.21,   0.17,  -0.09,
         0.21,  -0.02,  -0.04,   0.14,   0.22,  -0.09,  -0.04,   0.08,
         0.15,  -0.08,   0.04,  -0.07,  -0.1 ,   0.01,   0.04,  -0.01,
         0.06,   0.01,   0.27,  -0.02,   0.07,  -0.02,   0.22,   0.11,
        -0.03,   0.16,   0.03,  -0.19,   0.16,   0.05,  -0.08,   0.07,
         0.03,  -0.17,   0.13,   0.13,   0.13,  -0.12,  -0.16,  -0.16,
         0.06,   0.2 ,  -0.07,  -0.1 ,  -0.05,  -0.17,   0.02,   0.13,
        -0.04,  -0.07,  -0.17,  -0.18,   0.03,  -0.17,  -0.07,   0.12,
        -0.05,  -0.  ,  -0.  ,   0.14,  -0.13,   0.03])

I'd like to find the index at which the array is not fluctuating, or say when considering the next item is not significant anymore.

How do I determine this point? Is there a way to compute this with pandas for example?
Maybe considering the total average and check if adding an extra item in the computation would increase or decrease significantly the total average?

I tried to find local min and max

 extrema = np.concatenate((argrelmin(array)[0], argrelmax(array)[0]))

but that returns basically the whole array length because there still are fluctuations in the array

Body:
You can do like this, tuning envelope as you wish:

import numpy as np
import matplotlib.pyplot as plot

x = np.array([ 33.5 , ...])

mean = np.mean(x)
envelope = 0.1

for i in range(len(x)-1, -1, -1):
    if abs(x[i]-mean) > envelope:
        i -= 1
        break

plot.plot(x, '.')
plot.axvline(i)
plot.show()

With envelope = 0.5

With envelope = 0.1


问:
Reformat Date Before Form Submitted
I have a form with a date field and a calendar picker. When I use this I have it entering the date as dd/mm/yyyy. This works.

I want to store the date as yyyymmdd though. Is there a way using javascript to reformat the date? For example, I click submit, it reformats the date and then does the submit and writes the reformatted date to the database?

Maybe there is a better approach? e.g. using a hidden input field that has the correctly formatted version of the date somehow?

答:
If you load the value as a Date object, you can format it any way you like. However, please consider the use of a library that already solves this issue for you, like moment.js.

function formatDate() {
  const value = document.getElementById("date-input").value;
  const date = new Date(value);

  const year = date.getFullYear() + "";
  let month = date.getMonth() + 1 + "";
  let day = date.getDate() + "";

  if (day.length == 1) day = "0" + day;
  if (month.length == 1) month = "0" + month;

  const formattedDate = year + "/" + month + "/" + day;

  document.getElementById("date-output").innerHTML = formattedDate;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="date-input" type="date">
<button onclick="formatDate()">format!</button>
<div id="date-output"></div></code>```

Title: Reformat Date Before Form Submitted

Body:
If you load the value as a Date object, you can format it any way you like. However, please consider the use of a library that already solves this issue for you, like moment.js.

function formatDate() {
  const value = document.getElementById("date-input").value;
  const date = new Date(value);

  const year = date.getFullYear() + "";
  let month = date.getMonth() + 1 + "";
  let day = date.getDate() + "";

  if (day.length == 1) day = "0" + day;
  if (month.length == 1) month = "0" + month;

  const formattedDate = year + "/" + month + "/" + day;

  document.getElementById("date-output").innerHTML = formattedDate;
}

<input id="date-input" type="date">
<button onclick="formatDate()">format!</button>
<div id="date-output"></div>


问:
Pivot MySQL rows to columns in view
I have the following tables: days, periods, prices, brands, vehicles.

The Price model belongsTo Day and Period.

DB Schema:

```<code>CREATE TABLE `days` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `low` int(11) NOT NULL DEFAULT '0',
  `high` int(11) DEFAULT '0',
  `brand_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);
CREATE TABLE `periods` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `start` date NOT NULL DEFAULT '0000-00-00',
  `finish` date NOT NULL DEFAULT '0000-00-00',
  `brand_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);
CREATE TABLE `brands` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `brand` varchar(255) NOT NULL DEFAULT '',
  `slug` varchar(20) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
);
CREATE TABLE `vehicles` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `size_id` int(11) DEFAULT NULL,
  `brand_id` int(11) DEFAULT NULL,
  `slug` varchar(50) NOT NULL,
  `model` varchar(50) DEFAULT NULL,
  `image` varchar(50) DEFAULT NULL,
  `short_specs` text,
  `specs` text,
  `publish` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`id`)
);
CREATE TABLE `prices` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `vehicle_id` int(3) NOT NULL DEFAULT '0',
  `day_id` int(3) NOT NULL DEFAULT '0',
  `period_id` int(3) NOT NULL DEFAULT '0',
  `price` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`)
);
</code>```

I'm using virtualFields for the Day and Period models:

```<code>// day.php
var $virtualFields = array(
    'name' => "CONCAT(Day.low,IF(Day.high IS NULL, '+', ' to '),IF(Day.high IS NULL, '', Day.high))"
);

// period.php  dates are localized using setLocale and strftime in afterFind()
var $virtualFields = array(
    'name' => "CONCAT(Period.start,'|', Period.finish)"
);
function afterFind($results) {
    foreach ($results as $key => $val) {
        if (isset($val['Period']['name'])) {
            $dates = explode('|',$val['Period']['name']);
            $results[$key]['Period']['name'] = strftime('%d %b %Y',strtotime($dates[0])). ' – ' . strftime('%d %b %Y',strtotime($dates[1]));
        }
    }
    return $results;
}
</code>```

In the Price model if I do:

```<code>function price($id) {
    $this->set('prices', $this->find('all',array('conditions' => ('Price.vehicle_id' => $id))));
}
</code>```

This is shown in the view

```Day            Period                      Price
5 - 20          01 May 2011 to 31 Aug 2011  $87.00
21 to 27        01 May 2011 to 31 Aug 2011  $66.00
28+             01 May 2011 to 31 Aug 2011  $63.00
5 - 20          01 Sep 2011 to 30 Sep 2011  $177.00
21 to 27        01 Sep 2011 to 30 Sep 2011  $165.00
28+             01 Sep 2011 to 30 Sep 2011  $155.00
5 - 20          01 Oct 2011 to 31 Oct 2011  $322.00
21 to 27        01 Oct 2011 to 31 Oct 2011  $310.00
28+             01 Oct 2011 to 31 Oct 2011  $300.00
```

How can I present the data like this?

```                           5 - 20 days     21 - 27 days    28+ days
01 May 2011 to 31 Aug 2011  $87.00      $66.00      $63.00
01 Sep 2011 to 30 Sep 2011  $177.00         $165.00         $155.00
01 Oct 2011 to 31 Oct 2011  $322.00         $310.00         $300.00
```

I have been trying to learn about pivot tables but am struggling to do this in CakePHP.  Any suggestions would be much appreciated.

答: Mark Story wrote a blog post titled "Creating easy reports with pivot tables", which will most likely help you. The essential piece is to create a separate field in the query for each column you want, then use an expression for the field with an IF to select only those rows that should be used in that column.

ContentLicense: CC BY-SA 3.0

Title: Pivot MySQL rows to columns in view

Body:
I have the following tables: days, periods, prices, brands, vehicles.

The Price model belongsTo Day and Period.

DB Schema:

CREATE TABLE `days` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `low` int(11) NOT NULL DEFAULT '0',
  `high` int(11) DEFAULT '0',
  `brand_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);
CREATE TABLE `periods` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `start` date NOT NULL DEFAULT '0000-00-00',
  `finish` date NOT NULL DEFAULT '0000-00-00',
  `brand_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);
CREATE TABLE `brands` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `brand` varchar(255) NOT NULL DEFAULT '',
  `slug` varchar(20) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
);
CREATE TABLE `vehicles` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `size_id` int(11) DEFAULT NULL,
  `brand_id` int(11) DEFAULT NULL,
  `slug` varchar(50) NOT NULL,
  `model` varchar(50) DEFAULT NULL,
  `image` varchar(50) DEFAULT NULL,
  `short_specs` text,
  `specs` text,
  `publish` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`id`)
);
CREATE TABLE `prices` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `vehicle_id` int(3) NOT NULL DEFAULT '0',
  `day_id` int(3) NOT NULL DEFAULT '0',
  `period_id` int(3) NOT NULL DEFAULT '0',
  `price` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`)
);

I'm using virtualFields for the Day and Period models:

// day.php
var $virtualFields = array(
    'name' => "CONCAT(Day.low,IF(Day.high IS NULL, '+', ' to '),IF(Day.high IS NULL, '', Day.high))"
);

// period.php  dates are localized using setLocale and strftime in afterFind()
var $virtualFields = array(
    'name' => "CONCAT(Period.start,'|', Period.finish)"
);
function afterFind($results) {
    foreach ($results as $key => $val) {
        if (isset($val['Period']['name'])) {
            $dates = explode('|',$val['Period']['name']);
            $results[$key]['Period']['name'] = strftime('%d %b %Y',strtotime($dates[0])). ' – ' . strftime('%d %b %Y',strtotime($dates[1]));
        }
    }
    return $results;
}

In the Price model if I do:

function price($id) {
    $this->set('prices', $this->find('all',array('conditions' => ('Price.vehicle_id' => $id))));
}

This is shown in the view

Day            Period                      Price
5 - 20          01 May 2011 to 31 Aug 2011  $87.00
21 to 27        01 May 2011 to 31 Aug 2011  $66.00
28+             01 May 2011 to 31 Aug 2011  $63.00
5 - 20          01 Sep 2011 to 30 Sep 2011  $177.00
21 to 27        01 Sep 2011 to 30 Sep 2011  $165.00
28+             01 Sep 2011 to 30 Sep 2011  $155.00
5 - 20          01 Oct 2011 to 31 Oct 2011  $322.00
21 to 27        01 Oct 2011 to 31 Oct 2011  $310.00
28+             01 Oct 2011 to 31 Oct 2011  $300.00

How can I present the data like this?

                           5 - 20 days     21 - 27 days    28+ days
01 May 2011 to 31 Aug 2011  $87.00      $66.00      $63.00
01 Sep 2011 to 30 Sep 2011  $177.00         $165.00         $155.00
01 Oct 2011 to 31 Oct 2011  $322.00         $310.00         $300.00

I have been trying to learn about pivot tables but am struggling to do this in CakePHP.  Any suggestions would be much appreciated.


问:
Format of the initialization string does not conform to specification starting at index 0
I have an ASP.NET application which runs fine on my local development machine.

When I run this application online, it shows the following error:

Format of the initialization string does not conform to specification starting at index 0

Why is this appearing, and how can I fix it?

答: In my case the problem was that on the server, a different appsettings.json file was used by the application.</p>


问:
Failed to connect to localhost/127.0.0.1:44326
I'm facing this error when I've to fetch data from web API from localhost, android app is running in emulator.

Failed to connect to localhost/127.0.0.1:44326

No response is getting from the localhost server in xamarin app whereas I'm able to fetch result in postman and in browser as well. I put URL ("https://localhost:44326/api/passportStatus") in xamarin MainPage.xaml.cs. are these info sufficient to know what I want actually?

This is my mainpage.xaml.cs

```<code>public partial class MainPage : ContentPage
    {`public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            empDetails();
        }

        private async void empDetails()
        {
            var result = "";
        HttpClient client = new HttpClient();
        var API_URL = "https://localhost:44326/api/passportStatus";
        client.BaseAddress = new Uri(API_URL);
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage respons = await client.GetAsync(API_URL);
        result = await respons.Content.ReadAsStringAsync();
        var PassportDetails = JsonConvert.DeserializeObject<List<detail>>(result);
        EmpDeatils.ItemsSource = PassportDetails;
        }
    }
</code>```

答:
Update your code like below

```<code>public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            empDetails();
        }

        private async void empDetails()
        {
            var result = "";
        HttpClient client = new HttpClient();
        var API_URL = "https://192.168.0.47:44326/api/";//Updated
        client.BaseAddress = new Uri(API_URL);
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage respons = await client.GetAsync("passportStatus");//Updated
        result = await respons.Content.ReadAsStringAsync();
        var PassportDetails = JsonConvert.DeserializeObject<List<detail>>(result);
        EmpDeatils.ItemsSource = PassportDetails;
        }
    }
</code>```

Hope this will resolve ur issue

Body:
I'm facing this error when I've to fetch data from web API from localhost, android app is running in emulator.

Failed to connect to localhost/127.0.0.1:44326

No response is getting from the localhost server in xamarin app whereas I'm able to fetch result in postman and in browser as well. I put URL ("https://localhost:44326/api/passportStatus") in xamarin MainPage.xaml.cs. are these info sufficient to know what I want actually?

This is my mainpage.xaml.cs

public partial class MainPage : ContentPage
    {`public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            empDetails();
        }

        private async void empDetails()
        {
            var result = "";
        HttpClient client = new HttpClient();
        var API_URL = "https://localhost:44326/api/passportStatus";
        client.BaseAddress = new Uri(API_URL);
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage respons = await client.GetAsync(API_URL);
        result = await respons.Content.ReadAsStringAsync();
        var PassportDetails = JsonConvert.DeserializeObject<List<detail>>(result);
        EmpDeatils.ItemsSource = PassportDetails;
        }
    }

Body:
Update your code like below

public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            empDetails();
        }

        private async void empDetails()
        {
            var result = "";
        HttpClient client = new HttpClient();
        var API_URL = "https://192.168.0.47:44326/api/";//Updated
        client.BaseAddress = new Uri(API_URL);
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage respons = await client.GetAsync("passportStatus");//Updated
        result = await respons.Content.ReadAsStringAsync();
        var PassportDetails = JsonConvert.DeserializeObject<List<detail>>(result);
        EmpDeatils.ItemsSource = PassportDetails;
        }
    }

Hope this will resolve ur issue


问:
How to return observable from subscribe
I'm trying to return an observable when I get a certain value in a subscriber, but I fail miserably.

This is the code:

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
    // get route to be activated
    this.routeToActivate = route.routeConfig.path;

    // get user access levels
    return this._firebase.isUserAdmin          <-- returns Subscription, not Observable
        .map(user => user.access_level)
        .subscribe( access => {
           // I need to return an observable here
        });
}
</code>```

There are not many resources on observables in angular 2, so I don't know where to start. Can anyone help with this please?

UPDATE -> Working Version

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
            // get route to be activated
            this.routeToActivate = route.routeConfig.path;

            // get user access levels
            return this._firebase.isUserAdmin
                .map(user => {
                    let accessLevel = user.access_level;

                    if (accessLevel === 'admin' ) {
                        return true;
                    }

                }).first();
        }
</code>```

答:
Couldn't we just use pipe with map from import { map } from 'rxjs/operators';?

```<code>import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SearchHostService {
  constructor(private readonly http: HttpClient) {}

  searchForHosts(searchString: string): Observable<Employee[]> {
    return this.http
      .get<Employee[]>('./assets/host-users.json')
      .pipe(
        map(employees =>
          employees.filter(({ displayName }) =>
            displayName.toLowerCase().startsWith(searchString),
          ),
        ),
      );
  }
}
</code>```

Title: How to return observable from subscribe

Body:
I'm trying to return an observable when I get a certain value in a subscriber, but I fail miserably.

This is the code:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
    // get route to be activated
    this.routeToActivate = route.routeConfig.path;

    // get user access levels
    return this._firebase.isUserAdmin          <-- returns Subscription, not Observable
        .map(user => user.access_level)
        .subscribe( access => {
           // I need to return an observable here
        });
}

There are not many resources on observables in angular 2, so I don't know where to start. Can anyone help with this please?

UPDATE -> Working Version

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
            // get route to be activated
            this.routeToActivate = route.routeConfig.path;

            // get user access levels
            return this._firebase.isUserAdmin
                .map(user => {
                    let accessLevel = user.access_level;

                    if (accessLevel === 'admin' ) {
                        return true;
                    }

                }).first();
        }

Body:
Couldn't we just use pipe with map from import { map } from 'rxjs/operators';?

import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SearchHostService {
  constructor(private readonly http: HttpClient) {}

  searchForHosts(searchString: string): Observable<Employee[]> {
    return this.http
      .get<Employee[]>('./assets/host-users.json')
      .pipe(
        map(employees =>
          employees.filter(({ displayName }) =>
            displayName.toLowerCase().startsWith(searchString),
          ),
        ),
      );
  }
}


问:
How can I check if a file contains only integers?
In my project I need to upload a file and check that inside it there is an integer (positive or negative) for each line so that it can be represented within a vector.

Since I am working on QT and C++ I have considered two proposals, but both when I insert a number in the file for example "35.2" with a comma and I press the start button the program crashes.

Is there a better solution to mitigate the problem? I am attaching one of the solution that I was evaluating.

```<code>QFile file_in(file_name);

file_in.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream in(&file_in);
int elem;
int pos = 0;
QString s;
QIntValidator valid(-999, 999, this);

while(!in.atEnd())
{
    in >> elem;
    s = QString::number(elem);
    if(!valid.validate(s,pos))
    {
        v.clear();
        QMessageBox msg(this);
        msg.setText("Input non valido");
        msg.exec();
        return;
    }
    else
    {
        v.push_back(elem);
    }
}
</code>```

答:
A simpler solution would be to read the file line by line and check if the current line is convertible to an integer.

Qt already provides a lot of convenience methods. For instance, you would be interested by QByteArray::toInt().

Hence a solution could be:

```<code>bool validate(const QString & file_name)
{
    QFile in_f(file_name);
    if(!in_f.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    bool is_valid = true;
    while(is_valid && !in_f.atEnd())
    {
        QByteArray line = in_f.readLine();
        line.toInt(&is_valid); // is_valid is set to false if the conversion failed
    }
    return is_valid;
}
</code>```

This way there is no crash. If each line contains an integer, it will return true, otherwise, if at least one line contains something else (string, double, ...), it will return false.

As implemented here, if the file is empty, the function will return true. Of course you can add a check for this case if you want to return false instead.

Body:
In my project I need to upload a file and check that inside it there is an integer (positive or negative) for each line so that it can be represented within a vector.

Since I am working on QT and C++ I have considered two proposals, but both when I insert a number in the file for example "35.2" with a comma and I press the start button the program crashes.

Is there a better solution to mitigate the problem? I am attaching one of the solution that I was evaluating.

QFile file_in(file_name);

file_in.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream in(&file_in);
int elem;
int pos = 0;
QString s;
QIntValidator valid(-999, 999, this);

while(!in.atEnd())
{
    in >> elem;
    s = QString::number(elem);
    if(!valid.validate(s,pos))
    {
        v.clear();
        QMessageBox msg(this);
        msg.setText("Input non valido");
        msg.exec();
        return;
    }
    else
    {
        v.push_back(elem);
    }
}

Body:
A simpler solution would be to read the file line by line and check if the current line is convertible to an integer.

Qt already provides a lot of convenience methods. For instance, you would be interested by QByteArray::toInt().

Hence a solution could be:

bool validate(const QString & file_name)
{
    QFile in_f(file_name);
    if(!in_f.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    bool is_valid = true;
    while(is_valid && !in_f.atEnd())
    {
        QByteArray line = in_f.readLine();
        line.toInt(&is_valid); // is_valid is set to false if the conversion failed
    }
    return is_valid;
}

This way there is no crash. If each line contains an integer, it will return true, otherwise, if at least one line contains something else (string, double, ...), it will return false.

As implemented here, if the file is empty, the function will return true. Of course you can add a check for this case if you want to return false instead.


问:
I have created a Fragment but don't know what to put inside
I have realised an NFC (to scan tags) application, but now I have to create fragment who works with my MainActivity because I'd like to implement ViewPager in future.

Problem is that i'm really beginner and my code became too big to know what I have to put in Activity and what I have to put in Fragment

One week that I'm trying to understand...

Here is my code

```<code>public class MainActivity extends FragmentActivity {
    ObjectAnimator anim;
    ObjectAnimator anim2;
    private int display, result, detect = 0;
    private NfcAdapter nfcAdapter;
    private ImageButton nfcButton;
    private PendingIntent pendingIntent;
    private ImageButton qrButton;
    private TextView text;
    private ImageButton webButton;
    String link = null;
    public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        slidr = Slidr.attach(this);
        setDetect(1);
        setContentView((int) R.layout.activity_main);
        this.text = (TextView) findViewById(R.id.text);
        this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        IntentIntegrator integrator = new IntentIntegrator(this);
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setDisplay(1);
                manageBlinkEffect();
            }
        });
        this.pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {                                   // RESULTAT DU SCAN QR CODE
        if (requestCode != CUSTOMIZED_REQUEST_CODE && requestCode != IntentIntegrator.REQUEST_CODE) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        switch (requestCode) {
            case CUSTOMIZED_REQUEST_CODE: {
                Toast.makeText(this, "REQUEST_CODE = " + requestCode, Toast.LENGTH_LONG).show();
                break;
            }
            default:
                break;
        }

        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

        if (result.getContents() != null) {
            Log.d("MainActivity", "Scanned");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Résultat du scan :");
            if (URLUtil.isValidUrl(result.getContents())) {                                                                      // si url...
                builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
                builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
            } else {                                                                                // si plain text...
                builder.setNeutralButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
            }
            builder.setMessage(result.getContents().toString());
            builder.create().show();
        }
    }

    public void manageBlinkEffect() {                                                                           // ANIMATION DU LOGO SENZU SUITE A UN CLIC
        anim.setDuration(1000);
        anim.setRepeatMode(ValueAnimator.REVERSE);
        anim.setRepeatCount(9);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationCancel(animation);
                if (getRes() != 1){
                    Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
                    Toast.makeText(getApplicationContext(), "Aucun badge n'a été détécté !", Toast.LENGTH_SHORT).show();
                    nfcButton.startAnimation(shake);
                }
            }
        });
        anim2.setDuration(1000);
        anim2.setRepeatMode(ValueAnimator.REVERSE);
        anim2.setRepeatCount(9);
        anim2.start();
    }

    public void onResume() {
        super.onResume();

        Intent intent = getIntent(); // Recuperer l'intent actuel
        NdefMessage[] msgs;
        if (getDetect() == 1 && (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))) { // si l'application a ete lancee via une detection NFC du device  (ACTION_NDEF_DISCOVERED, voir AndroidManifest)
            Parcelable[] rawMessages =
                    intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMessages != null) { // si NDEF dans le scan
                setDisplay(1);
                resolveIntent(intent); // parser le scan NFC
            }  else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
                setDetect(0);
                getResult(msgs);
            }
        }
        NfcAdapter nfcAdapter2 = this.nfcAdapter;
        if (nfcAdapter2 != null) {
            if (!nfcAdapter2.isEnabled()) {
                showWirelessSettings();
            }
            this.nfcAdapter.enableForegroundDispatch(this, this.pendingIntent, (IntentFilter[]) null, (String[][]) null);
        }
    }

    private void showWirelessSettings() {
        Toast.makeText(this, "Veuillez activer le service NFC", Toast.LENGTH_SHORT).show();
        startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
    }

    public void onPause() {
        setDetect(0);
        super.onPause();
    }

    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getDetect() != 1) {
            resolveIntent(intent);
        }
    }

    private void resolveIntent(Intent intent) {                                                                 // DETECTION NFC ET PARSING NDEF
        NdefMessage[] msgs;
        String action = intent.getAction();
        Log.d("Infos", getIntent().toString());
        Log.d("Infos", "display = " + display);
        if (getDisplay() != 1) {
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            nfcButton.startAnimation(shake);
            Toast.makeText(this, "Veuillez lancer un scan", Toast.LENGTH_LONG).show();
            return;
        }
        else if ("android.nfc.action.TAG_DISCOVERED".equals(action) || "android.nfc.action.TECH_DISCOVERED".equals(action) || "android.nfc.action.NDEF_DISCOVERED".equals(action)) {
            setRes(1);
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
            if (getDisplay() == 1) {
                getResult(msgs);
            }
        }
    }

    private void getResult(NdefMessage[] msgs) {                                                            // MODAL AVEC RESULTAT DU SCAN NFC
        if (msgs != null && msgs.length != 0) {
            final StringBuilder tmp_builder = new StringBuilder();
            List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
            int size = records.size();
            for (int i = 0; i < size; i++) {
                tmp_builder.append(records.get(i).str());
                tmp_builder.append("\n");
            }
            System.out.println(tmp_builder.toString());
            this.anim.cancel();
            this.anim2.cancel();
            setDisplay(0);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Resultat du scan :");
            builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                 /*  Intent i = new Intent(MainActivity.this, RightActivity.class);
                    link = tmp_builder.toString();
                    i.putExtra("url", link);
                    startActivity(i);*/
                }
            });
            builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("Texte copié", link);
                    clipboard.setPrimaryClip(clip);
                }
            });
            builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {}
            });
            builder.setMessage(tmp_builder.toString());
            builder.create().show();
        }
    }
</code>```

I don't know if I have to transfert my onResume, onPause etc. in my Fragment

Really lost...

答:
I think you need to make the changes in stages

I would understand how viewpager and fragments work first see https://abhiandroid.com/materialdesign/viewpager for a tutorial

The next stage is to create your first fragment with the nfcButton on it BUT not try to link it up yet with the NFC stuff.

This is because the starting point of handling NFC has to be in the Activity as you are overriding Activity methods to do this.

This is basically putting the code below in to the onViewCreated method of your fragment and moving the xml related to the button to the fragment's xml

this.text = (TextView) findViewById(R.id.text);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // setDisplay should not be used at this stage
                // setDisplay(1);
                manageBlinkEffect();
            }
        });
```

<p>Also move the method <code>manageBlinkEffect()</code> to the fragment.</p>

<p>You should comment out in <code>getResult</code> as well at the moment</p>

<pre class="lang-java prettyprint-override"><code>this.anim.cancel();
this.anim2.cancel();
</code>```

Then setup your viewpager in main xml file

The reason for commenting out these lines at the moment is that these need Activity to Fragment communication, you should understand https://developer.android.com/training/basics/fragments/communicating

Next stage is connecting you button back to the setDetect Flag (replacing the commented out setDetect() line)

i.e Your Fragment with the nfcButton it in has to tell the MainActivity to start processing any NFC data it gets sent

Then the MainActivity in getResult needs to tell the Fragment with the nfc to stop animating it's Button IF the Fragment with the button in is being displayed and and that Fragment is up and running. Again this is fragment communication from Activity to Fragment this time.

Body:
I have realised an NFC (to scan tags) application, but now I have to create fragment who works with my MainActivity because I'd like to implement ViewPager in future.

Problem is that i'm really beginner and my code became too big to know what I have to put in Activity and what I have to put in Fragment

One week that I'm trying to understand...

Here is my code

public class MainActivity extends FragmentActivity {
    ObjectAnimator anim;
    ObjectAnimator anim2;
    private int display, result, detect = 0;
    private NfcAdapter nfcAdapter;
    private ImageButton nfcButton;
    private PendingIntent pendingIntent;
    private ImageButton qrButton;
    private TextView text;
    private ImageButton webButton;
    String link = null;
    public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        slidr = Slidr.attach(this);
        setDetect(1);
        setContentView((int) R.layout.activity_main);
        this.text = (TextView) findViewById(R.id.text);
        this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        IntentIntegrator integrator = new IntentIntegrator(this);
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setDisplay(1);
                manageBlinkEffect();
            }
        });
        this.pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {                                   // RESULTAT DU SCAN QR CODE
        if (requestCode != CUSTOMIZED_REQUEST_CODE && requestCode != IntentIntegrator.REQUEST_CODE) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        switch (requestCode) {
            case CUSTOMIZED_REQUEST_CODE: {
                Toast.makeText(this, "REQUEST_CODE = " + requestCode, Toast.LENGTH_LONG).show();
                break;
            }
            default:
                break;
        }

        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

        if (result.getContents() != null) {
            Log.d("MainActivity", "Scanned");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Résultat du scan :");
            if (URLUtil.isValidUrl(result.getContents())) {                                                                      // si url...
                builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
                builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
            } else {                                                                                // si plain text...
                builder.setNeutralButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
            }
            builder.setMessage(result.getContents().toString());
            builder.create().show();
        }
    }

    public void manageBlinkEffect() {                                                                           // ANIMATION DU LOGO SENZU SUITE A UN CLIC
        anim.setDuration(1000);
        anim.setRepeatMode(ValueAnimator.REVERSE);
        anim.setRepeatCount(9);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationCancel(animation);
                if (getRes() != 1){
                    Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
                    Toast.makeText(getApplicationContext(), "Aucun badge n'a été détécté !", Toast.LENGTH_SHORT).show();
                    nfcButton.startAnimation(shake);
                }
            }
        });
        anim2.setDuration(1000);
        anim2.setRepeatMode(ValueAnimator.REVERSE);
        anim2.setRepeatCount(9);
        anim2.start();
    }

    public void onResume() {
        super.onResume();

        Intent intent = getIntent(); // Recuperer l'intent actuel
        NdefMessage[] msgs;
        if (getDetect() == 1 && (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))) { // si l'application a ete lancee via une detection NFC du device  (ACTION_NDEF_DISCOVERED, voir AndroidManifest)
            Parcelable[] rawMessages =
                    intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMessages != null) { // si NDEF dans le scan
                setDisplay(1);
                resolveIntent(intent); // parser le scan NFC
            }  else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
                setDetect(0);
                getResult(msgs);
            }
        }
        NfcAdapter nfcAdapter2 = this.nfcAdapter;
        if (nfcAdapter2 != null) {
            if (!nfcAdapter2.isEnabled()) {
                showWirelessSettings();
            }
            this.nfcAdapter.enableForegroundDispatch(this, this.pendingIntent, (IntentFilter[]) null, (String[][]) null);
        }
    }

    private void showWirelessSettings() {
        Toast.makeText(this, "Veuillez activer le service NFC", Toast.LENGTH_SHORT).show();
        startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
    }

    public void onPause() {
        setDetect(0);
        super.onPause();
    }

    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getDetect() != 1) {
            resolveIntent(intent);
        }
    }

    private void resolveIntent(Intent intent) {                                                                 // DETECTION NFC ET PARSING NDEF
        NdefMessage[] msgs;
        String action = intent.getAction();
        Log.d("Infos", getIntent().toString());
        Log.d("Infos", "display = " + display);
        if (getDisplay() != 1) {
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            nfcButton.startAnimation(shake);
            Toast.makeText(this, "Veuillez lancer un scan", Toast.LENGTH_LONG).show();
            return;
        }
        else if ("android.nfc.action.TAG_DISCOVERED".equals(action) || "android.nfc.action.TECH_DISCOVERED".equals(action) || "android.nfc.action.NDEF_DISCOVERED".equals(action)) {
            setRes(1);
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
            if (getDisplay() == 1) {
                getResult(msgs);
            }
        }
    }

    private void getResult(NdefMessage[] msgs) {                                                            // MODAL AVEC RESULTAT DU SCAN NFC
        if (msgs != null && msgs.length != 0) {
            final StringBuilder tmp_builder = new StringBuilder();
            List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
            int size = records.size();
            for (int i = 0; i < size; i++) {
                tmp_builder.append(records.get(i).str());
                tmp_builder.append("\n");
            }
            System.out.println(tmp_builder.toString());
            this.anim.cancel();
            this.anim2.cancel();
            setDisplay(0);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Resultat du scan :");
            builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                 /*  Intent i = new Intent(MainActivity.this, RightActivity.class);
                    link = tmp_builder.toString();
                    i.putExtra("url", link);
                    startActivity(i);*/
                }
            });
            builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("Texte copié", link);
                    clipboard.setPrimaryClip(clip);
                }
            });
            builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {}
            });
            builder.setMessage(tmp_builder.toString());
            builder.create().show();
        }
    }

I don't know if I have to transfert my onResume, onPause etc. in my Fragment

Really lost...

Body:
I think you need to make the changes in stages

I would understand how viewpager and fragments work first see https://abhiandroid.com/materialdesign/viewpager for a tutorial

The next stage is to create your first fragment with the nfcButton on it BUT not try to link it up yet with the NFC stuff.

This is because the starting point of handling NFC has to be in the Activity as you are overriding Activity methods to do this.

This is basically putting the code below in to the onViewCreated method of your fragment and moving the xml related to the button to the fragment's xml

this.text = (TextView) findViewById(R.id.text);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // setDisplay should not be used at this stage
                // setDisplay(1);
                manageBlinkEffect();
            }
        });

Also move the method manageBlinkEffect() to the fragment.

You should comment out in getResult as well at the moment

this.anim.cancel();
this.anim2.cancel();

Then setup your viewpager in main xml file

The reason for commenting out these lines at the moment is that these need Activity to Fragment communication, you should understand https://developer.android.com/training/basics/fragments/communicating

Next stage is connecting you button back to the setDetect Flag (replacing the commented out setDetect() line)

i.e Your Fragment with the nfcButton it in has to tell the MainActivity to start processing any NFC data it gets sent

Then the MainActivity in getResult needs to tell the Fragment with the nfc to stop animating it's Button IF the Fragment with the button in is being displayed and and that Fragment is up and running. Again this is fragment communication from Activity to Fragment this time.


问:
Difference between node, peer and user in Hyperledger Fabric
I'd like to read about the difference between these terms: Node, Peer and User.

From what I understand, a node is basically a machine which inside is running the HL Fabric binaries and is communicating with other machines belonging to the same network.
A peer is the type of the node, in particular:

Orderer: the one which put the transactions in a certain order for the insert in the ledger.

Endorser: this type is the one that runs the chaincode and produces the RW sets.

Commitment: a peer that propagates valid transaction among the network.

Finally, a user is a subject that has a digital certificate and exists in some organization. More users can work on the same node / peer.

Please tell me if there is something wrong in what I wrote and, eventually, why is that wrong.

答:
Your definition of a user is correct. I think the below graphic from the Hyperledger Fabric paper should be helpful toward understanding the word 'peer'.

Node: Generic term for any type of application that is part of the Fabric network. A node in a Fabric network can be one of three things: Client, Peer or Ordering Service Node (Orderer)

Peer: Every peer maintains a copy of the ledger. The peers execute a consensus protocol to validate transactions, group them into blocks, and build a hash chain over the blocks. A peer may be an endorser for a specific chaincode, but doesn't have to be.

Endorser: Part of every peer. Runs the chaincode and produces the RW sets.

Committer: Part of every peer. Performs validation of transactions after ordering

Ledger: Part of every peer. Stores blockchain state and history.

Orderer: Separate instances responsible for reaching consensus on the order of transactions, i.e. Raft based

Client: Submits transaction proposals to peers, specifically those peers that are endorsers for the relevant chaincode

User: Has a valid user certificate issued by an MSP. Creates transactions using a client to interact with chaincode.

To gain a thorough understanding of each of these I recommend reading the full paper yourself.


答:
You could assess this by using a sliding window and looking at the standard deviation over the window. A simple threshold might suffice. For example:

k = 6  # window size
thresh = 0.5
for i in range(0, len(a) - k):
    b = np.std(a[i:i+k])
    if b < thresh:
        print(i)
        break
>>> 55
```


问:
Form an numpy array from indices and fill with zeroes
I have a nympy array a = np.array([483, 39, 18, 999, 20, 48]

I have an array of indices indices = np.array([2, 3])

I would like to have all the indices of the array and fill the rest of the indices with 0 so I get as a result :

np.array([0, 0, 18, 999, 0, 0])

Thank you for your answer.

答:
You can create a function that uses the input array and the index array to do this, as in the following:

import numpy as np

def remove_by_index(input_array, indexes):
    for i,_ in enumerate(input_array):
        if i not in indexes:
            input_array[i] = 0
    return input_array

input_array = np.array([483, 39, 18, 999, 20, 48])
indexes = np.array([2, 3])

new_out = remove_by_index(input_array, indexes)

expected_out = np.array([0, 0, 18, 999, 0, 0])

print(new_out == expected_out)  # to check if it's correct
```

<h2><strong>Edit</strong></h2>

<p>You can also use list comprehension inside the function, which would be better, as:</p>

<pre class="lang-py prettyprint-override"><code>def remove_by_index(input_array, indexes):
    return [input_array[i] if (i in indexes) else 0 for i,_ in enumerate(input_array)]
</code>```

It is not, as pointed out in comments, the most efficient way of doing it, performing iteration at Python level instead of C level, but it does work, and for casual use it will solve.

Body:
You can create a function that uses the input array and the index array to do this, as in the following:

import numpy as np

def remove_by_index(input_array, indexes):
    for i,_ in enumerate(input_array):
        if i not in indexes:
            input_array[i] = 0
    return input_array

input_array = np.array([483, 39, 18, 999, 20, 48])
indexes = np.array([2, 3])

new_out = remove_by_index(input_array, indexes)

expected_out = np.array([0, 0, 18, 999, 0, 0])

print(new_out == expected_out)  # to check if it's correct

Edit

You can also use list comprehension inside the function, which would be better, as:

def remove_by_index(input_array, indexes):
    return [input_array[i] if (i in indexes) else 0 for i,_ in enumerate(input_array)]

It is not, as pointed out in comments, the most efficient way of doing it, performing iteration at Python level instead of C level, but it does work, and for casual use it will solve.


问:
Convert java to kotlin on paste
So I checked "Don't show this dialog next time", but it turns out that it will then never convert the code again.

Where do I remove the checkmark again so I can get back to converting the java code to kotlin when pasted?

Thanks in advance.

https://developer.android.com/kotlin/get-started.html#convert-to-kotlin-code

答:
In my case I needed to have the "Do you want to convert ..." dialog again, despite the option to convert checked.

Preferences -> Editor -> General -> Smart Keys -> Scroll to the end -> Convert posted Java code to Kotlin (checked)

Preferences -> Editor -> General -> Smart Keys -> Scroll to the end -> Don't show Java to Kotlin conversion dialog on paste (unchecked)

File -> Invalidate Caches / Restart

Title: Convert java to kotlin on paste


问:
Difference in various Selenium Waits
What is the difference between Implicitwait,Explicitwait, Fluentwait and Thread.sleep(), i'm always confused about these waits, if any body can explain i would really appreciate it.

Thanks in advance.

答:
Implicit Wait

The implicit wait will tell to the web driver to wait for certain amount of time before it throws a "No Such Element Exception". The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception. it can be declared globally, so that any code under that declaration wait for that specific amount time before it throws to an exception.
Eg:

```<code>driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
</code>```

Explicit Wait

The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an "ElementNotVisibleException" exception.Once we declare explicit wait we have to use "ExpectedCondtions" or we can configure how frequently we want to check the condition using Fluent Wait. Already there are many expected conditions exist in addition to that, we can also create custom expected conditions

Thread.sleep()

These days while implementing we are using Thread.Sleep() generally it is not recommended to use.These are java wait, it will tell the thread to wait for the specific amount of time(the execution will be stopped until the wait time completes)

Hope it will clear your doubts, For more details refer https://www.guru99.com/implicit-explicit-waits-selenium.html

Title: Difference in various Selenium Waits

Body:
Implicit Wait

The implicit wait will tell to the web driver to wait for certain amount of time before it throws a "No Such Element Exception". The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception. it can be declared globally, so that any code under that declaration wait for that specific amount time before it throws to an exception.
Eg:

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Explicit Wait

The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an "ElementNotVisibleException" exception.Once we declare explicit wait we have to use "ExpectedCondtions" or we can configure how frequently we want to check the condition using Fluent Wait. Already there are many expected conditions exist in addition to that, we can also create custom expected conditions

Thread.sleep()

These days while implementing we are using Thread.Sleep() generally it is not recommended to use.These are java wait, it will tell the thread to wait for the specific amount of time(the execution will be stopped until the wait time completes)

Hope it will clear your doubts, For more details refer https://www.guru99.com/implicit-explicit-waits-selenium.html


问:
Run server.product and open url [http: // localhost: 8080 / webui /] web error
I used the source code from iDempiere.

Running mvn validate is successful.

Run mvn verify successfully.

Import source into eclipse is successfully.

Run file install.app is successfully.

When run file server.app it will be fail.

Run url http://localhost:8080/webui/ failed.

Please guide how to fix the problem.

答:
It sounds like maybe you installed iDempiere on top of a JPiere database?

JPiere is a japanese distro of iDempiere, your error message is pointing to the error that jpiere theme is not installed.

For iDempiere vanilla is better to follow fresher instructions from here:
https://wiki.idempiere.org/en/Installing_iDempiere

I can't assess about the accuracy of the link you provided as is in japanese - but I see it mentions Eclipse201909.  For running fine the latest version you need Eclipse201912 instead.


答:
Please read the doc about validate method here:

https://doc.qt.io/archives/qt-4.8/qintvalidator.html#validate

you are using a criteria for valid inputs as valid(-999, 999, this);

so if the list in the file is holding a row with 1000, using a toInt method will return you a false positive result!

the result is not just True or False like you may think...

you actually get:

Title: How can I check if a file contains only integers?


答:
How about this?

```<code>('20/02/2020').split('/').reverse().join('')
</code>```

This SHOULD WORK based on the information you have given. Unless your datepicker returns the value as something else or in some other format. For that you will need to intercept the form submit by your own click handler and check the value.

Title: Reformat Date Before Form Submitted

Body:
I have a form with a date field and a calendar picker. When I use this I have it entering the date as dd/mm/yyyy. This works.

I want to store the date as yyyymmdd though. Is there a way using javascript to reformat the date? For example, I click submit, it reformats the date and then does the submit and writes the reformatted date to the database?

Maybe there is a better approach? e.g. using a hidden input field that has the correctly formatted version of the date somehow?

Body:
How about this?

('20/02/2020').split('/').reverse().join('')

This SHOULD WORK based on the information you have given. Unless your datepicker returns the value as something else or in some other format. For that you will need to intercept the form submit by your own click handler and check the value.


问:
Remove or Filter values out of an Array using for loop or a function
I have an Array and i would like to  Filter or delete the following urls from my Array every time they appear:

```<code>"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"
</code>```

My Array

```<code>Array= [
        "https://basueUrl.com/Patient"
        "https://basueUrl.com/Organization"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/Practitioner"
        "https://basueUrl.com/Encounter"
        "https://basueUrl.com/Condition"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/ExplanationOfBenefit"
        ]
</code>```

First Solution I have tried for loop but did not work?

```<code>   for( var i = 0; i < Array.length; i++){
   if ( Array[i] === "https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim") {
    Array.splice(i, 1);
    i--;
   }
}
console.log(Array);

</code>```

Second Solution I tried making a remove method did not work either.

```<code>function arrayRemove(Array, value) {

   return Array.filter(function(ele){
       return ele != value;
   });
}
var result = arrayRemove(Array,"https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");

</code>```

Any suggestion please?

答:
```<code>Array.filter(x => x !== "https://basueUrl.com/Claim" && x !== "https://basueUrl.com/ExplanationOfBenefit")
</code>```

Body:
I have an Array and i would like to  Filter or delete the following urls from my Array every time they appear:

"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"

My Array

Array= [
        "https://basueUrl.com/Patient"
        "https://basueUrl.com/Organization"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/Practitioner"
        "https://basueUrl.com/Encounter"
        "https://basueUrl.com/Condition"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/ExplanationOfBenefit"
        ]

First Solution I have tried for loop but did not work?

   for( var i = 0; i < Array.length; i++){
   if ( Array[i] === "https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim") {
    Array.splice(i, 1);
    i--;
   }
}
console.log(Array);

Second Solution I tried making a remove method did not work either.

function arrayRemove(Array, value) {

   return Array.filter(function(ele){
       return ele != value;
   });
}
var result = arrayRemove(Array,"https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");

Any suggestion please?


问:
Trigger change event <select> using jquery
is there anyway i could trigger a change event on select box on page load and select a particular option.

Also the function executed by adding the trigger after binding the function to the event.

I was trying to output something like this

```<code><select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>

$(function(){
    $('.check').trigger('change'); //This event will fire the change event.
    $('.check').change(function(){
      var data= $(this).val();
      alert(data);
    });
});
</code>```

http://jsfiddle.net/v7QWd/1/

答:
You can try below code to solve your problem.

By default, first option select:

```<code>jQuery('.select').find('option')[0].selected=true;
</code>```

Body:
is there anyway i could trigger a change event on select box on page load and select a particular option.

Also the function executed by adding the trigger after binding the function to the event.

I was trying to output something like this

<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>

$(function(){
    $('.check').trigger('change'); //This event will fire the change event.
    $('.check').change(function(){
      var data= $(this).val();
      alert(data);
    });
});

http://jsfiddle.net/v7QWd/1/

Body:
You can try below code to solve your problem.

By default, first option select:

jQuery('.select').find('option')[0].selected=true;


问:
DRF: Customising Exception Messages from the API
I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail.

For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns:

```<code>{
    "detail": "Authentication credentials were not provided."
}
</code>```

Which comes from line 171 from the rest_framework.exceptions: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the

```<code>{
    "success": false,
    "message": "Authentication credentials were not provided.",
    "data": null
}
</code>```

So, I assume I now need to begin customising my own exceptions.

How best should I go about doing this?

Perhaps it has some tie in with default_error_messages = {} inside the serializer ...

答:
There is a decorator solution that creates custom Response on each type of your exceptions:

# project/api/exceptions.py
from functools import wraps

from rest_framework import status

def handle_exceptions(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except AuthCredentialsError as exc:
            return Response(
                {"message": exc.message},
                status=status.HTTP_405_METHOD_NOT_ALLOWED,
            )
    return wrapper

# project/api/your_code.py
from project.api.exceptions import handle_exceptions

class SomeViewSet():

    @handle_exceptions
    def create(self, request, *args, **kwargs):
        raise AuthCredentialsError("Authentication credentials were not provided")
```

Body:
I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail.

For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns:

{
    "detail": "Authentication credentials were not provided."
}

Which comes from line 171 from the rest_framework.exceptions: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the

{
    "success": false,
    "message": "Authentication credentials were not provided.",
    "data": null
}

So, I assume I now need to begin customising my own exceptions.

How best should I go about doing this?

Perhaps it has some tie in with default_error_messages = {} inside the serializer ...


答:
Idea is replace 0 to missing values, forward filling them, convert all another values to NaNs, compare greater like 1 and count Trues by sum to Series converted to one row DataFrame with transpose:

```<code>m = df1.eq(0)

df2 = (df1.mask(m)
          .ffill()
          .where(m)
          .gt(1)
          .sum()
          .add_suffix('_count')
          .to_frame()
          .T
          )
print (df2)
   x1_count  X2_count  X3_count
0         6         6         2
</code>```

Title: how to count rows when value change from value greater than threshold to 0

Body:
I have three columns in dataframe , X1  X2  X3 , i want to count rows when value change from value greater than 1 to 0 .  if before 0 value less than 1 dont need to count.

input df:

df1=pd.DataFrame({'x1':[3,4,7,0,0,0,0,20,15,16,0,0,70],
             'X2':[3,4,7,0,0,0,0,20,15,16,0,0,70],
             'X3':[6,3,0.5,0,0,0,0,20,15,16,0,0,70]})

print(df1)

    x1  X2    X3
0    3   3   6.0
1    4   4   3.0
2    7   7   0.5
3    0   0   0.0
4    0   0   0.0
5    0   0   0.0
6    0   0   0.0
7   20  20  20.0
8   15  15  15.0
9   16  16  16.0
10   0   0   0.0
11   0   0   0.0
12  70  70  70.0

desired_output

   x1_count  X2_count  X3_count
0         6         6         2

Body:
Idea is replace 0 to missing values, forward filling them, convert all another values to NaNs, compare greater like 1 and count Trues by sum to Series converted to one row DataFrame with transpose:

m = df1.eq(0)

df2 = (df1.mask(m)
          .ffill()
          .where(m)
          .gt(1)
          .sum()
          .add_suffix('_count')
          .to_frame()
          .T
          )
print (df2)
   x1_count  X2_count  X3_count
0         6         6         2


问:
How do i add values to a string array from a class?
I am trying to create a simple object-oriented program for a fictional movie theatre.
Therefore I am making a kind of list with all the movies. My issue is that I can not add genres to my genre array in the child classes to the Movies class.

Here is what I have made so far.

```<code>using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BentesBio
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie[] moviesArray = new Movie[6];

            moviesArray[0] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Genre = { "", "" }, Cast = {} };
            moviesArray[1] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[2] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[3] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[4] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Theme = { "", "" } };
            moviesArray[5] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };

            Console.ReadKey();
        }
    }

    class Movie
    {
        public string Director { get; set; }
        public string Country { get; set; }
        public double Budget { get; set; }
        public string BudgetCurrency { get; set; }
        public double BudgetDKK { get; set; }
        public int Year { get; set; }
        public string Score { get; set; }
        public int Length { get; set; }
    }

    class FeatureFilm : Movie
    {
        public string[] Genre { get; set; }
        public string[] Cast { get; set; }
    }

    class Documentary : Movie
    {
        public string[] Theme { get; set; }
    }
}

</code>```

Any suggestions would be much appreciated.

答:
Replace -

```<code>Genre = { "", "" }
</code>```

with -

```<code>Genre = new string[] { "", "" }
</code>```

And same goes for assignment of Theme

And yes as per other answers you should use List<T> that'll give you flexibility to add random number of movies instead of a pre declared fixed count.

Body:
I am trying to create a simple object-oriented program for a fictional movie theatre.
Therefore I am making a kind of list with all the movies. My issue is that I can not add genres to my genre array in the child classes to the Movies class.

Here is what I have made so far.

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BentesBio
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie[] moviesArray = new Movie[6];

            moviesArray[0] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Genre = { "", "" }, Cast = {} };
            moviesArray[1] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[2] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[3] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[4] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Theme = { "", "" } };
            moviesArray[5] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };

            Console.ReadKey();
        }
    }

    class Movie
    {
        public string Director { get; set; }
        public string Country { get; set; }
        public double Budget { get; set; }
        public string BudgetCurrency { get; set; }
        public double BudgetDKK { get; set; }
        public int Year { get; set; }
        public string Score { get; set; }
        public int Length { get; set; }
    }

    class FeatureFilm : Movie
    {
        public string[] Genre { get; set; }
        public string[] Cast { get; set; }
    }

    class Documentary : Movie
    {
        public string[] Theme { get; set; }
    }
}

Any suggestions would be much appreciated.

Body:
Replace -

Genre = { "", "" }

with -

Genre = new string[] { "", "" }

And same goes for assignment of Theme

And yes as per other answers you should use List<T> that'll give you flexibility to add random number of movies instead of a pre declared fixed count.


问:
How to check if string value is in array
I am stuck on a small problem, but been lack of logic so need your help.

I have an if statement:

```<code>    func showButton() {
        if viewModel.model.id == Constants.Identifiers.showId[<any>] {
            //do this. Like show the button
        } else {
            //do that. Like hide the button
        }
    }
</code>```

So the problem is that I want to check if viewmodel.model.id has any of the values in Constants.Identifiers.showId[]
model.id is a string, and Identifiers.showId[] is array of strings..

I know this is an easy, but... Thanks for the help!

答:
You may use array.contains(_:) method. Documentation Link

```<code>func showButton() {
    if Constants.Identifiers.showId.contains(viewModel.model.id) {
        // do this. Like show the button
    } else {
        // do that. Like hide the button
    }
}
</code>```

Body:
I am stuck on a small problem, but been lack of logic so need your help.

I have an if statement:

    func showButton() {
        if viewModel.model.id == Constants.Identifiers.showId[<any>] {
            //do this. Like show the button
        } else {
            //do that. Like hide the button
        }
    }

So the problem is that I want to check if viewmodel.model.id has any of the values in Constants.Identifiers.showId[]
model.id is a string, and Identifiers.showId[] is array of strings..

I know this is an easy, but... Thanks for the help!

Body:
You may use array.contains(_:) method. Documentation Link

func showButton() {
    if Constants.Identifiers.showId.contains(viewModel.model.id) {
        // do this. Like show the button
    } else {
        // do that. Like hide the button
    }
}


答:
try it </p>

```<code>if Constants.Identifiers.showId.contains(viewModel.model.id) {

}
</code>```

Title: How to check if string value is in array

Body:
try it

if Constants.Identifiers.showId.contains(viewModel.model.id) {

}