问:
Incompatible types inferred type does not conform to equality constraint(s)
So I have a model Model.

```<code>public class Model { .... }
</code>```

This has two subclasses:

```<code>public class SubmodelA extend Model { .... }
</code>```

and

```<code>public class SubmodelB extend Model { .... }
</code>```

These three are wrapped under Data class.

```<code>public class ApiData<T extends Model> {

    public T data;

}
</code>```

My general response wrapper looks like this:

```<code>public class ApiResponse<DATA> {

    DATA data;
}
</code>```

The "dummy" api operation remains the same:

```<code>public interface Endpoints {

    Call<ApiResponse<ApiData>> getData();
}
</code>```

I have an implementation of retrofit2.Callback to handle the responses:

```<code>public class ApiCallbackProxy<T> implements retrofit2.Callback<T> {

    public interface ApiResultListener<RESPONSE_TYPE> {
        void onResult(RESPONSE_TYPE response, ApiError error);
    }

    private ApiResultListener<T> mListener;

    private ApiCallbackProxy(ApiResultListener<T> listener) {
        mListener = listener;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {

    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {

    }

    public static <T> ApiCallbackProxy<T> with(ApiResultListener<T> callback) {
        return new ApiCallbackProxy<>(callback);
    }
}
</code>```

The ApiClient

```<code>public class ApiClient {

    public Endpoints mRetrofit;

    public ApiClient() {
       Retrofit retrofit = new Retrofit.Builder().build();
       mRetrofit = retrofit.create(Endpoints.class);
    }

    public <U extends Model> void getData(ApiResultListener<ApiResponse<ApiData<U>>> callback) {
       //Compiler hits here
       mRetrofit.getData().enqueue(ApiCallbackProxy.with(callback));
    }
}
</code>```

Compiler hits at ApiCallbackProxy.with(callback) with this error:

So I want depending on where this API call is used in the app to return a different subclass of model or the model itself.

ie.

```<code>public static void main (String[] args) {
    ApiClient apiClient = new ApiClient();
    apiClient.getData(listener2);
}

public static final ApiResultListener<ApiResponse<Data<SubmodelA>>> listener = (response, error) -> {};

public static final ApiResultListener<ApiResponse<Data<Model>>> listener2 = (response, error) -> {};

public static final ApiResultListener<ApiResponse<Data<SubmodelB>>> listener3 = (response, error) -> {};
</code>```

答:
The ApiClient class has a listener that expects ApiData in the response.

The problem is, there is no U. You have an Endpoint, and the endpoint has no generic types, and it returns just ApiData with no concrete type selected for the generic.

This is a case of generics gone wrong. The usual idea would be to make Endpoint generic:

```<code>public interface Endpoints<U> {
    Call<ApiResponse<ApiData<U>>> getData();
}
</code>```

However, what does the Retrofit do? It turns HTTP API into Java interface. And looking at the most simple example at the github repo of Retrofit, it seems pretty clear to me that you are supposed to put interfaces that access some real HTTP endpoint. It is not some abstract GET.

So you'd rather give it a concrete type than make it generic. Do something like:

```<code>public interface Endpoints {
    Call<ApiResponse<ApiData<Model>>> getData();
}
</code>```

I expect Retrofit to deserialize the data in the response to your Model. So, having a concrete class rather than an unset generic type variable is crucial to the successful deserialization. However, you can only use it with listeners being either of the following:

```<code>ApiResultListener<ApiResponse<Data<Model>>>
ApiResultListener<ApiResponse<Data<? super Model>>>
</code>```

Also, in the older part of the question, the ApiResponse<Payload> part where the generic type variable looks like it was Payload class, now that is quite devious :)

Body:
So I have a model Model.

public class Model { .... }

This has two subclasses:

public class SubmodelA extend Model { .... }

and

public class SubmodelB extend Model { .... }

These three are wrapped under Data class.

public class ApiData<T extends Model> {

    public T data;

}

My general response wrapper looks like this:

public class ApiResponse<DATA> {

    DATA data;
}

The "dummy" api operation remains the same:

public interface Endpoints {

    Call<ApiResponse<ApiData>> getData();
}

I have an implementation of retrofit2.Callback to handle the responses:

public class ApiCallbackProxy<T> implements retrofit2.Callback<T> {

    public interface ApiResultListener<RESPONSE_TYPE> {
        void onResult(RESPONSE_TYPE response, ApiError error);
    }

    private ApiResultListener<T> mListener;

    private ApiCallbackProxy(ApiResultListener<T> listener) {
        mListener = listener;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {

    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {

    }

    public static <T> ApiCallbackProxy<T> with(ApiResultListener<T> callback) {
        return new ApiCallbackProxy<>(callback);
    }
}

The ApiClient

public class ApiClient {

    public Endpoints mRetrofit;

    public ApiClient() {
       Retrofit retrofit = new Retrofit.Builder().build();
       mRetrofit = retrofit.create(Endpoints.class);
    }

    public  void getData(ApiResultListener<ApiResponse<ApiData>> callback) {
       //Compiler hits here
       mRetrofit.getData().enqueue(ApiCallbackProxy.with(callback));
    }
}

Compiler hits at ApiCallbackProxy.with(callback) with this error:

So I want depending on where this API call is used in the app to return a different subclass of model or the model itself.

ie.

public static void main (String[] args) {
    ApiClient apiClient = new ApiClient();
    apiClient.getData(listener2);
}

public static final ApiResultListener<ApiResponse<Data<SubmodelA>>> listener = (response, error) -> {};

public static final ApiResultListener<ApiResponse<Data<Model>>> listener2 = (response, error) -> {};

public static final ApiResultListener<ApiResponse<Data<SubmodelB>>> listener3 = (response, error) -> {};

Body:
The ApiClient class has a listener that expects ApiData<U> in the response.

The problem is, there is no U. You have an Endpoint, and the endpoint has no generic types, and it returns just ApiData with no concrete type selected for the generic.

This is a case of generics gone wrong. The usual idea would be to make Endpoint generic:

public interface Endpoints<U> {
    Call<ApiResponse<ApiData<U>>> getData();
}

However, what does the Retrofit do? It turns HTTP API into Java interface. And looking at the most simple example at the github repo of Retrofit, it seems pretty clear to me that you are supposed to put interfaces that access some real HTTP endpoint. It is not some abstract GET.

So you'd rather give it a concrete type than make it generic. Do something like:

public interface Endpoints {
    Call<ApiResponse<ApiData<Model>>> getData();
}

I expect Retrofit to deserialize the data in the response to your Model. So, having a concrete class rather than an unset generic type variable is crucial to the successful deserialization. However, you can only use it with listeners being either of the following:

ApiResultListener<ApiResponse<Data<Model>>>
ApiResultListener<ApiResponse<Data<? super Model>>>

Also, in the older part of the question, the ApiResponse<Payload> part where the generic type variable looks like it was Payload class, now that is quite devious :)


来源: stackexchange

问:
How to scroll to bottom in a ScrollView on activity startup
I am displaying some data in a ScrollView. On activity startup (method onCreate) I fill the ScrollView with data and want to scroll to the bottom.

I tried to use getScrollView().fullScroll(ScrollView.FOCUS_DOWN). This works when I make it as an action on button click but it doesn't work in the onCreate method.

Is there any way how to scroll the ScrollView to the bottom on activity startup? That means the view is already scrolled to the bottom when first time displayed.

答:
```<code> scrollView.postDelayed(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    },1000);
</code>```

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to print a `QString` using `QDebug`?
I need to write a terminal application that lists the available bluetooth devices nearby, here is my attempt at it:

```<code>void findDevice()
{
   QBluetoothLocalDevice localDevice;
    QString localDeviceName;
    localDeviceName= localDevice.name();
    QDebug << localDeviceName;

}
</code>```

The first step I took is to print my own device name then once done that I could move on into retrieving a list of  device and print them the same way. However I constantly keep getting the error:

expected unqualified-id

```<code>`QDebug << localDeviceName;
       ^
</code>```

and dont know what seems to be the problem here.

答:
You need to :</p>

```<code>qDebug() << localDeviceName;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to write a terminal application that lists the available bluetooth devices nearby, here is my attempt at it:

void findDevice()
{
   QBluetoothLocalDevice localDevice;
    QString localDeviceName;
    localDeviceName= localDevice.name();
    QDebug << localDeviceName;

}

The first step I took is to print my own device name then once done that I could move on into retrieving a list of  device and print them the same way. However I constantly keep getting the error:

expected unqualified-id

`QDebug << localDeviceName;
       ^

and dont know what seems to be the problem here.

Body:
You need to :

qDebug() << localDeviceName;


问:
Keyboard is not being dismissed: Facebook Account Kit iOS 11
I have integrated Facebook Account Kit SDK v.4.26.0.

Following is the scenario in which I am facing difficulty:

When user clicks on sign in, Login with Phone Number controller is being presented and keyboard is appeared immediately on that screen to enter phone number. Now I tap on anywhere in the screen outside textfield & keyboard to trigger keyboard dismiss event. But from iOS 11.*, keyboard is not dismissed and if I navigate back by clicking back button, in that situation also keyboard remains open. Keyboard dismiss action works fine before iOS 11.0.

Following are the steps I have tried to resolve this problem:

 1. Using AKFViewController instance which is presented for authentication, I tried to execute view.endEditing(true) in order to dismiss keyboard from delegate methods of AKFViewControllerDelegate. (This method did not worked)

答:
This is fixed in the 4.28.0 release

https://developers.facebook.com/bugs/102125683887755/


问:
How to select a row having a column with max value with a group by
I have a table with the next columns

```<code>MSG_ID          NOT NULL NUMBER(10)
CREATION_DATE            DATE
PORT                     VARCHAR2(50)
MESSAGE                  VARCHAR2(1024)
IP_ADDRESS               VARCHAR2(50)
PARSED                   NUMBER(1)
PARSED_ON                DATE
</code>```

Where parse time is parsed_on -  creation_date.

I would like to know if it is possible in 1 single query extract for each hour the message that take longer to parse, getting the HOUR, PORT, MSG_ID MINUTES...I am blocked here

```<code>select TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID, ROUND(MAX(parsed_on -  creation_date)) * 24*60 MINUTES
        from T_INCOME_CALLS
         where TO_CHAR(CREATION_DATE, 'dd/mm/yyyy') = TO_CHAR(SYSDATE, 'dd/mm/yyyy')
        group by TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
         order by TO_CHAR(CREATION_DATE, 'HH24') ;
</code>```

答:
I have assumed that the need is for the item that takes most time, per hour, for a grouping of IP_ADDRESS and PORT, which is different to your original query. I am also assuming MSG_ID is unique.

If you want 1 and only 1 row per recorded hour then use row_number(), if however you want tied values as well substitute dense_rank() in the query below. The create_on date has been used as a tie-beaker for sorting.

```<code>SELECT
       TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR
     , PORT, MSG_ID
     , ROUND(parsed_on -  creation_date) * 24*60 MINUTES
FROM (
      SELECT
            T_INCOME_CALLS.*
           , ROW_NUMBER() OVER(PARTITION BY IP_ADDRESS, port, TO_CHAR(CREATION_DATE, 'HH24')
                                ORDER BY (parsed_on - creation_date) desc, CREATION_DATE) AS rn
      FROM T_INCOME_CALLS
      WHERE CREATION_DATE >= TRUNC(SYSDATE) AND CREATION_DATE < TRUNC(SYSDATE) + 1
      )
WHERE rn = 1
</code>```

Please avoid converting dates into strings for your where clause, this is not efficient . Instead leave created_on untouched and amend the criteria to suit that data which will allow access to indexes for the filtering.

Body:
I have a table with the next columns

MSG_ID          NOT NULL NUMBER(10)
CREATION_DATE            DATE
PORT                     VARCHAR2(50)
MESSAGE                  VARCHAR2(1024)
IP_ADDRESS               VARCHAR2(50)
PARSED                   NUMBER(1)
PARSED_ON                DATE

Where parse time is parsed_on -  creation_date.

I would like to know if it is possible in 1 single query extract for each hour the message that take longer to parse, getting the HOUR, PORT, MSG_ID MINUTES...I am blocked here

select TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID, ROUND(MAX(parsed_on -  creation_date)) * 24*60 MINUTES
        from T_INCOME_CALLS
         where TO_CHAR(CREATION_DATE, 'dd/mm/yyyy') = TO_CHAR(SYSDATE, 'dd/mm/yyyy')
        group by TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
         order by TO_CHAR(CREATION_DATE, 'HH24') ;

Body:
I have assumed that the need is for the item that takes most time, per hour, for a grouping of IP_ADDRESS and PORT, which is different to your original query. I am also assuming MSG_ID is unique.

If you want 1 and only 1 row per recorded hour then use row_number(), if however you want tied values as well substitute dense_rank() in the query below. The create_on date has been used as a tie-beaker for sorting.

SELECT
       TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR
     , PORT, MSG_ID
     , ROUND(parsed_on -  creation_date) * 24*60 MINUTES
FROM (
      SELECT
            T_INCOME_CALLS.*
           , ROW_NUMBER() OVER(PARTITION BY IP_ADDRESS, port, TO_CHAR(CREATION_DATE, 'HH24')
                                ORDER BY (parsed_on - creation_date) desc, CREATION_DATE) AS rn
      FROM T_INCOME_CALLS
      WHERE CREATION_DATE >= TRUNC(SYSDATE) AND CREATION_DATE < TRUNC(SYSDATE) + 1
      )
WHERE rn = 1

Please avoid converting dates into strings for your where clause, this is not efficient . Instead leave created_on untouched and amend the criteria to suit that data which will allow access to indexes for the filtering.


问:
Ruby String class multiple methods and efficiency
I was looking through the Ruby source code and I can't seem to find a answer to my question:

If I call multiple methods on a string (str.upcase.reverse), does Ruby optimize this query? The code for upcase basically loops over the string and coverts each letter to its uppercase value and the reverse reverses the string. Does Ruby combine these (or any other combinable combinations) so that it will reverse AND capitalize at the same time O(n) instead of looping over each character in the string twice?

答: The optimization you are hoping for will not happen.  The reverse method is being called on a string (the result of str.upcase).  Note that the resulting behavior is still O(n) however (O(2n) is O(n))


问:
The GNU screen is unresponsive, seems blocked
GNU Screen seems to freeze. Unable to enter user input.

I was using GNU screen and when I pressed the screen it became unresponsive. I can execute all the GNU screen commands, but can't enter user input. I don't want to kill this screen as I have important work and I don't want to lose it.

答:
When you do screen -ls the first number of the screen name is the process id. So if the output is

```<code>There is a screen on:
    21605.pts-0.Random-server   (11/12/2017 11:44:15 PM)    (Detached)
1 Socket in /var/run/screen/S-kg.
</code>```

Then this will kill it:

```<code>kill 21605
</code>```

Notice the number for the kill command is the same as in the screen -ls output.

Body:
When you do screen -ls the first number of the screen name is the process id. So if the output is

There is a screen on:
    21605.pts-0.Random-server   (11/12/2017 11:44:15 PM)    (Detached)
1 Socket in /var/run/screen/S-kg.

Then this will kill it:

kill 21605

Notice the number for the kill command is the same as in the screen -ls output.


问:
Runtime Error this.object.remove is not a function
In my Ionic app, I can't delete specific key, it keeps telling me that remove is not a function. It seems there are some things changed after the last updates in angularfire2. It gives me this error:

```<code>    Runtime Error
    this.employees.remove is not a function

TypeError: this.employees.remove is not a function
    at EmployeesPage.webpackJsonp.76.EmployeesPage.deleteEmployee (http://localhost:8100/build/main.js:319:24)
    at Object.eval [as handleEvent] (ng:///AppModule/EmployeesPage.ngfactory.js:47:31)
    at handleEvent (http://localhost:8100/build/vendor.js:12380:138)
    at callWithDebugContext (http://localhost:8100/build/vendor.js:13850:42)
    at Object.debugHandleEvent [as handleEvent] (http://localhost:8100/build/vendor.js:13438:12)
    at dispatchEvent (http://localhost:8100/build/vendor.js:8972:21)
    at http://localhost:8100/build/vendor.js:9583:20
    at HTMLButtonElement.<anonymous> (http://localhost:8100/build/vendor.js:37400:53)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15040)
    at Object.onInvokeTask (http://localhost:8100/build/vendor.js:4238:33)
</code>```

I also unable to retrieve the key from my firebase database.

HTML code:

```<code><ion-list>
<ion-item-sliding *ngFor="let employee of employees | async">
  <ion-item>
    <ion-avatar item-start>
      <img src="../../assets/imgs/avatar.png">
    </ion-avatar>
    <h2>{{ employee.fname }} {{ employee.lname }}</h2>
    <p>{{ employee.position }} at {{ employee.company }}</p>
    <p>Key: {{ employee.key }}</p>
  </ion-item>
  <ion-item-options side="left">
    <button ion-button color="secondary">
      <ion-icon name="create"></ion-icon>
      Edit
    </button>
    <button ion-button color="danger" (click)="deleteEmployee(employee.key)">
      <ion-icon name="trash"></ion-icon>
      Delete
    </button>
  </ion-item-options>
  <ion-item-options side="right">
    <button ion-button color="primary">
      <ion-icon name="eye"></ion-icon>
      View
    </button>
  </ion-item-options>
</ion-item-sliding>
</code>```

Typescript code:

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabase, AngularFireList  } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@IonicPage()
@Component({
  selector: 'page-employees',
  templateUrl: 'employees.html',
})
export class EmployeesPage {

  public employees: AngularFireList<any[]>;

  constructor(
    public navCtrl   : NavController,
    public navParams : NavParams,
    public empDb     : AngularFireDatabase
  )
  {
    this.employees = this.empDb.list('/emloyeesionic').valueChanges();
  }

  deleteEmployee(key: string)
  {
    this.employees.remove(key);
  }
}
</code>```

I can't figure what the problem is!!!!

答:
Issue is your this.employees is not a reference to the real-time database after calling valueChanges() but is an Observable of the list data. Have a separate variable pointing to the reference. If you want the key, use snapShotChanges()

```<code>empRef:any;//the reference

constructor(
    public navCtrl   : NavController,
    public navParams : NavParams,
    public empDb     : AngularFireDatabase
  )
  {
    this.empRef = this.empDb.list('/emloyeesionic');
    this.employees = this.empRef.snapshotChanges();
  }
</code>```

In deleteEmployee function, use the reference to delete the item from the list.

```<code>deleteEmployee(key: string)
  {
    this.empRef.remove(key);
  }
</code>```

In your HTML, you will get actual value in employee.payload.val() and key in employee.payload.key

Body:
In my Ionic app, I can't delete specific key, it keeps telling me that remove is not a function. It seems there are some things changed after the last updates in angularfire2. It gives me this error:

    Runtime Error
    this.employees.remove is not a function

TypeError: this.employees.remove is not a function
    at EmployeesPage.webpackJsonp.76.EmployeesPage.deleteEmployee (http://localhost:8100/build/main.js:319:24)
    at Object.eval [as handleEvent] (ng:///AppModule/EmployeesPage.ngfactory.js:47:31)
    at handleEvent (http://localhost:8100/build/vendor.js:12380:138)
    at callWithDebugContext (http://localhost:8100/build/vendor.js:13850:42)
    at Object.debugHandleEvent [as handleEvent] (http://localhost:8100/build/vendor.js:13438:12)
    at dispatchEvent (http://localhost:8100/build/vendor.js:8972:21)
    at http://localhost:8100/build/vendor.js:9583:20
    at HTMLButtonElement.<anonymous> (http://localhost:8100/build/vendor.js:37400:53)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15040)
    at Object.onInvokeTask (http://localhost:8100/build/vendor.js:4238:33)

I also unable to retrieve the key from my firebase database.

HTML code:

<ion-list>
<ion-item-sliding *ngFor="let employee of employees | async">
  <ion-item>
    <ion-avatar item-start>

    </ion-avatar>

{{ employee.fname }} {{ employee.lname }}

{{ employee.position }} at {{ employee.company }}

Key: {{ employee.key }}

  </ion-item>
  <ion-item-options side="left">
    <button ion-button color="secondary">
      <ion-icon name="create"></ion-icon>
      Edit
    </button>
    <button ion-button color="danger" (click)="deleteEmployee(employee.key)">
      <ion-icon name="trash"></ion-icon>
      Delete
    </button>
  </ion-item-options>
  <ion-item-options side="right">
    <button ion-button color="primary">
      <ion-icon name="eye"></ion-icon>
      View
    </button>
  </ion-item-options>
</ion-item-sliding>

Typescript code:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabase, AngularFireList  } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@IonicPage()
@Component({
  selector: 'page-employees',
  templateUrl: 'employees.html',
})
export class EmployeesPage {

  public employees: AngularFireList<any[]>;

  constructor(
    public navCtrl   : NavController,
    public navParams : NavParams,
    public empDb     : AngularFireDatabase
  )
  {
    this.employees = this.empDb.list('/emloyeesionic').valueChanges();
  }

  deleteEmployee(key: string)
  {
    this.employees.remove(key);
  }
}

I can't figure what the problem is!!!!

Body:
Issue is your this.employees is not a reference to the real-time database after calling valueChanges() but is an Observable of the list data. Have a separate variable pointing to the reference. If you want the key, use snapShotChanges()

empRef:any;//the reference

constructor(
    public navCtrl   : NavController,
    public navParams : NavParams,
    public empDb     : AngularFireDatabase
  )
  {
    this.empRef = this.empDb.list('/emloyeesionic');
    this.employees = this.empRef.snapshotChanges();
  }

In deleteEmployee function, use the reference to delete the item from the list.

deleteEmployee(key: string)
  {
    this.empRef.remove(key);
  }

In your HTML, you will get actual value in employee.payload.val() and key in employee.payload.key


问:
Matplotlib specify axes value inside an interval
I have a csv with 200 data points. If I plot it, the x-axis will take default values from 0 to 200. However, 4 data points correspond to each event, so I would like to have values from 0 to 50 on the x-axis.

This is what I have now

```<code>import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

ax1.plot(val, color='blue', label='t1')
ax1.plot(val2, color='red', label='t2')
ax1.plot(val3, color='green', label='t3')
ax1.plot(val5, color='magenta', label='t4')

plt.axis([0,200,0,0.8])

plt.xlabel('Values')
plt.ylabel('Events')
ax1.legend(loc='upper right')
</code>```

Any idea how I can modify this to effectively divide the numbers on the x-axis by 4 ?

答:
Use x=np.arange(0,50,0.25) as x-value in your plots, as an example:

```<code>ax1.plot(x,val, color='blue', label='t1')
</code>```

Body:
I have a csv with 200 data points. If I plot it, the x-axis will take default values from 0 to 200. However, 4 data points correspond to each event, so I would like to have values from 0 to 50 on the x-axis.

This is what I have now

import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

ax1.plot(val, color='blue', label='t1')
ax1.plot(val2, color='red', label='t2')
ax1.plot(val3, color='green', label='t3')
ax1.plot(val5, color='magenta', label='t4')

plt.axis([0,200,0,0.8])

plt.xlabel('Values')
plt.ylabel('Events')
ax1.legend(loc='upper right')

Any idea how I can modify this to effectively divide the numbers on the x-axis by 4 ?

Body:
Use x=np.arange(0,50,0.25) as x-value in your plots, as an example:

ax1.plot(x,val, color='blue', label='t1')


问:
Beginner JS calculator
I am new into the world of JS, and I'm trying to build a basic calculator.
Everything work fine so long but I have problem displaying different elements on the result screen of the calculator.

When I click 1 then 2, 1 will disappear but I want it to stay for my calculation.

Please help!!

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');
function add(){
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = result;
}
function addOne() {
  var one = document.getElementById('one').value = 1;
      displayText.value = one;
}
function addTwo() {
  var two = document.getElementById('two').value = 2;
      displayText.value = two;
}
function addPlus() {
  var plus = document.getElementById('plus').value = "+";
      displayText.value = plus;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div>
  <div class="display">
    <input type="text" id="displayText" name="" value="">
    <p>The result of your calculation is: <span id="output"></span></p>
  </div>
  <div class="btn_wrap">
    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>
  </div>
</div>
      </code>```

答:
you are replacing existing value in textbox so, it will disappear
replace the addOne() and addTwo() functions with below code</p>

```<code>function addOne() {
                var one = document.getElementById('one').value = 1;
                        displayText.value = displayText.value + one;
            }
            function addTwo() {
                var two = document.getElementById('two').value = 2;
                        displayText.value =displayText.value + two;
            }
</code>```

Title: Beginner JS calculator

Body:
I am new into the world of JS, and I'm trying to build a basic calculator.
Everything work fine so long but I have problem displaying different elements on the result screen of the calculator.

When I click 1 then 2, 1 will disappear but I want it to stay for my calculation.

Please help!!

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');
function add(){
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = result;
}
function addOne() {
  var one = document.getElementById('one').value = 1;
      displayText.value = one;
}
function addTwo() {
  var two = document.getElementById('two').value = 2;
      displayText.value = two;
}
function addPlus() {
  var plus = document.getElementById('plus').value = "+";
      displayText.value = plus;
}

    <input type="text" id="displayText" name="" value="">

The result of your calculation is:

    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>

Body:
you are replacing existing value in textbox so, it will disappear
replace the addOne() and addTwo() functions with below code

function addOne() {
                var one = document.getElementById('one').value = 1;
                        displayText.value = displayText.value + one;
            }
            function addTwo() {
                var two = document.getElementById('two').value = 2;
                        displayText.value =displayText.value + two;
            }


问:
IBM Watson. How to pass context from node to node?
I"m trying to string together multiple IBM Watson requests:

Request #1:  Play music.

Watson responds with the following:

```<code>{
"intents": [
    {
        "intent": "turn_on",
        "confidence": 0.9498470783233643
    }
],
"entities": [
    {
        "entity": "appliance",
        "location": [
            5,
            10
        ],
        "value": "radio",
        "confidence": 1
    }
],
"input": {
    "text": "play music"
},
"output": {
    "text": [
        "What kind of music would you like to hear?"
    ],
    "nodes_visited": [
        "node_1_1510258504338",
        "node_2_1510258615227"
    ],
    "log_messages": []
},
"context": {
    "conversation_id": "79e93cac-12bb-40fa-ab69-88f56d0845e4",
    "system": {
        "dialog_stack": [
            {
                "dialog_node": "node_2_1510258615227"
            }
        ],
        "dialog_turn_counter": 1,
        "dialog_request_counter": 1,
        "_node_output_map": {
            "node_2_1510258615227": [
                0
            ]
        }
    }
 }
}
</code>```

Request #2:  The patron would type rock.

My problem is that I'm getting an error message that states the following

No dialog node matched for the input at a root level. (and there is 1 more warning in the log)",
        "log_messages": [

I'm pretty sure I have to pass a context into the 2nd request but I'm not sure what I need to include.  Right now I'm only passing in the conversation_id.  is there something specific from the above response that I need to pass in?  For example, I'm passing this:

```<code>{
"input": {
  "text": "rock"
},
"context": {
  "conversation_id": "79e93cac-12bb-40fa-ab69-88f56d0845e4"
 }
}
</code>```

答:
Your node that actions the type of music people select, is it a child of your 'turn_on' node [node_2_1510258615227]?

If so, as Simon demonstrates above, you need to also pass back as part of the API call the complete context packet. This informs Watson Conversation where in the dialog flow you were last. As the conversation system is state free, i.e. It does not store any state information about individual conversations, it will not by default know where it is within a conversation. This is why you then need to return the context element of the previous response, to allow watson to know where you were in the conversation flow.

Your error above states that Watson looked down the list of dialog nodes you have defined at your root level, and could not find a matching condition. Due to the fact your matching condition was within a child node.

Body:
I"m trying to string together multiple IBM Watson requests:

Request #1:  Play music.

Watson responds with the following:

{
"intents": [
    {
        "intent": "turn_on",
        "confidence": 0.9498470783233643
    }
],
"entities": [
    {
        "entity": "appliance",
        "location": [
            5,
            10
        ],
        "value": "radio",
        "confidence": 1
    }
],
"input": {
    "text": "play music"
},
"output": {
    "text": [
        "What kind of music would you like to hear?"
    ],
    "nodes_visited": [
        "node_1_1510258504338",
        "node_2_1510258615227"
    ],
    "log_messages": []
},
"context": {
    "conversation_id": "79e93cac-12bb-40fa-ab69-88f56d0845e4",
    "system": {
        "dialog_stack": [
            {
                "dialog_node": "node_2_1510258615227"
            }
        ],
        "dialog_turn_counter": 1,
        "dialog_request_counter": 1,
        "_node_output_map": {
            "node_2_1510258615227": [
                0
            ]
        }
    }
 }
}

Request #2:  The patron would type rock.

My problem is that I'm getting an error message that states the following

No dialog node matched for the input at a root level. (and there is 1 more warning in the log)",
        "log_messages": [

I'm pretty sure I have to pass a context into the 2nd request but I'm not sure what I need to include.  Right now I'm only passing in the conversation_id.  is there something specific from the above response that I need to pass in?  For example, I'm passing this:

{
"input": {
  "text": "rock"
},
"context": {
  "conversation_id": "79e93cac-12bb-40fa-ab69-88f56d0845e4"
 }
}


问:
Symfony 3 - Modify form value after submit and validation
In my application I have the requirement to modify a submitted and validated form value.

The use case is a form with an address that is validated and possibly corrected by an external web service. I need to update the address in the form after the correction and inform the user about that in there newly rendered form. The user should not get a validation error after correction.

Symfony's form component does not allow to modify an already submitted form value and throws an AlreadySubmittedException exception.

One solution is to pass the corrected address to the template and add logic to it. But this is the wrong way in my opinion.

Is there another solution?

Thanks in advance,
Jens

答:
Yes you're correct, passing the corrected value to the template is not the right way.

The correct way is to add an event listener to your form and validate/correct the value there.

```<code>use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('address');

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();
            // do webservice validation here and
            $data = [];

            // set new data
            $event->setData($data);
        });
    }
}
</code>```

The docs for more information.

Body:
Yes you're correct, passing the corrected value to the template is not the right way.

The correct way is to add an event listener to your form and validate/correct the value there.

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('address');

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();
            // do webservice validation here and
            $data = [];

            // set new data
            $event->setData($data);
        });
    }
}

The docs for more information.


问:
rest controller not working in spring boot
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

```<code>2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
</code>```

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

```<code>package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}
</code>```

the controller file:

```<code>@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

```<code>@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

it works fine!

答:
Create a person class to test:

```<code>public class Person{

private String name;
private String nickname;

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

In your method of controller, try this:

```<code> @GetMapping(value ="/test", consumes = {MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<?> helloWorld() {
        Person person = new Person();
        person.setName("test");
        person.setNickname("test2");
        return ResponseEntity.status(HttpStatus.OK).body(person);
    }
</code>```

Body:
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}

the controller file:

@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

it works fine!

Body:
Create a person class to test:

public class Person{

private String name;
private String nickname;

//getters and setters...
}

In your method of controller, try this:

 @GetMapping(value ="/test", consumes = {MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<?> helloWorld() {
        Person person = new Person();
        person.setName("test");
        person.setNickname("test2");
        return ResponseEntity.status(HttpStatus.OK).body(person);
    }


问:
splice() method works but array does not change after execution
I'm using express.js (node.js) to build an application. I have a products array declared as a session (req.session.products) in app.js folder.
Here's the POST route:

```<code>router.post('/remove-cart', (req, res, next) => {

    var product_id = req.body.product_id; //get product id from client

    console.log(req.session.products)

    var n = req.session.products.indexOf(product_id); //get position of product id in the array
    req.session.products.splice(n, 1); //remove it

    console.log(req.session.products)

});
</code>```

At the end of the route it logs this when n = 0:

```<code>[ '1', '3', '3', '3', '3' ]
[ '3', '3', '3', '3' ]
</code>```

This is what I'm expecting, however, this does not affect the main session (req.session.products) and doesn't sort of "save" it. Why?

答:
Your real problem here is that you are not returning the req.session.products array to your app, you need to send it back in the response.

In the end of your .post() method write this line:

```<code>res.send(req.session.products);
</code>```

Body:
I'm using express.js (node.js) to build an application. I have a products array declared as a session (req.session.products) in app.js folder.
Here's the POST route:

router.post('/remove-cart', (req, res, next) => {

    var product_id = req.body.product_id; //get product id from client

    console.log(req.session.products)

    var n = req.session.products.indexOf(product_id); //get position of product id in the array
    req.session.products.splice(n, 1); //remove it

    console.log(req.session.products)

});

At the end of the route it logs this when n = 0:

[ '1', '3', '3', '3', '3' ]
[ '3', '3', '3', '3' ]

This is what I'm expecting, however, this does not affect the main session (req.session.products) and doesn't sort of "save" it. Why?

Body:
Your real problem here is that you are not returning the req.session.products array to your app, you need to send it back in the response.

In the end of your .post() method write this line:

res.send(req.session.products);


问:
AsyncTask <Map<String, List<Object>>
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

```<code>Map<String, List<Object>>
</code>```

I tried starting the asynctask like this:

```<code>public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>
</code>```

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

```<code>@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}
</code>```

and the on post execute like this:

```<code>@Override
public void onPostExecute(Map<String, List<Object>> map) {
}
</code>```

What is wrong with my syntax and how would I implement this correctly?

Thanks

答:
As per  developer gide link
AsyncTask syntax is like this

public abstract class AsyncTask<Params, Progress, Result>

so your AsyncTask look like

```<code>public class GetIndividualAlarmsFromDataBase extends AsyncTask<String,Void,Map<String,List<Object>>>
</code>```

Title: AsyncTask <Map<String, List<Object>>

Body:
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

Map<String, List<Object>>

I tried starting the asynctask like this:

public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}

and the on post execute like this:

@Override
public void onPostExecute(Map<String, List<Object>> map) {
}

What is wrong with my syntax and how would I implement this correctly?

Thanks

Body:
As per  developer gide link
AsyncTask syntax is like this

public abstract class AsyncTask<Params, Progress, Result>

so your AsyncTask look like

public class GetIndividualAlarmsFromDataBase extends AsyncTask<String,Void,Map<String,List<Object>>>


问:
Sublime and q files Automatic Build Setup, on Mac OS
I am working with Sublime and also running some q/kdb scripts from Sublime.
I have a "q Build" set up and works fine when I manually change the build.
But I tend to switch between q and other languages quiet often and each time I need to manually change the build type.

How can I setup all *.q files to be run automatically with the q build setup I already have only by doing the usual Command + B?

```<code>{
"cmd": ["[full q path]", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.q",

}
</code>```

答:
I believe you need to add a language syntax definition file, in order to create a new "scope" for automatically enabling the build system.

You can see the answer here for an example: https://stackoverflow.com/a/14263821/8694303

Body:
I am working with Sublime and also running some q/kdb scripts from Sublime.
I have a "q Build" set up and works fine when I manually change the build.
But I tend to switch between q and other languages quiet often and each time I need to manually change the build type.

How can I setup all *.q files to be run automatically with the q build setup I already have only by doing the usual Command + B?

{
"cmd": ["[full q path]", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.q",

}


问:
Using createLink to share with specific users
I am trying to create a link to share a document with createLink from Microsoft Graph for specific users without using an invite but it is creating a link with Anyone with the link can edit this document permission.

I'm calling this endpoint:

```<code>POST /me/drive/items/{itemId}/createLink
</code>```

With this request body:

```<code>{
  "type": "edit",
  "scope": "anonymous"
}
</code>```

Am I missing something?

答:
Please refer this link https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_invite
You can share the file with specific user by adding user's in
"recipients":[{"@odata.type":"microsoft.graph.driveRecipient"}]
parameter. You can set sendInvitation parameter like "sendInvitation":false to avoid sending the invitation mail.</p>

Body:
I am trying to create a link to share a document with createLink from Microsoft Graph for specific users without using an invite but it is creating a link with Anyone with the link can edit this document permission.

I'm calling this endpoint:

POST /me/drive/items/{itemId}/createLink

With this request body:

{
  "type": "edit",
  "scope": "anonymous"
}

Am I missing something?


问:
Displaying additional attribute in table - Laravel
My pivot table admin_user with additional attribute item_no. I am finding it hard to retrieve the additional attribute into my html table.

PS: i tried $admin->pivot->item_no in my table but i get an error trying to get a non-object

Admin

```<code>public function users()
    {
        return $this->belongsToMany('App\User')->withPivot('item_no')
        ->withTimestamps();
    }
</code>```

admin_food

```<code>admin_id

user_id

item_no
</code>```

Controller

```<code>public function index()
     {
         $admins = Admin::where('id',1)->get();

         return view('index',compact('admins'));
     }
</code>```

HTML

```<code><table class="table" id="table">
<thead>
    <tr>
    <th>Order No#</th>
    <th>Name</th>

    </tr>

</thead>
<tbody>
@foreach($admins as $admin)
<tr >
<td>{{$admin->name}}</td>

</tr>
@endforeach
</tbody>
</table>
</code>```

答:
You access the item_id by access the pivot property of the user/related model.

Your controller is returning a collection that has only one admin.

```<code>     $admins = Admin::where('id',1)->get();
</code>```

admins will be a collection of 1 admin that has id = 1.

if this was on purpose, then you can access the item_id for every user related to this admin by this code:

```<code>@foreach($admins as $admin)
    @foreach($admin->users as $user)
        <tr>
            <td>{{$user->name}}</td>
            <td>{{$user->pivot->item_id}}</td>
        </tr>
    @endforeach
@endforeach
</code>```

To simplify:

```<code>$admin = Amdin::first();
$item_id = $admin->users()->first()->pivot->item_id
</code>```

Body:
My pivot table admin_user with additional attribute item_no. I am finding it hard to retrieve the additional attribute into my html table.

PS: i tried $admin->pivot->item_no in my table but i get an error trying to get a non-object

Admin

public function users()
    {
        return $this->belongsToMany('App\User')->withPivot('item_no')
        ->withTimestamps();
    }

admin_food

admin_id

user_id

item_no

Controller

public function index()
     {
         $admins = Admin::where('id',1)->get();

         return view('index',compact('admins'));
     }

HTML

    Order No#
    Name

@foreach($admins as $admin)

{{$admin->name}}

@endforeach

Body:
You access the item_id by access the pivot property of the user/related model.

Your controller is returning a collection that has only one admin.

     $admins = Admin::where('id',1)->get();

admins will be a collection of 1 admin that has id = 1.

if this was on purpose, then you can access the item_id for every user related to this admin by this code:

@foreach($admins as $admin)
    @foreach($admin->users as $user)
        <tr>
            <td>{{$user->name}}</td>
            <td>{{$user->pivot->item_id}}</td>
        </tr>
    @endforeach
@endforeach

To simplify:

$admin = Amdin::first();
$item_id = $admin->users()->first()->pivot->item_id


问:
PHP - self, static or $this in callback function
Is it possible to access classes/objects reffered as self, static and $this in anonymous callbacks in PHP? Just like this:

```<code>class Foo {
    const BAZ = 5;
    public static function bar() {
         echo self::BAZ; // it works OK
         array_filter(array(1,3,5), function($number) /* use(self) */ {
             return $number !== self::BAZ; // I cannot access self from here
         });
    }
}
</code>```

Is there any way to make it behave as with usual variables, using use(self) clause?

答:
What about this:</p>

```<code>class Foo {
    const BAZ = 5;
    $self = __class__;
    public static function bar() {
         echo self::BAZ; // it works OK
         array_filter(array(1,3,5), function($number) use($self) {
             return $number !== $self::BAZ; // access to self, just your const must be public
         });
    }
}
</code>```

Body:
Is it possible to access classes/objects reffered as self, static and $this in anonymous callbacks in PHP? Just like this:

class Foo {
    const BAZ = 5;
    public static function bar() {
         echo self::BAZ; // it works OK
         array_filter(array(1,3,5), function($number) /* use(self) */ {
             return $number !== self::BAZ; // I cannot access self from here
         });
    }
}

Is there any way to make it behave as with usual variables, using use(self) clause?

Body:
What about this:

class Foo {
    const BAZ = 5;
    $self = __class__;
    public static function bar() {
         echo self::BAZ; // it works OK
         array_filter(array(1,3,5), function($number) use($self) {
             return $number !== $self::BAZ; // access to self, just your const must be public
         });
    }
}


问:
Property not found in class - Flow & React
I am trying to leverage Flow and get it working nicely with a react component of mine. However I am getting:

client/search-container.jsx:18   18:     this.handleSearchSubmit =
  this.handleSearchSubmit.bind(this);
                ^^^^^^^^^^^^^^^^^^ property handleSearchSubmit. Property not found in   18: class SearchContainer extends
  React.Component {
             ^^^^^^^^^^^^^^^ SearchContainer

The component I have set up is as followed:

```<code>// @flow

import React, { PropTypes } from 'react';
import SearchForm from './search-form';

type Props = {
  onSearchUpdate: Function,
}

class SearchContainer extends React.Component {
  props: Props;

  constructor(props: Props) {
    super(props);
    this.handleSearchSubmit = this.handleSearchSubmit.bind(this);
  }

  handleSearchSubmit(searchTerm: {address: string, lat: number, lng: number}): void {
    this.props.onSearchUpdate(searchTerm);
  }

  render() {
    return (
      <div className="searchBox">
        <SearchForm onSearchSubmit={this.handleSearchSubmit} />
      </div>
    );
  }
}

// SearchContainer.propTypes = {
//   onSearchUpdate: PropTypes.func,
// };

export default SearchContainer;
</code>```

You'll see previously I was making use of the propTypes at the bottom of my class. Questions:

Does my class set up look correct?

Why is flow complaining that property handleSearchSubmit is not found and the same too with the name of my class name SearchContainer

答:
Hello I feel like that @TLadd answer is a hack.

Flow is asking for the type of handleSearchSubmit and it does not find it
you just need to add this below below the method definition

```<code>  handleSearchSubmit: <your type>;
</code>```

This is the final code

```<code>// @flow

import React, { PropTypes } from 'react';
import SearchForm from './search-form';

type Props = {
  onSearchUpdate: Function,
}

class SearchContainer extends React.Component {
  props: Props;
  // ->>>
  handleSearchSubmit: <your type>;
  // <---
  constructor(props: Props) {
    super(props);
    this.handleSearchSubmit = this.handleSearchSubmit.bind(this);
  }

  handleSearchSubmit(searchTerm: {address: string, lat: number, lng: number}): void {
    this.props.onSearchUpdate(searchTerm);
  }

  render() {
    return (
      <div className="searchBox">
        <SearchForm onSearchSubmit={this.handleSearchSubmit} />
      </div>
    );
  }
}

// SearchContainer.propTypes = {
//   onSearchUpdate: PropTypes.func,
// };

export default SearchContainer;
</code>```

Body:
I am trying to leverage Flow and get it working nicely with a react component of mine. However I am getting:

client/search-container.jsx:18   18:     this.handleSearchSubmit =
  this.handleSearchSubmit.bind(this);
                ^^^^^^^^^^^^^^^^^^ property handleSearchSubmit. Property not found in   18: class SearchContainer extends
  React.Component {
             ^^^^^^^^^^^^^^^ SearchContainer

The component I have set up is as followed:

// @flow

import React, { PropTypes } from 'react';
import SearchForm from './search-form';

type Props = {
  onSearchUpdate: Function,
}

class SearchContainer extends React.Component {
  props: Props;

  constructor(props: Props) {
    super(props);
    this.handleSearchSubmit = this.handleSearchSubmit.bind(this);
  }

  handleSearchSubmit(searchTerm: {address: string, lat: number, lng: number}): void {
    this.props.onSearchUpdate(searchTerm);
  }

  render() {
    return (

        <SearchForm onSearchSubmit={this.handleSearchSubmit} />

    );
  }
}

// SearchContainer.propTypes = {
//   onSearchUpdate: PropTypes.func,
// };

export default SearchContainer;

You'll see previously I was making use of the propTypes at the bottom of my class. Questions:

Does my class set up look correct?

Why is flow complaining that property handleSearchSubmit is not found and the same too with the name of my class name SearchContainer

Body:
Hello I feel like that @TLadd answer is a hack.

Flow is asking for the type of handleSearchSubmit and it does not find it
you just need to add this below below the method definition

  handleSearchSubmit: <your type>;

This is the final code

// @flow

import React, { PropTypes } from 'react';
import SearchForm from './search-form';

type Props = {
  onSearchUpdate: Function,
}

class SearchContainer extends React.Component {
  props: Props;
  // ->>>
  handleSearchSubmit: <your type>;
  // <---
  constructor(props: Props) {
    super(props);
    this.handleSearchSubmit = this.handleSearchSubmit.bind(this);
  }

  handleSearchSubmit(searchTerm: {address: string, lat: number, lng: number}): void {
    this.props.onSearchUpdate(searchTerm);
  }

  render() {
    return (
      <div className="searchBox">
        <SearchForm onSearchSubmit={this.handleSearchSubmit} />
      </div>
    );
  }
}

// SearchContainer.propTypes = {
//   onSearchUpdate: PropTypes.func,
// };

export default SearchContainer;


问:
print last line from the variable output in python
I am looking to get the last line produced from the line variable

```<code>bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line
</code>```

output i am getting is as follows ..

```<code>-122.1058
-123.1050
-125.10584323
</code>```

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

```<code>bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)
</code>```

this yeilds teh desired as folows..

```<code>bash-4.1$ ./file2_dup.py
-125.10584323
</code>```

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

答:
You could test if the new line is smaller as the one before like this</p>

```<code>#!/usr/bin/python
res_line = 0
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = float(line.split()[-1].strip())
      if res_line > line:
          res_line = line
  print res_line
</code>```

Body:
I am looking to get the last line produced from the line variable

bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line

output i am getting is as follows ..

-122.1058
-123.1050
-125.10584323

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)

this yeilds teh desired as folows..

bash-4.1$ ./file2_dup.py
-125.10584323

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

Body:
You could test if the new line is smaller as the one before like this

#!/usr/bin/python
res_line = 0
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = float(line.split()[-1].strip())
      if res_line > line:
          res_line = line
  print res_line


问:
asp.net availability calendar showing full year
I am looking for a asp.net control that will display a full year in a grid format, with each month as a row and each day in the month as the columns. I have found the following classic ASP script which produces the correct format: http://www.livio.net/code/calendar_36/CalendarTestYearly36.asp?infomode=HELP (see Yearly Calendar)

Is anything like this available or is there a way to do this simply without a specific control? I am new to asp.net.

Thanks

答:
Whipped up this, just for you:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Yearly Calendar</title>
    <style type="text/css">
        table td { padding:0; margin:0; border:1px solid #dadada; }
        table th { width:25px; text-align:center; }
        table td { text-align:center; }
        table td span { color:#dadada; }
        table td a { color:#000000; text-decoration:none; }
        table td a:hover { text-decoration:underline; }
        table td a.hasEvents { color:#ff0000; }
        table td a.selected { color:#0000ff; font-weight:bold; }
        table td.month { background-color:#999999; }
        table td.weekend { background-color:#D0D0D0; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="0" cellspacing="0">
            <thead>
                <tr>
                    <th>
                        <asp:Literal ID="litSelectedYear" runat="server" />
                    </th>
                    <% for (int iWeek = 1; iWeek <= 6; iWeek++) {
                        for (int iDay = 1; iDay <= 7; iDay++) { if (iWeek == 6 && iDay > 2) break; %>
                        <th>
                            <%= GetDayName(iDay) %>
                        </th>
                    <% } } %>
                </tr>
            </thead>
            <asp:Repeater ID="repMonths" runat="server" OnInit="repMonths_OnInit" OnItemDataBound="repMonths_OnItemDataBound">
                <ItemTemplate>
                    <tr>
                        <td class="month">
                            <asp:HyperLink ID="hylMonth" runat="server" />
                        </td>
                        <asp:Repeater ID="repDays" runat="server" OnItemDataBound="repDays_OnItemDataBound">
                            <ItemTemplate>
                                <td id="tdDay" runat="server">
                                    <asp:Literal ID="litDay" runat="server" />
                                </td>
                            </ItemTemplate>
                        </asp:Repeater>
                    </tr>
                </ItemTemplate>
            </asp:Repeater>
        </table>
    </div>
    </form>
</body>
</html>
</code>```

```<code>using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    private DateTime _dtMonth;
    private DateTime _selectedDate;
    private bool _specialDaySelected = true;
    private int _currentBindingMonth;

    protected void repMonths_OnInit(object sender, EventArgs e)
    {
        if (!DateTime.TryParse(Request.QueryString["CalDate"], out _selectedDate))
        {
            _specialDaySelected = false;
            int selectedMonth, selectedYear;
            int.TryParse(Request.QueryString["CalYear"], out selectedYear);
            int.TryParse(Request.QueryString["CalMonth"], out selectedMonth);

            if (selectedYear <= 0) selectedYear = DateTime.Now.Year;
            if (selectedMonth <= 1) selectedMonth = 1;
            else if (selectedMonth > 12) selectedMonth = 12;

            _selectedDate = new DateTime(selectedYear, selectedMonth, 1);
        }

        litSelectedYear.Text = _selectedDate.Year.ToString();

        repMonths.DataSource = new int[]{1,2,3,4,5,6,7,8,9,10,11,12};
        repMonths.DataBind();
    }

    protected void repMonths_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater repDays = (Repeater)e.Item.FindControl("repDays");
            HyperLink hylMonth = (HyperLink)e.Item.FindControl("hylMonth");
            _currentBindingMonth = (int)e.Item.DataItem;
            _dtMonth = new DateTime(_selectedDate.Year, _currentBindingMonth, 1);

            hylMonth.Text = _dtMonth.ToString("MMM");
            hylMonth.NavigateUrl = string.Format("{0}?CalMonth={1}&CalYear={2}", Request.Path, _currentBindingMonth, _selectedDate.Year);

            if (_currentBindingMonth == _selectedDate.Month) hylMonth.Attributes.Add("class", "selected");

            if (_dtMonth.DayOfWeek != DayOfWeek.Monday)
            {
                int daysToSubtract = -(int)_dtMonth.DayOfWeek;

                if (_dtMonth.DayOfWeek == DayOfWeek.Sunday) daysToSubtract = -7; // Special case. US weeks start with sunday, thus the enum DayOfWeek.Sunday = 0.

                _dtMonth = _dtMonth.AddDays(daysToSubtract + 1);
            }

            DateTime[] dates = new DateTime[37];
            for (int i = 0; i < 37; i++)
            {
                dates[i] = _dtMonth;
                _dtMonth = _dtMonth.AddDays(1);
            }

            repDays.DataSource = dates;
            repDays.DataBind();
        }
    }

    protected void repDays_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DateTime date = (DateTime)e.Item.DataItem;
            Literal litDay = (Literal)e.Item.FindControl("litDay");
            HtmlTableCell tdDay = (HtmlTableCell)e.Item.FindControl("tdDay");

            if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
                tdDay.Attributes.Add("class", "weekend");

            if (_currentBindingMonth == date.Month)
                litDay.Text = string.Format("<a href=\"{0}?CalDate={3}-{2}-{1}\"{4}>{3}</a>", Request.Path, date.Year, date.Month, date.Day.ToString("D2"), (_specialDaySelected && date.Equals(_selectedDate)) ? " class=\"selected\"" : string.Empty);
            else
                litDay.Text = string.Format("<span>{0}</span>", date.Day.ToString("D2"));

            // Clear ID's
            tdDay.ID = string.Empty;
        }
    }

    public static string GetDayName(int dayInWeek)
    {
        switch (dayInWeek)
        {
            case 1: return "mo";
            case 2: return "tu";
            case 3: return "we";
            case 4: return "th";
            case 5: return "fr";
            case 6: return "sa";
            case 7: return "su";
        }

        return "God only made seven days in a week.";
    }
}
</code>```

Body:
Whipped up this, just for you:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Yearly Calendar</title>
    <style type="text/css">
        table td { padding:0; margin:0; border:1px solid #dadada; }
        table th { width:25px; text-align:center; }
        table td { text-align:center; }
        table td span { color:#dadada; }
        table td a { color:#000000; text-decoration:none; }
        table td a:hover { text-decoration:underline; }
        table td a.hasEvents { color:#ff0000; }
        table td a.selected { color:#0000ff; font-weight:bold; }
        table td.month { background-color:#999999; }
        table td.weekend { background-color:#D0D0D0; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="0" cellspacing="0">
            <thead>
                <tr>
                    <th>
                        <asp:Literal ID="litSelectedYear" runat="server" />
                    </th>
                    <% for (int iWeek = 1; iWeek <= 6; iWeek++) {
                        for (int iDay = 1; iDay <= 7; iDay++) { if (iWeek == 6 && iDay > 2) break; %>
                        <th>
                            <%= GetDayName(iDay) %>
                        </th>
                    <% } } %>
                </tr>
            </thead>
            <asp:Repeater ID="repMonths" runat="server" OnInit="repMonths_OnInit" OnItemDataBound="repMonths_OnItemDataBound">
                <ItemTemplate>
                    <tr>
                        <td class="month">
                            <asp:HyperLink ID="hylMonth" runat="server" />
                        </td>
                        <asp:Repeater ID="repDays" runat="server" OnItemDataBound="repDays_OnItemDataBound">
                            <ItemTemplate>
                                <td id="tdDay" runat="server">
                                    <asp:Literal ID="litDay" runat="server" />
                                </td>
                            </ItemTemplate>
                        </asp:Repeater>
                    </tr>
                </ItemTemplate>
            </asp:Repeater>
        </table>
    </div>
    </form>
</body>
</html>

using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    private DateTime _dtMonth;
    private DateTime _selectedDate;
    private bool _specialDaySelected = true;
    private int _currentBindingMonth;

    protected void repMonths_OnInit(object sender, EventArgs e)
    {
        if (!DateTime.TryParse(Request.QueryString["CalDate"], out _selectedDate))
        {
            _specialDaySelected = false;
            int selectedMonth, selectedYear;
            int.TryParse(Request.QueryString["CalYear"], out selectedYear);
            int.TryParse(Request.QueryString["CalMonth"], out selectedMonth);

            if (selectedYear <= 0) selectedYear = DateTime.Now.Year;
            if (selectedMonth <= 1) selectedMonth = 1;
            else if (selectedMonth > 12) selectedMonth = 12;

            _selectedDate = new DateTime(selectedYear, selectedMonth, 1);
        }

        litSelectedYear.Text = _selectedDate.Year.ToString();

        repMonths.DataSource = new int[]{1,2,3,4,5,6,7,8,9,10,11,12};
        repMonths.DataBind();
    }

    protected void repMonths_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater repDays = (Repeater)e.Item.FindControl("repDays");
            HyperLink hylMonth = (HyperLink)e.Item.FindControl("hylMonth");
            _currentBindingMonth = (int)e.Item.DataItem;
            _dtMonth = new DateTime(_selectedDate.Year, _currentBindingMonth, 1);

            hylMonth.Text = _dtMonth.ToString("MMM");
            hylMonth.NavigateUrl = string.Format("{0}?CalMonth={1}&CalYear={2}", Request.Path, _currentBindingMonth, _selectedDate.Year);

            if (_currentBindingMonth == _selectedDate.Month) hylMonth.Attributes.Add("class", "selected");

            if (_dtMonth.DayOfWeek != DayOfWeek.Monday)
            {
                int daysToSubtract = -(int)_dtMonth.DayOfWeek;

                if (_dtMonth.DayOfWeek == DayOfWeek.Sunday) daysToSubtract = -7; // Special case. US weeks start with sunday, thus the enum DayOfWeek.Sunday = 0.

                _dtMonth = _dtMonth.AddDays(daysToSubtract + 1);
            }

            DateTime[] dates = new DateTime[37];
            for (int i = 0; i < 37; i++)
            {
                dates[i] = _dtMonth;
                _dtMonth = _dtMonth.AddDays(1);
            }

            repDays.DataSource = dates;
            repDays.DataBind();
        }
    }

    protected void repDays_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DateTime date = (DateTime)e.Item.DataItem;
            Literal litDay = (Literal)e.Item.FindControl("litDay");
            HtmlTableCell tdDay = (HtmlTableCell)e.Item.FindControl("tdDay");

            if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
                tdDay.Attributes.Add("class", "weekend");

            if (_currentBindingMonth == date.Month)
                litDay.Text = string.Format("<a href=\"{0}?CalDate={3}-{2}-{1}\"{4}>{3}</a>", Request.Path, date.Year, date.Month, date.Day.ToString("D2"), (_specialDaySelected && date.Equals(_selectedDate)) ? " class=\"selected\"" : string.Empty);
            else
                litDay.Text = string.Format("<span>{0}</span>", date.Day.ToString("D2"));

            // Clear ID's
            tdDay.ID = string.Empty;
        }
    }

    public static string GetDayName(int dayInWeek)
    {
        switch (dayInWeek)
        {
            case 1: return "mo";
            case 2: return "tu";
            case 3: return "we";
            case 4: return "th";
            case 5: return "fr";
            case 6: return "sa";
            case 7: return "su";
        }

        return "God only made seven days in a week.";
    }
}


问:
Proguard error after adding Glide v4
I am not able to generate the apk with proguard enabled after adding glide v4 library.
I have added the below lines in proguard-rules

```<code>-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}
</code>```

It's showing the below error while building.

Warning:com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool:
  can't find referenced field 'android.graphics.Bitmap$Config HARDWARE'
  in library class android.graphics.Bitmap$Config

答:
I assume you take your proguard rules from this glide page but it is miswritten. Replace below line

-keep public class * extends com.bumptech.glide.AppGlideModule

with this:

-keep public class * extends com.bumptech.glide.module.AppGlideModule

as you see, module package is missing. It is also properly documented on README page. You can also check your AppGlideModule class path from External Libraries.

Title: Proguard error after adding Glide v4

Body:
I am not able to generate the apk with proguard enabled after adding glide v4 library.
I have added the below lines in proguard-rules

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

It's showing the below error while building.

Warning:com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool:
  can't find referenced field 'android.graphics.Bitmap$Config HARDWARE'
  in library class android.graphics.Bitmap$Config


问:
Adding a drop shadow to ImageView
Is it possible to do a drop shadow on the content of an ImageView?

Not a square, but an object drop shadow that acts on the non-transparent content of the ImageView.

Like this

答:
Use this class to draw shadow on bitmap</p>

```<code>public class ShadowGenerator {

    // Percent of actual icon size
    private static final float HALF_DISTANCE = 0.5f;
    public static final float BLUR_FACTOR = 0.5f/48;

    // Percent of actual icon size
    private static final float KEY_SHADOW_DISTANCE = 1f/48;
    public static final int KEY_SHADOW_ALPHA = 61;

    public static final int AMBIENT_SHADOW_ALPHA = 30;

    private static final Object LOCK = new Object();
    // Singleton object guarded by {@link #LOCK}
    private static ShadowGenerator sShadowGenerator;

    private  int mIconSize;

    private final Canvas mCanvas;
    private final Paint mBlurPaint;
    private final Paint mDrawPaint;
    private final Context mContext;

    private ShadowGenerator(Context context) {
        mContext = context;
        mCanvas = new Canvas();
        mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
        mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public synchronized Bitmap recreateIcon(Bitmap icon) {
        mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
        int[] offset = new int[2];
        Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
        mCanvas.setBitmap(result);

        // Draw ambient shadow
        mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);

        // Draw key shadow
        mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);

        // Draw the icon
        mDrawPaint.setAlpha(255);
        mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);

        mCanvas.setBitmap(null);
        return result;
    }

    public static ShadowGenerator getInstance(Context context) {

        synchronized (LOCK) {
            if (sShadowGenerator == null) {
                sShadowGenerator = new ShadowGenerator(context);
            }
        }
        return sShadowGenerator;
    }

}
</code>```

Title: Adding a drop shadow to ImageView

Body:
Use this class to draw shadow on bitmap

public class ShadowGenerator {

    // Percent of actual icon size
    private static final float HALF_DISTANCE = 0.5f;
    public static final float BLUR_FACTOR = 0.5f/48;

    // Percent of actual icon size
    private static final float KEY_SHADOW_DISTANCE = 1f/48;
    public static final int KEY_SHADOW_ALPHA = 61;

    public static final int AMBIENT_SHADOW_ALPHA = 30;

    private static final Object LOCK = new Object();
    // Singleton object guarded by {@link #LOCK}
    private static ShadowGenerator sShadowGenerator;

    private  int mIconSize;

    private final Canvas mCanvas;
    private final Paint mBlurPaint;
    private final Paint mDrawPaint;
    private final Context mContext;

    private ShadowGenerator(Context context) {
        mContext = context;
        mCanvas = new Canvas();
        mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
        mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public synchronized Bitmap recreateIcon(Bitmap icon) {
        mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
        int[] offset = new int[2];
        Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
        mCanvas.setBitmap(result);

        // Draw ambient shadow
        mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);

        // Draw key shadow
        mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);

        // Draw the icon
        mDrawPaint.setAlpha(255);
        mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);

        mCanvas.setBitmap(null);
        return result;
    }

    public static ShadowGenerator getInstance(Context context) {

        synchronized (LOCK) {
            if (sShadowGenerator == null) {
                sShadowGenerator = new ShadowGenerator(context);
            }
        }
        return sShadowGenerator;
    }

}