问:
SQOOP Export failure
I am trying to export a table from HDFS to SQOOP but I am getting java exceptions.
The query I'm using is as follows:

```<code>sqoop export --connect jdbc:mysql://172.31.54.174/Database --driver com.mysql.jdbc.Driver --username user --password userpassword --table accounts --export-dir /user/pri/accounts
</code>```

While execution this query gives me below error:

```<code>17/03/29 07:54:26 INFO mapreduce.Job:  map 0% reduce 0%
17/03/29 07:54:30 INFO mapreduce.Job: Task Id : attempt_1489328678238_4886_m_000002_0, Status : FAILED
Error: java.io.IOException: Can't export data, please check failed map task logs
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:112)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:39)
        at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:146)
        at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
        at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
Caused by: java.lang.RuntimeException: Can't parse input data: '\N'
        at accounts.__loadFromFields(accounts.java:691)
        at accounts.parse(accounts.java:584)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:83)
        ... 10 more
Caused by: java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
        at java.sql.Timestamp.valueOf(Timestamp.java:204)
        at accounts.__loadFromFields(accounts.java:643)
        ... 12 more
</code>```

The file that I am exporting contains data as below :

```<code>1,2008-10-23 16:05:05.0,\N,Donald,Becton,2275 Washburn Street,Oakland,CA,94660,5100032418,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0

2,2008-11-12 03:00:01.0,\N,Donna,Jones,3885 Elliott Street,San Francisco,CA,94171,4150835799,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0
</code>```

I have also created the table accounts and its structure is as follows:

+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| acct_num       | varchar(20) | NO   | PRI |         |       |
| acct_create_dt | datetime    | NO   |     | NULL    |       |
| acc_close_dt   | datetime    | YES  |     | NULL    |       |
| first_name     | varchar(20) | NO   |     | NULL    |       |
| last_name      | varchar(20) | NO   |     | NULL    |       |
| address        | varchar(30) | NO   |     | NULL    |       |
| city           | varchar(20) | NO   |     | NULL    |       |
| state          | varchar(20) | NO   |     | NULL    |       |
| zipcode        | varchar(20) | NO   |     | NULL    |       |
| phone_number   | varchar(20) | YES  |     | NULL    |       |
| created        | datetime    | NO   |     | NULL    |       |
| modified       | datetime    | NO   |     | NULL    |       |
+----------------+-------------+------+-----+---------+-------+

I am also attaching a screenshot of the error.

答: As you can see from your logs '\N' is like escape character so it isnot fitting in varchar.I dont understand why you are adding the same. Also the timestamp format issues is indicated.And also check in your existing data if any column you are using for primary key is repeated itself. </p>

Title: SQOOP Export failure

Body:
I am trying to export a table from HDFS to SQOOP but I am getting java exceptions.
The query I'm using is as follows:

sqoop export --connect jdbc:mysql://172.31.54.174/Database --driver com.mysql.jdbc.Driver --username user --password userpassword --table accounts --export-dir /user/pri/accounts

While execution this query gives me below error:

17/03/29 07:54:26 INFO mapreduce.Job:  map 0% reduce 0%
17/03/29 07:54:30 INFO mapreduce.Job: Task Id : attempt_1489328678238_4886_m_000002_0, Status : FAILED
Error: java.io.IOException: Can't export data, please check failed map task logs
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:112)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:39)
        at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:146)
        at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
        at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
Caused by: java.lang.RuntimeException: Can't parse input data: '\N'
        at accounts.__loadFromFields(accounts.java:691)
        at accounts.parse(accounts.java:584)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:83)
        ... 10 more
Caused by: java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
        at java.sql.Timestamp.valueOf(Timestamp.java:204)
        at accounts.__loadFromFields(accounts.java:643)
        ... 12 more

The file that I am exporting contains data as below :

1,2008-10-23 16:05:05.0,\N,Donald,Becton,2275 Washburn Street,Oakland,CA,94660,5100032418,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0

2,2008-11-12 03:00:01.0,\N,Donna,Jones,3885 Elliott Street,San Francisco,CA,94171,4150835799,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0

I have also created the table accounts and its structure is as follows:

+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| acct_num       | varchar(20) | NO   | PRI |         |       |
| acct_create_dt | datetime    | NO   |     | NULL    |       |
| acc_close_dt   | datetime    | YES  |     | NULL    |       |
| first_name     | varchar(20) | NO   |     | NULL    |       |
| last_name      | varchar(20) | NO   |     | NULL    |       |
| address        | varchar(30) | NO   |     | NULL    |       |
| city           | varchar(20) | NO   |     | NULL    |       |
| state          | varchar(20) | NO   |     | NULL    |       |
| zipcode        | varchar(20) | NO   |     | NULL    |       |
| phone_number   | varchar(20) | YES  |     | NULL    |       |
| created        | datetime    | NO   |     | NULL    |       |
| modified       | datetime    | NO   |     | NULL    |       |
+----------------+-------------+------+-----+---------+-------+

I am also attaching a screenshot of the error.


来源: stackexchange

问:
Ionic 2 is not working in local machine
I tried to run the ionic 2 basic application from my ubuntu 16.04.2 LTS machine. After ionic serve command.

It's showing up to this message ,nothing is building after this message

```<code>> ionic-app-base@ ionic:serve /home/USER_NAME/Desktop/training/ionicProject/testProject
> ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
</code>```

following info based on ionic

```<code>Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.2.2
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.1
Xcode version: Not installed
</code>```

答:
I was having the same issue, I tried all versions of ionic/app-scripts 1.0.0 and above. the versions that work for me are 1.0.0 and 1.0.1 .

 Try changing ionic/app-script version in package.json to 1.0.0 or 1.0.1

Then run npm install in your app folder

ionic serve (using sudo is not necessary.)

-------ionic info-------

```
Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.2
Ionic App Lib Version: 2.2.1
<b>Ionic App Scripts Version: 1.0.1</b>
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.0
Xcode version: Not installed

```

ContentLicense: CC BY-SA 3.0

Title: Ionic 2 is not working in local machine

Body:
I tried to run the ionic 2 basic application from my ubuntu 16.04.2 LTS machine. After ionic serve command.

It's showing up to this message ,nothing is building after this message

> ionic-app-base@ ionic:serve /home/USER_NAME/Desktop/training/ionicProject/testProject
> ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"

following info based on ionic

Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.2.2
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.1
Xcode version: Not installed

Body:
I was having the same issue, I tried all versions of ionic/app-scripts 1.0.0 and above. the versions that work for me are 1.0.0 and 1.0.1 .

 Try changing ionic/app-script version in package.json to 1.0.0 or 1.0.1

Then run npm install in your app folder

ionic serve (using sudo is not necessary.)

-------ionic info-------

Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.2
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.0.1
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.0
Xcode version: Not installed


问:
Mirth HL7 ACK ERROR: Message control Ids do not match
I'm starting out with Mirth and HL7 and I'm trying to send a message to a remote server. My MSH looks as follows:

```<code>MSH|^~\&|EPIC|EPIC|IMG_SCHEDULE_APPT|REMOTE|20170328193318|PERSONNAME|ORM^O01|12345678|T|2.4||||||||||
</code>```

The response looks as follows:

```<code>MSH|^~\&|IMG_SCHEDULE_APPT|REMOTE|EPIC|EPIC|20170328193318||ACK|12345678|T|2.4|
MSA|AA|||
</code>```

and I get an error saying ERROR: Message control Ids do not match.

As far as I understand this error means that the Message Control Id which is returned in the ACK message is not the same.

From what I can see, the number 12345678 is the Message Control Id, and I see that number both in the message I send as well as the in the ACK which is returned. So what is wrong here? And who is at fault? Me or the remote party?

Does anybody know how I can solve or debug this?

答: MSA.2 (Message Control ID) is required and should be the same as the ControlId in the former message that the ACK message acknowleges..</p>

Body:
I'm starting out with Mirth and HL7 and I'm trying to send a message to a remote server. My MSH looks as follows:

MSH|^~\&|EPIC|EPIC|IMG_SCHEDULE_APPT|REMOTE|20170328193318|PERSONNAME|ORM^O01|12345678|T|2.4||||||||||

The response looks as follows:

MSH|^~\&|IMG_SCHEDULE_APPT|REMOTE|EPIC|EPIC|20170328193318||ACK|12345678|T|2.4|
MSA|AA|||

and I get an error saying ERROR: Message control Ids do not match.

As far as I understand this error means that the Message Control Id which is returned in the ACK message is not the same.

From what I can see, the number 12345678 is the Message Control Id, and I see that number both in the message I send as well as the in the ACK which is returned. So what is wrong here? And who is at fault? Me or the remote party?

Does anybody know how I can solve or debug this?


问:
What's really more performant? Haskell or OCaml
I spent the last 18 months getting the grip of functional programming, starting with learning OCaml and for some weeks now Haskell. Now I want to take the next step and implement some actual application: A simple realtime terrain editor. I've written numerous realtime terrain rendering engines, so this is a familiar topic. And the used recursive algorithms and data structures seem very fit for a functional implementation.

With this being a realtime application I'm naturally looking for the best performance I can get. Now some proponents of OCaml quite frequently complain about Haskell being slow compared to OCaml or F#. But according to the The Computer Language Benchmarks Game Haskell oftenly beats OCaml, if only by rather small fractions. There remains the problem, that this benchmark takes only very specific samples.

The right thing to do would be to, of course, implement the program in both languages and compare them, but I simply don't want to do double the work.

But maybe other people did comparable applications in OCaml and Haskell and give some statistics?

答:
I've written numerous realtime terrain rendering engines, so this is a familiar topic.

Familiar enough to know where most time will be spent?

If so then maybe you can write code for just that part in different languages and compare.

But according to the The Computer Language Benchmarks Game Haskell often beats OCaml, if only by rather small fractions — there remains the problem, that this benchmark takes only very specific samples.

The benchmarks game reports 4 sets of results - one core and quad core, 32 or 64 bit Ubuntu - and you may find that the OCaml or Haskell benchmark programs perform better or worse depending on the platform.

All a benchmark can do is take very specific samples, and of course you should disregard comparisons on tasks that are unlike where most time will be spent in your application - large integer arithmetic? regex? strings? - and look at the comparisons that are most like what you intend to do.

ContentLicense: CC BY-SA 4.0


问:
How to re-open something after used `JQuery.remove()`?
I used a free template for my app and with this template there is a button to "hide" list like this:

the little x button

And the executed code is the following one:

```<code>$(document).on('click', '.close-link', function () {
   var $BOX_PANEL = $(this).closest('.x_panel');
   $BOX_PANEL.remove();
});
</code>```

Now I'm trying to add a button to re-open this list but here comes the struggle I can't find a way to do that. I checked the documentation of JQuery remove() and there is not JQuery open()...

Do you guy have an idea ?

[EDIT] maybe the HTML would be great so :

```<code><div class="col-md-6 col-sm-12 col-xs-12">
    <div class="x_panel">
        <div class="x_title">
            <h2>Machines</h2>
               <ul class="nav navbar-right panel_toolbox">
                  <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a></li>
                  <li class="dropdwon">
                     <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                     <ul class="dropdown-menu" role="menu"></ul>
                  </li>
                  {{#if isNotHome}}<li><a class="backLocalHostDocker"><i class="fa fa-home"></i></a></li>{{/if}}
                  <li><a class="close-link" id="closeList"><i class="fa fa-close"></i></a></li>
              </ul>
           <div class="clearfix"></div>
         </div>
         <div class="x_content">
             <br />
             <ul class="container"></ul>
         </div>
    </div>
</div>
</code>```

I just cleaned the code to just display the structure

答:
You can use jQuery toggle() function to Show/Hide Tags

Example :

```<code>$(document).on('click', '.close-link', function () {
    $('.x_panel').toggle();
});
</code>```

Now, you can show/hide your .x_panel block by clicking .close-link

Here is the details about toggle() function.

Body:
I used a free template for my app and with this template there is a button to "hide" list like this:

the little x button

And the executed code is the following one:

$(document).on('click', '.close-link', function () {
   var $BOX_PANEL = $(this).closest('.x_panel');
   $BOX_PANEL.remove();
});

Now I'm trying to add a button to re-open this list but here comes the struggle I can't find a way to do that. I checked the documentation of JQuery remove() and there is not JQuery open()...

Do you guy have an idea ?

[EDIT] maybe the HTML would be great so :

Machines

                  {{#if isNotHome}}

{{/if}}

I just cleaned the code to just display the structure

Body:
You can use jQuery toggle() function to Show/Hide Tags

Example :

$(document).on('click', '.close-link', function () {
    $('.x_panel').toggle();
});

Now, you can show/hide your .x_panel block by clicking .close-link

Here is the details about toggle() function.


问:
Peek of multiprocessing.queue?
I have multiple worker processes reading from the same multiprocessing.queue(). Each worker process only read contents belongs to itself, and must leave the other contents untouched. So basically the worker process must first check the queue contents then decides whether to pop one item.

Is there any way to do this with multiprocessing.queue?

答:
you can always put back messages that you don't need (if order is not an issue)

```<code>def get_my_job():

    while True:
        job = q.get()
        if job == 'mine':
            return job
        q.put(job)
        time.sleep(random()/2) #preventing deadlocks...
</code>```

If the order is important you may use multiple Queues for so each message type will be in its own Queue

```<code>queues = { 'queue4worker_type1': Queue(),
           'queue4worker_type2': Queue(),
          }
#each worker can now consume only messages for its wanted types ...
</code>```

Title: Peek of multiprocessing.queue?

Body:
you can always put back messages that you don't need (if order is not an issue)

def get_my_job():

    while True:
        job = q.get()
        if job == 'mine':
            return job
        q.put(job)
        time.sleep(random()/2) #preventing deadlocks...

If the order is important you may use multiple Queues for so each message type will be in its own Queue

queues = { 'queue4worker_type1': Queue(),
           'queue4worker_type2': Queue(),
          }
#each worker can now consume only messages for its wanted types ...


问:
OpenCV with Visual Studio 2015 Enterprise
Hello Im trying to use OpenCV 3.0 with Visual Studio 2015 Enterprise but for some reason it is not working, what am I doing wrong ?

First of all I have OpenCV extracted in C:\opencv\ with 7z archive

In Visual Studio Project -> TestProject Properties

Configuration -> All Configuration && Platform -> All Platform

Configuration Properties -> VC++ Directory -> Include Directories => C:\opencv\opencv\build\include

Configuration Properties -> VC++ Directory -> Library Directories => C:\opencv\opencv\build\x86\vc12\lib

Configuration Properties -> C/C++ -> General -> Additional Include Libraries => C:\opencv\opencv\build\include

Configuration Properties -> Linker -> General -> Additional Library Directories => C:\opencv\opencv\build\x86\vc12\bin

Configuration -> Debug && Platform -> All Platform

Configuration Properties -> Linker -> Input -> Additional Dependencies =>

opencv_ts300d.lib

opencv_world300d.lib

Configuration -> Release && Platform -> All Platform

Configuration Properties -> Linker -> Input -> Additional Dependencies =>

opencv_ts300.lib

opencv_world300.lib

Now when I run a sample code I get MSVCP120D.dll is missing and MSVCR120D.dll is missing and cannot open input file 'kernel32.lib' errors. Does anyone had the same problem or know a solution ?

答:
To fix "MSVCP120D.dll is missing and MSVCR120D.dll" please download them
and put here
C:\Windows\System32</p>


问:
converting a string into a double
I am looking for a way to get floating point input from a user.

My way of going about this is to use a self-made getstrn function and plug that into another function which would convert the string into a double.

My safe get string:

```<code>void safeGetString(char arr[], int limit){
    int c, i;
    i = 0;
    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}
</code>```

What would be the best way to write this get_double function?

答:
Any of:

strtod()

atof()

sscanf()

Of these sscanf offers the strongest validation, since the other two return a valid double value of 0.0 if the input cannot be interpreted as a double, while sscanf() returns the number of format specifiers successfully matched to the input. So:

```<code>input_valid = (sscanf( arr, "%lf", value ) != 0 ) ;
</code>```

ContentLicense: CC BY-SA 2.5

Title: converting a string into a double

Body:
I am looking for a way to get floating point input from a user.

My way of going about this is to use a self-made getstrn function and plug that into another function which would convert the string into a double.

My safe get string:

void safeGetString(char arr[], int limit){
    int c, i;
    i = 0;
    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}

What would be the best way to write this get_double function?

Body:
Any of:

strtod()

atof()

sscanf()

Of these sscanf offers the strongest validation, since the other two return a valid double value of 0.0 if the input cannot be interpreted as a double, while sscanf() returns the number of format specifiers successfully matched to the input. So:

input_valid = (sscanf( arr, "%lf", value ) != 0 ) ;


问:
Wordpress: Uploaded file could not be moved - how to edit owner or similar?
After having created a Wordpress website on a test server, I moved it to the clients server. The website works as intended, but now I cannot upload files anymore via the Wordpress media area: I am getting a message "Uploaded file could not be moved to Uploads/.../..." (not sure about the exact English terms here, I use a different language)

Both "servers" are actually just webspaces at different providers - I have no access to the server configuration.

I saw this question and its answers. Now, when I simply set file permissions of the "uploads" folder and all its contents to "777", uploading is possible again, but as is mentioned everywhere, this should not be done for security reasons.

The remaining solution would be to check if the owner of the folder and files is correct. Probably not, but: Where do I see the owner (in an FTP program like Filezilla) and how can I change it? Or what else could I do to solve this problem with the very limited possibilies I have (basically just FTP access, no control over server settings)?

FWIW: Via FTP (Filezilla) I have no problem uploading files to that directory.

答:
Just to let interested users know: I contacted the providers support, they gave me the advice to update the account to a higher PHP version (by putting two lines into .htaccess, which I didn't know was possible), and now the problem is gone - I can upload files again, with the regular 755 setting for file permissions on the "upload folder" and its subfolders.
(BTW: PHP was 5.2(!), now 7)


问:
How to know local report path in rdlc report in c#
I want to check which Report is calling in the application.
Means I want to know the local report path of the rdlc.

I am using now:

```<code>reportViewer.LocalReport.ReportPath = reportpath;
</code>```

But I'mm getting Error like:

An Error Occur during Local Report Processing

答:
try this

```<code>ReportViewer1.LocalReport.DataSources.Add(reportDataset);
    ReportViewer1.LocalReport.ReportPath = Server.MapPath("Reports/RPT_Reports.rdlc");
</code>```

Body:
I want to check which Report is calling in the application.
Means I want to know the local report path of the rdlc.

I am using now:

reportViewer.LocalReport.ReportPath = reportpath;

But I'mm getting Error like:

An Error Occur during Local Report Processing

Body:
try this

ReportViewer1.LocalReport.DataSources.Add(reportDataset);
    ReportViewer1.LocalReport.ReportPath = Server.MapPath("Reports/RPT_Reports.rdlc");


问:
Disable button until checkbox ticked
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

```<code><td>
    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
    <td>
    <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
    </td>
</td>
</tr>
<td class="label1"></td>
<td align="right">
    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</i></button>
</td>
</code>```

答:
Add the attribute disabled to the button initially

```<code> <td>
                                <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
            <td>
            <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
            </td>
                            </td>
                          </tr>
                            <td class="label1"></td>
                            <td align="right">
                                <button type="submit" class="btn btn1" name="terms" id="terms" disabled>Receive</i></button>
                            </td>
</code>```

Title: Disable button until checkbox ticked

Body:
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />

 I agree to the Terms & Conditions

    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</button>

Body:
Add the attribute disabled to the button initially

 <td>
                                <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
            <td>
            <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
            </td>
                            </td>
                          </tr>
                            <td class="label1"></td>
                            <td align="right">
                                <button type="submit" class="btn btn1" name="terms" id="terms" disabled>Receive</i></button>
                            </td>


问:
Android Accelerometer with better accuracy
I'm building an augmented reality app with POI.
Most of the app is done but now I am trying to find a better stabilization of my sensors, in particular the Accelerometer. I have used low pass filter, but POI are still bouncing to much. The thing I was trying to do is get 5 or more readings of accelerometer and then divide it by n. That should give me better readings but i have no idea how to make it. I can make a for loop but I can't just make for(int i=0;  i<n;  i++)  , because i++ should be done only when the value of accelerometer has changed. If I do it with a simple for loop, I will get an error because the loop is done faster then the sensors are changed. The thing i was looking for is a timer that will changed only when the sensors are changed too.

This is what i have done so far:

```<code>static final float ALPHA = 0.15f; // if ALPHA = 1 OR 0, no filter applies.

// low level pass filter, so i can get steadier reading of mobile sensors
// using only accelerometer and compass
protected float[] lowPass(float[] input, float[] output) {
    if (output == null) return input;
    for (int i = 0; i < input.length; i++) {
       output[i] = output[i] + ALPHA * (input[i] - output[i]);
       // output[i] = input[i]*ALPHA + output[i]*(1.0f-ALPHA);
    }

    return output;
}

public void onSensorChanged(SensorEvent event) {

    StringBuilder msg = new StringBuilder(event.sensor.getName())
            .append(" ");
    for (float value : event.values) {
        msg.append("[").append(String.format("%.3f", value)).append("]");
    }

    switch (event.sensor.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
            lastAccelerometer = lowPass(event.values.clone(), lastAccelerometer);
            accelData = msg.toString();
            break;
        case Sensor.TYPE_GYROSCOPE:
            gyroData = msg.toString();
            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            lastCompass = lowPass(event.values.clone(), lastCompass);
            compassData = msg.toString();
            break;
    }

    this.invalidate();

}
</code>```

答:
I found the solution :</p>

```<code>protected float[] getMovingAvg() {
    float [] output = new float [3];
    for( int i = 0; i< moveVector.size(); i++) {
        output[0] += moveVector.get(i)[0];
        output[1] += moveVector.get(i)[1];
        output[2] += moveVector.get(i)[2];

    }
    output[0] = output[0]/moveVector.size();
    output[1] = output[1]/moveVector.size();
    output[2] = output[2]/moveVector.size();

    if(moveVector.size() >= 70) {
       moveVector.remove(0);
    }

    return output;
}
</code>```

Body:
I'm building an augmented reality app with POI.
Most of the app is done but now I am trying to find a better stabilization of my sensors, in particular the Accelerometer. I have used low pass filter, but POI are still bouncing to much. The thing I was trying to do is get 5 or more readings of accelerometer and then divide it by n. That should give me better readings but i have no idea how to make it. I can make a for loop but I can't just make for(int i=0;  i<n;  i++)  , because i++ should be done only when the value of accelerometer has changed. If I do it with a simple for loop, I will get an error because the loop is done faster then the sensors are changed. The thing i was looking for is a timer that will changed only when the sensors are changed too.

This is what i have done so far:

static final float ALPHA = 0.15f; // if ALPHA = 1 OR 0, no filter applies.

// low level pass filter, so i can get steadier reading of mobile sensors
// using only accelerometer and compass
protected float[] lowPass(float[] input, float[] output) {
    if (output == null) return input;
    for (int i = 0; i < input.length; i++) {
       output[i] = output[i] + ALPHA * (input[i] - output[i]);
       // output[i] = input[i]*ALPHA + output[i]*(1.0f-ALPHA);
    }

    return output;
}

public void onSensorChanged(SensorEvent event) {

    StringBuilder msg = new StringBuilder(event.sensor.getName())
            .append(" ");
    for (float value : event.values) {
        msg.append("[").append(String.format("%.3f", value)).append("]");
    }

    switch (event.sensor.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
            lastAccelerometer = lowPass(event.values.clone(), lastAccelerometer);
            accelData = msg.toString();
            break;
        case Sensor.TYPE_GYROSCOPE:
            gyroData = msg.toString();
            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            lastCompass = lowPass(event.values.clone(), lastCompass);
            compassData = msg.toString();
            break;
    }

    this.invalidate();

}

Body:
I found the solution :

protected float[] getMovingAvg() {
    float [] output = new float [3];
    for( int i = 0; i< moveVector.size(); i++) {
        output[0] += moveVector.get(i)[0];
        output[1] += moveVector.get(i)[1];
        output[2] += moveVector.get(i)[2];

    }
    output[0] = output[0]/moveVector.size();
    output[1] = output[1]/moveVector.size();
    output[2] = output[2]/moveVector.size();

    if(moveVector.size() >= 70) {
       moveVector.remove(0);
    }

    return output;
}


问:
DICOM [Storage SCP] : What should be the Associate Response if no proposed presentation context is accepted?
My application is Storage SCP. Third party Storage SCU connects to my application and proposes two presentation contexts. SCP does not support either. What Associate Response should I send in this case?

Set the status of each presentation context to "Rejected - Abstract syntax not supported.", and send Associate Accept. This way, none of the presentation contexts in Associate Response will be accepted. Associate Accept does not make sense here.

Send Associate Reject all together.

I am doing option 2 now, but not sure if this is correct implementation. I searched specifications but could not found anything conclusive. Please mention the location in specifications that clearly discuss about this situation.

答:
AFAIK, there is no explicit rule, but I think it is very clear implicitly by the reasons that the SCP must give for association- and/or presentation context rejection.

Referring to PS 3.8, 7.1.1.9, there is a positive list of valid reasons for association rejection. There is no reason defined which is suitable to indicate that the association is rejected because none of the proposed presentation contexts can be accepted.

For Presentation Context rejection, PS3.8, table 9-18 defines the possible reasons. I suppose that either

```<code>3 - abstract-syntax-not-supported (provider rejection)
</code>```

or

```<code>4 - transfer-syntaxes-not-supported (provider rejection)
</code>```

Is appropriate to express the reason for rejection. In other words, I do not think that your implementation is correct. You should accept the association, reject all presentation contexts and expect the SCU to release / abort the association.

Body:
AFAIK, there is no explicit rule, but I think it is very clear implicitly by the reasons that the SCP must give for association- and/or presentation context rejection.

Referring to PS 3.8, 7.1.1.9, there is a positive list of valid reasons for association rejection. There is no reason defined which is suitable to indicate that the association is rejected because none of the proposed presentation contexts can be accepted.

For Presentation Context rejection, PS3.8, table 9-18 defines the possible reasons. I suppose that either

3 - abstract-syntax-not-supported (provider rejection)

or

4 - transfer-syntaxes-not-supported (provider rejection)

Is appropriate to express the reason for rejection. In other words, I do not think that your implementation is correct. You should accept the association, reject all presentation contexts and expect the SCU to release / abort the association.


问:
SpringRoo 2.0.RC1 - How can i use date Calenderfields in entityFormatExpression and got correct format
date Calendar

When i use date Calender field in entityFormatExpression i got a

```<code>entity jpa --class ~.domain.Pet --sequenceName PET_SEQ --entityFormatExpression "#{name} (#{type}) birthDay: #{birthDay}"
field date --fieldName birthDay --type java.util.Calendar --notNull --dateTimeFormatPattern "dd.MM.yyyy"
</code>```

Log Warning

```<code>2017-03-22 10:43:55.738  WARN - QP: - 6424 --- [io-8082-exec-10] .w.s.m.s.DefaultHandlerExceptionRes
olver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableExcep
tion: Could not write content: Failed to convert from type [org.springframework.roo.petclinic.domain
.Pet] to type [java.lang.String] for value 'Pet {id='1', version='0', sendReminders='false', name='M
imi', weight='4.5', birthDay='java.util.GregorianCalendar[time=1490137200000,areFieldsSet=true,areAl
lFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSa
vings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,of
fset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,st
artDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTi
me=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=2,WEEK_OF
_YEAR=12,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0
,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=0]', ITERABLE_T
O_ADD_CANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!', ITERABLE_TO_REMOVE_C
ANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!'}org.springframework.roo.petc
linic.domain.Pet@1f'; nested exception is org.springframework.expression.spel.SpelEvaluationExceptio
n: EL1001E:(pos 0): Type conversion problem, cannot convert from @javax.validation.constraints.NotNu
ll @javax.persistence.Temporal @org.springframework.format.annotation.DateTimeFormat java.util.Grego
rianCalendar to java.lang.String (through reference chain: io.springlets.data.web.select2.Select2Dat
aWithConversion["results"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException
: Failed to convert from type [org.springframework.roo.petclinic.domain.Pet] to type [java.lang.Stri
ng] for value 'Pet {id='1', version='0', sendReminders='false', name='Mimi', weight='4.5', birthDay=
'java.util.GregorianCalendar[time=1490137200000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,
zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,useDaylight=tru
e,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=36000
00,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600
000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],fi
rstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=4,DAY_
OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=
0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=0]', ITERABLE_TO_ADD_CANT_BE_NULL_MESSAGE='T
he given Iterable of items to add can't be null!', ITERABLE_TO_REMOVE_CANT_BE_NULL_MESSAGE='The give
n Iterable of items to add can't be null!'}org.springframework.roo.petclinic.domain.Pet@1f'; nested
exception is org.springframework.expression.spel.SpelEvaluationException: EL1001E:(pos 0): Type conv
ersion problem, cannot convert from @javax.validation.constraints.NotNull @javax.persistence.Tempora
l @org.springframework.format.annotation.DateTimeFormat java.util.GregorianCalendar to java.lang.Str
ing (through reference chain: io.springlets.data.web.select2.Select2DataWithConversion["results"])
2017-03-22 10:43:55.754  WARN - QP: - 6424 --- [io-8082-exec-10] .w.s.m.s.DefaultHandlerExceptionRes
olver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessa
geNotWritableException: Could not write content: Failed to convert from type [org.springframework.ro
o.petclinic.domain.Pet] to type [java.lang.String] for value 'Pet {id='1', version='0', sendReminder
s='false', name='Mimi', weight='4.5', birthDay='java.util.GregorianCalendar[time=1490137200000,areFi
eldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",of
fset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[i
d=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMont
h=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,en
dDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=20
17,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_
IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFS
ET=0]', ITERABLE_TO_ADD_CANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!', IT
ERABLE_TO_REMOVE_CANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!'}org.spring
framework.roo.petclinic.domain.Pet@1f'; nested exception is org.springframework.expression.spel.Spel
EvaluationException: EL1001E:(pos 0): Type conversion problem, cannot convert from @javax.validation
.constraints.NotNull @javax.persistence.Temporal @org.springframework.format.annotation.DateTimeForm
at java.util.GregorianCalendar to java.lang.String (through reference chain: io.springlets.data.web.
select2.Select2DataWithConversion["results"]); nested exception is com.fasterxml.jackson.databind.Js
onMappingException: Failed to convert from type [org.springframework.roo.petclinic.domain.Pet] to ty
pe [java.lang.String] for value 'Pet {id='1', version='0', sendReminders='false', name='Mimi', weigh
t='4.5', birthDay='java.util.GregorianCalendar[time=1490137200000,areFieldsSet=true,areAllFieldsSet=
true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=36000
00,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=360000
0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWee
k=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,
endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=2,WEEK_OF_YEAR=12,WE
EK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOU
R_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=0]', ITERABLE_TO_ADD_CANT_
BE_NULL_MESSAGE='The given Iterable of items to add can't be null!', ITERABLE_TO_REMOVE_CANT_BE_NULL
_MESSAGE='The given Iterable of items to add can't be null!'}org.springframework.roo.petclinic.domai
n.Pet@1f'; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1001E:
(pos 0): Type conversion problem, cannot convert from @javax.validation.constraints.NotNull @javax.p
ersistence.Temporal @org.springframework.format.annotation.DateTimeFormat java.util.GregorianCalenda
r to java.lang.String (through reference chain: io.springlets.data.web.select2.Select2DataWithConver
sion["results"])
</code>```

When i create a Visit the Pet don't show in List.

date Date

When i use an date Date field and create a Visit the Pet shown in List but the format is not correct.

In Clinic Eaxmpel i have set a birthDay field to Pet and use it in entityFormatExpression

```<code>entity jpa --class ~.domain.Pet --sequenceName PET_SEQ --entityFormatExpression "#{name} (#{type}) birthDay: #{birthDay}"

focus --class ~.domain.Pet
field date --fieldName birthDay --type java.util.Date --notNull --dateTimeFormatPattern "dd.MM.yyyy"
</code>```

I have set dateTimeFormatPattern "dd.MM.yyyy"

In create edit/ view i see

enter image description here

When i create a visit Object i see

enter image description here

This is not the format i used for this field.

答:
The conversion to String when the JSON data is sent to the select2 component is performed by the EntityExpression utilities which are registered in the ConversionService.

Those utilities use the SpEl support to parse the expression and convert the entity to a String. It seems the SpEl expression isn't using or doesn't have access to the ConversionService itself to convert to String the object properties included in the expression.

I've created an issue in the Springlets project to take a look at the problem.

Body:
date Calendar

When i use date Calender field in entityFormatExpression i got a

entity jpa --class ~.domain.Pet --sequenceName PET_SEQ --entityFormatExpression "#{name} (#{type}) birthDay: #{birthDay}"
field date --fieldName birthDay --type java.util.Calendar --notNull --dateTimeFormatPattern "dd.MM.yyyy"

Log Warning

2017-03-22 10:43:55.738  WARN - QP: - 6424 --- [io-8082-exec-10] .w.s.m.s.DefaultHandlerExceptionRes
olver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableExcep
tion: Could not write content: Failed to convert from type [org.springframework.roo.petclinic.domain
.Pet] to type [java.lang.String] for value 'Pet {id='1', version='0', sendReminders='false', name='M
imi', weight='4.5', birthDay='java.util.GregorianCalendar[time=1490137200000,areFieldsSet=true,areAl
lFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSa
vings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,of
fset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,st
artDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTi
me=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=2,WEEK_OF
_YEAR=12,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0
,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=0]', ITERABLE_T
O_ADD_CANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!', ITERABLE_TO_REMOVE_C
ANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!'}org.springframework.roo.petc
linic.domain.Pet@1f'; nested exception is org.springframework.expression.spel.SpelEvaluationExceptio
n: EL1001E:(pos 0): Type conversion problem, cannot convert from @javax.validation.constraints.NotNu
ll @javax.persistence.Temporal @org.springframework.format.annotation.DateTimeFormat java.util.Grego
rianCalendar to java.lang.String (through reference chain: io.springlets.data.web.select2.Select2Dat
aWithConversion["results"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException
: Failed to convert from type [org.springframework.roo.petclinic.domain.Pet] to type [java.lang.Stri
ng] for value 'Pet {id='1', version='0', sendReminders='false', name='Mimi', weight='4.5', birthDay=
'java.util.GregorianCalendar[time=1490137200000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,
zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,useDaylight=tru
e,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=36000
00,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600
000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],fi
rstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=4,DAY_
OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=
0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=0]', ITERABLE_TO_ADD_CANT_BE_NULL_MESSAGE='T
he given Iterable of items to add can't be null!', ITERABLE_TO_REMOVE_CANT_BE_NULL_MESSAGE='The give
n Iterable of items to add can't be null!'}org.springframework.roo.petclinic.domain.Pet@1f'; nested
exception is org.springframework.expression.spel.SpelEvaluationException: EL1001E:(pos 0): Type conv
ersion problem, cannot convert from @javax.validation.constraints.NotNull @javax.persistence.Tempora
l @org.springframework.format.annotation.DateTimeFormat java.util.GregorianCalendar to java.lang.Str
ing (through reference chain: io.springlets.data.web.select2.Select2DataWithConversion["results"])
2017-03-22 10:43:55.754  WARN - QP: - 6424 --- [io-8082-exec-10] .w.s.m.s.DefaultHandlerExceptionRes
olver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessa
geNotWritableException: Could not write content: Failed to convert from type [org.springframework.ro
o.petclinic.domain.Pet] to type [java.lang.String] for value 'Pet {id='1', version='0', sendReminder
s='false', name='Mimi', weight='4.5', birthDay='java.util.GregorianCalendar[time=1490137200000,areFi
eldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",of
fset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[i
d=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMont
h=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,en
dDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=20
17,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_
IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFS
ET=0]', ITERABLE_TO_ADD_CANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!', IT
ERABLE_TO_REMOVE_CANT_BE_NULL_MESSAGE='The given Iterable of items to add can't be null!'}org.spring
framework.roo.petclinic.domain.Pet@1f'; nested exception is org.springframework.expression.spel.Spel
EvaluationException: EL1001E:(pos 0): Type conversion problem, cannot convert from @javax.validation
.constraints.NotNull @javax.persistence.Temporal @org.springframework.format.annotation.DateTimeForm
at java.util.GregorianCalendar to java.lang.String (through reference chain: io.springlets.data.web.
select2.Select2DataWithConversion["results"]); nested exception is com.fasterxml.jackson.databind.Js
onMappingException: Failed to convert from type [org.springframework.roo.petclinic.domain.Pet] to ty
pe [java.lang.String] for value 'Pet {id='1', version='0', sendReminders='false', name='Mimi', weigh
t='4.5', birthDay='java.util.GregorianCalendar[time=1490137200000,areFieldsSet=true,areAllFieldsSet=
true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=36000
00,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=360000
0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWee
k=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,
endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=2,WEEK_OF_YEAR=12,WE
EK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=81,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOU
R_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=0]', ITERABLE_TO_ADD_CANT_
BE_NULL_MESSAGE='The given Iterable of items to add can't be null!', ITERABLE_TO_REMOVE_CANT_BE_NULL
_MESSAGE='The given Iterable of items to add can't be null!'}org.springframework.roo.petclinic.domai
n.Pet@1f'; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1001E:
(pos 0): Type conversion problem, cannot convert from @javax.validation.constraints.NotNull @javax.p
ersistence.Temporal @org.springframework.format.annotation.DateTimeFormat java.util.GregorianCalenda
r to java.lang.String (through reference chain: io.springlets.data.web.select2.Select2DataWithConver
sion["results"])

When i create a Visit the Pet don't show in List.

date Date

When i use an date Date field and create a Visit the Pet shown in List but the format is not correct.

In Clinic Eaxmpel i have set a birthDay field to Pet and use it in entityFormatExpression

entity jpa --class ~.domain.Pet --sequenceName PET_SEQ --entityFormatExpression "#{name} (#{type}) birthDay: #{birthDay}"

focus --class ~.domain.Pet
field date --fieldName birthDay --type java.util.Date --notNull --dateTimeFormatPattern "dd.MM.yyyy"

I have set dateTimeFormatPattern "dd.MM.yyyy"

In create edit/ view i see

enter image description here

When i create a visit Object i see

enter image description here

This is not the format i used for this field.


问:
Invalid JSON response: Bootstrap datatables
I have here a datatables connect with database using codeigniter. The problem here was my datatables wasn't display the output. I check in developer tools/ network if the data through ajax is sent to my controller and it was. Any help will appreciate.

My Controller

```<code>    class Person extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('person_model','person');
    }

    public function index()
    {
        $this->load->helper('url');
        $this->data['title'] = 'Division';
        $this->middle = 'person_view'; // its your view name, change for as per requirement.
        $this->layout();
    }

    public function ajax_list()
    {
        $list = $this->person->get_datatables();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $division) {
            $no++;
            $row = array();
            $row[] = $division->division_code;
            $row[] = $division->division_name;
            $row[] = $division->division_acro;

            //add html for action
            $row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_person('."'".$division->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
                  <a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_person('."'".$division->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';

            $data[] = $row;
        }

        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->person->count_all(),
                        "recordsFiltered" => $this->person->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }
}
</code>```

My Model

```<code>class Person_model extends CI_Model {

    var $table = 'division';
    var $column_order = array('division_code','division_name','division_acro','division_date',null); //set column field database for datatable orderable
    var $column_search = array('division_code','division_name','division_acro'); //set column field database for datatable searchable just firstname , lastname , address are searchable
    var $order = array('id' => 'desc'); // default order

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    private function _get_datatables_query()
    {

        $this->db->from($this->table);

        $i = 0;

        foreach ($this->column_search as $item) // loop column
        {
            if($_POST['search']['value']) // if datatable send POST for search
            {

                if($i===0) // first loop
                {
                    $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
                    $this->db->like($item, $_POST['search']['value']);
                }
                else
                {
                    $this->db->or_like($item, $_POST['search']['value']);
                }

                if(count($this->column_search) - 1 == $i) //last loop
                    $this->db->group_end(); //close bracket
            }
            $i++;
        }

        if(isset($_POST['order'])) // here order processing
        {
            $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        }
        else if(isset($this->order))
        {
            $order = $this->order;
            $this->db->order_by(key($order), $order[key($order)]);
        }
    }

    function get_datatables()
    {
        $this->_get_datatables_query();
        if($_POST['length'] != -1)
        $this->db->limit($_POST['length'], $_POST['start']);
        $query = $this->db->get();
        return $query->result();
    }

    function count_filtered()
    {
        $this->_get_datatables_query();
        $query = $this->db->get();
        return $query->num_rows();
    }

    public function count_all()
    {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }
</code>```

My view script

```<code><script type="text/javascript">

var save_method; //for save method string
var table;

$(document).ready(function() {

    //datatables
    table = $('#table').DataTable({

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.

        // Load data for the table's content from an Ajax source
        "ajax": {
            "url": "<?php echo  ('person/ajax_list')?>",
            "type": "POST"
        },

        //Set column definition initialisation properties.
        "columnDefs": [
        {
            "targets": [ -1 ], //last column
            "orderable": false, //set not orderable
        },
        ],

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

答:
If the server didn't reply to the Ajax request with valid JSON data, we need to know what it did reply with, so we can take corrective action. Typically, the response will consist of an error message from the program on the server which is being used to create the JSON, which will be the starting point for resolving the issue fully.

//I'm using google chrome
1. Hit Ctrl+Shift+I to open developer tools
2. Go to network tab
3. View the ajax response...(Mybe it was an error in your data...
4. Correct any errors

Body:
I have here a datatables connect with database using codeigniter. The problem here was my datatables wasn't display the output. I check in developer tools/ network if the data through ajax is sent to my controller and it was. Any help will appreciate.

My Controller

    class Person extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('person_model','person');
    }

    public function index()
    {
        $this->load->helper('url');
        $this->data['title'] = 'Division';
        $this->middle = 'person_view'; // its your view name, change for as per requirement.
        $this->layout();
    }

    public function ajax_list()
    {
        $list = $this->person->get_datatables();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $division) {
            $no++;
            $row = array();
            $row[] = $division->division_code;
            $row[] = $division->division_name;
            $row[] = $division->division_acro;

            //add html for action
            $row[] = 'id."'".')"> Edit
                  id."'".')"> Delete';

            $data[] = $row;
        }

        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->person->count_all(),
                        "recordsFiltered" => $this->person->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }
}

My Model

class Person_model extends CI_Model {

    var $table = 'division';
    var $column_order = array('division_code','division_name','division_acro','division_date',null); //set column field database for datatable orderable
    var $column_search = array('division_code','division_name','division_acro'); //set column field database for datatable searchable just firstname , lastname , address are searchable
    var $order = array('id' => 'desc'); // default order

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    private function _get_datatables_query()
    {

        $this->db->from($this->table);

        $i = 0;

        foreach ($this->column_search as $item) // loop column
        {
            if($_POST['search']['value']) // if datatable send POST for search
            {

                if($i===0) // first loop
                {
                    $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
                    $this->db->like($item, $_POST['search']['value']);
                }
                else
                {
                    $this->db->or_like($item, $_POST['search']['value']);
                }

                if(count($this->column_search) - 1 == $i) //last loop
                    $this->db->group_end(); //close bracket
            }
            $i++;
        }

        if(isset($_POST['order'])) // here order processing
        {
            $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        }
        else if(isset($this->order))
        {
            $order = $this->order;
            $this->db->order_by(key($order), $order[key($order)]);
        }
    }

    function get_datatables()
    {
        $this->_get_datatables_query();
        if($_POST['length'] != -1)
        $this->db->limit($_POST['length'], $_POST['start']);
        $query = $this->db->get();
        return $query->result();
    }

    function count_filtered()
    {
        $this->_get_datatables_query();
        $query = $this->db->get();
        return $query->num_rows();
    }

    public function count_all()
    {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

My view script


问:
Run script and php after form submission
I have an html form like this:

```<code><form method="get" action="save.php">
<input type="email" id="email" name="email"/>
<input type="submit" name="submit" value="Submit" />
</form>
</code>```

and in save.php i have something like this:

```<code><?php
session_start();

$email = $_REQUEST['email'];
$email_content = "Thank you for your subscription";
mail($email,"Thank you",$email_content);
header("Location:thankyou.php");
?>
</code>```

Now in save.php file i need to send this e-mail but also to echo a script that runs a js function. For example

```<code><?php
    echo "<script>";
    echo "<script src='my_path_to_file/file.js'></script>";
    echo "var subscriberEmail = '" . $email . "';";
    echo "mySubscribe(subscriberEmail);";
    echo "</script>";
 ?>
</code>```

Now, if i place the echoing of the script before mail(), then i don't go to thankyou.php, mail() is not executed, i don't go to thankyou.php but script function works. If i place echoing of script after mail, then mail is sent, i go to thankyou.php but script function is not executed at all.

Any ideas to make both happen?

Thank you in advance

答:
It's becouse echo command send content to browser, and header redirect will never works.

You could try to use comething like that:

```<code><?php
echo "<script>";
echo "<script src='my_path_to_file/file.js'></script>";
echo "var subscriberEmail = '" . $email . "';";
echo "mySubscribe(subscriberEmail);";
echo "document.location.href='thankyou.php';";
echo "</script>";
?>
</code>```

It means, move redirect command from php code to javascript.

Body:
I have an html form like this:

<form method="get" action="save.php">
<input type="email" id="email" name="email"/>
<input type="submit" name="submit" value="Submit" />
</form>

and in save.php i have something like this:

<?php
session_start();

$email = $_REQUEST['email'];
$email_content = "Thank you for your subscription";
mail($email,"Thank you",$email_content);
header("Location:thankyou.php");
?>

Now in save.php file i need to send this e-mail but also to echo a script that runs a js function. For example

<?php
    echo "";
    echo "var subscriberEmail = '" . $email . "';";
    echo "mySubscribe(subscriberEmail);";
    echo "</script>";
 ?>

Now, if i place the echoing of the script before mail(), then i don't go to thankyou.php, mail() is not executed, i don't go to thankyou.php but script function works. If i place echoing of script after mail, then mail is sent, i go to thankyou.php but script function is not executed at all.

Any ideas to make both happen?

Thank you in advance

Body:
It's becouse echo command send content to browser, and header redirect will never works.

You could try to use comething like that:

<?php
echo "<script>";
echo "<script src='my_path_to_file/file.js'></script>";
echo "var subscriberEmail = '" . $email . "';";
echo "mySubscribe(subscriberEmail);";
echo "document.location.href='thankyou.php';";
echo "</script>";
?>

It means, move redirect command from php code to javascript.


问:
Array Size Not Defined? C++
Dumb question. but can you do this.
(these are global variables by the way)

```<code>int size;
double Values[size];
</code>```

If Im getting the SIZE from a file?

I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Size 7).

The compiler complains, but Im wondering if their is some workaround. (these have to stay as global variables btw.

答:
You can, actually :)

C99 allows that. MSVC doesn't support C99, GCC does.

C++ compilers also tend to allow that as an extension (answer yourself if you're OK with depending on compiler extensions). The only requirement is that you need to know size at the moment of declaration of Values.

A std::vector is usually better (and safer and standarised and so on) anyway, unless you really really want that data on the stack.

Title: Array Size Not Defined? C++

Body:
Dumb question. but can you do this.
(these are global variables by the way)

int size;
double Values[size];

If Im getting the SIZE from a file?

I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Size 7).

The compiler complains, but Im wondering if their is some workaround. (these have to stay as global variables btw.


问:
Python os.stat and unicode file names
In my Django application, a user has uploaded a file with a unicode character in the name.

When I'm downloading files, I'm calling :

```<code>os.path.exists(media)
</code>```

to test that the file is there. This, in turn, seems to call

```<code>st = os.stat(path)
</code>```

Which then blows up with the error :

UnicodeEncodeError: 'ascii' codec can't encode character u'\xcf' in position 92: ordinal not in range(128)

What can I do about this? Is there an option to path.exists to handle it?

Update : Actually, all I had to do was encode the argument to exists, ie.

```<code>os.path.exists(media.encode('utf-8')
</code>```

Thanks everyone who answered.

答:
It is easy to get this kind of error when running service (E.g: gunicorn) from Upstart.

To fix that, set env in upstart file:

```<code>env LANG=en_US.UTF-8
env LC_CTYPE=en_US.UTF-8
env LC_ALL=en_US.UTF-8
</code>```

Title: Python os.stat and unicode file names

Body:
In my Django application, a user has uploaded a file with a unicode character in the name.

When I'm downloading files, I'm calling :

os.path.exists(media)

to test that the file is there. This, in turn, seems to call

st = os.stat(path)

Which then blows up with the error :

UnicodeEncodeError: 'ascii' codec can't encode character u'\xcf' in position 92: ordinal not in range(128)

What can I do about this? Is there an option to path.exists to handle it?

Update : Actually, all I had to do was encode the argument to exists, ie.

os.path.exists(media.encode('utf-8')

Thanks everyone who answered.

Body:
It is easy to get this kind of error when running service (E.g: gunicorn) from Upstart.

To fix that, set env in upstart file:

env LANG=en_US.UTF-8
env LC_CTYPE=en_US.UTF-8
env LC_ALL=en_US.UTF-8


问:
Issues with the AccessToken in the React Native FBSDK
I am having trouble with my ability to get the AccessToken in the fbsdk in React Native.

I am calling the core as suggested by Facebook:

```<code>const FBSDKCore = require('react-native-fbsdkcore');
const {
  FBSDKAccessToken,
} = FBSDKCore;
</code>```

And in one scenario I try to write the token in the log as suggested by a similair question stated here on SO.

```<code>    <View>
        <View style={{flex: 1, alignItems: 'center', padding: 50, marginTop: 250}}>
        <View>
          <LoginButton
            publishPermissions={["publish_actions"]}
            onLoginFinished={
              (error, result) => {
                if (error) {
                  alert("login has error: " + result.error);
                } else if (result.isCancelled) {
                  alert("login is cancelled.");
                } else {
                  FBSDKAccessToken.getCurrentAccessToken((token)=> {
                        console.log(token);
                      });
                  Actions.Navigator()
                }
              }
            }
            onLogoutFinished={() => {
              alert("logout.")}}/>
        </View>
        </View>
    </View>
</code>```

This gives me the redscreen "undefined is not an object (evaluating the FBSDKAccessTokenInterface.getCurrentAccessToken)

Trying to pull off something similair in other parts of the app, of course defining the const FBSDKAccessToken first, then calling the userID (which should be a part of the FBSDKCore) as:

```<code><Text style={{fontSize: 18, color:colors.General.navtext}}>{FBSDKAccessToken.userID}</Text>
</code>```

Yields nothing, where I believed it to return the userID of the logged in user. Also, if I try to write out the accesstoken in that same place as:

```<code><Text style={{fontSize: 18, color:colors.General.navtext}}>{FBSDKAccessToken.getCurrentAccessToken()}</Text>
</code>```

I get the same red screen as before.

I tried to look in to the linking of libraries, but that even caused further problem.

Hence, from this, I am pretty stranded and I would really appreciate some feedback on what has gone wrong.

答:
Try this.</p>

```<code>console.log(token.accessToken.toString());
</code>```

Body:
I am having trouble with my ability to get the AccessToken in the fbsdk in React Native.

I am calling the core as suggested by Facebook:

const FBSDKCore = require('react-native-fbsdkcore');
const {
  FBSDKAccessToken,
} = FBSDKCore;

And in one scenario I try to write the token in the log as suggested by a similair question stated here on SO.

    <View>
        <View style={{flex: 1, alignItems: 'center', padding: 50, marginTop: 250}}>
        <View>
          <LoginButton
            publishPermissions={["publish_actions"]}
            onLoginFinished={
              (error, result) => {
                if (error) {
                  alert("login has error: " + result.error);
                } else if (result.isCancelled) {
                  alert("login is cancelled.");
                } else {
                  FBSDKAccessToken.getCurrentAccessToken((token)=> {
                        console.log(token);
                      });
                  Actions.Navigator()
                }
              }
            }
            onLogoutFinished={() => {
              alert("logout.")}}/>
        </View>
        </View>
    </View>

This gives me the redscreen "undefined is not an object (evaluating the FBSDKAccessTokenInterface.getCurrentAccessToken)

Trying to pull off something similair in other parts of the app, of course defining the const FBSDKAccessToken first, then calling the userID (which should be a part of the FBSDKCore) as:

<Text style={{fontSize: 18, color:colors.General.navtext}}>{FBSDKAccessToken.userID}</Text>

Yields nothing, where I believed it to return the userID of the logged in user. Also, if I try to write out the accesstoken in that same place as:

<Text style={{fontSize: 18, color:colors.General.navtext}}>{FBSDKAccessToken.getCurrentAccessToken()}</Text>

I get the same red screen as before.

I tried to look in to the linking of libraries, but that even caused further problem.

Hence, from this, I am pretty stranded and I would really appreciate some feedback on what has gone wrong.

Body:
Try this.

console.log(token.accessToken.toString());


问:
How to use ftruncate in c99 without warning
I want to use ftruncate function in my code. I have to compile with option std=c99. I get warning:

```<code>In function ‘test’:
warning: implicit declaration of function ‘ftruncate’ [-Wimplicit-function-declaration]
</code>```

I tied to find on the Internet any solution which can solve this problem but I don't succeeded in.

I use ftrucnate because I want to clear content of an opened file after I get lock (flock).

答:
FatalError's answer did not work for me. Mostly all you have to do for it to work is: </p>

```<code>#include <unistd.h>
</code>```

Body:
I want to use ftruncate function in my code. I have to compile with option std=c99. I get warning:

In function ‘test’:
warning: implicit declaration of function ‘ftruncate’ [-Wimplicit-function-declaration]

I tied to find on the Internet any solution which can solve this problem but I don't succeeded in.

I use ftrucnate because I want to clear content of an opened file after I get lock (flock).

Body:
FatalError's answer did not work for me. Mostly all you have to do for it to work is:

#include <unistd.h>


问:
Apache .htaccess, subfolder
I have website on Phalcon and everything works fine (I have SSL) but now I would like to have an access to the forum (https://www.example.com/forum/) but I have a problem with the .htaccess configuration.

Phalcon have the specific config:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^www.example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com%{REQUEST_URI} [R=301,L]
    RewriteCond %{HTTPS} !=on
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>
</code>```

What is the correct configuration for home domain and /forum/ folder?

答:
```<code>RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^ "http://www.example.com%{REQUEST_URI}" [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^ "https://%{SERVER_NAME}%{REQUEST_URI}" [R,L]
RewriteCond %{REQUEST_URI} !^/forum/
RewriteRule ^.*$ public/$0 [L]
</code>```

Title: Apache .htaccess, subfolder

Body:
I have website on Phalcon and everything works fine (I have SSL) but now I would like to have an access to the forum (https://www.example.com/forum/) but I have a problem with the .htaccess configuration.

Phalcon have the specific config:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^www.example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com%{REQUEST_URI} [R=301,L]
    RewriteCond %{HTTPS} !=on
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>

What is the correct configuration for home domain and /forum/ folder?


问:
How to resize image in Drupal 7?
I'm working on Drupal 7.

Drupal 7 has inbuilt function image_load() & image_resize(). But it not resizing image. Although it has not source folder & destination folder path.

Can anybody help on this?

答:
```<code>function mymodulename_file_presave ($file) {

    if($file->type=='image')
    {
       $image_file = $file->uri;
       $image_name= $file->filename;
       $file_full_url= file_create_url($image_file);
       $url = $image_file;
       $destination_folder =$image_file;
       $newfname =  $destination_folder;

        if($file->filemime=='image/jpeg')
        {
            $file = fopen ($url, "rb");
            if ($file)
            {
                $filename=$newfname;
                $img = imagecreatefromjpeg($filename);
                header("Content-Type: image/jpeg");
                imagejpeg($img, $filename, 50);
            }
            if ($file)
            {
                fclose($file);
            }
        }
        else if($file->filemime=='image/png')
        {
             $file = fopen ($url, "rb");
            if ($file)
            {
                $filename=$newfname;
                $img = imagecreatefrompng($filename);
                header("Content-Type: image/jpeg");
                imagejpeg($img, $filename, 50);
            }
            if ($file)
            {
                fclose($file);
            }
        }
        else if($file->filemime=='image/gif')
        {
            $file = fopen ($url, "rb");
            if ($file)
            {
                $filename=$newfname;
                $img = imagecreatefrompng($filename);
                header("Content-Type: image/jpeg");
                imagejpeg($img, $filename, 50);
            }
            if ($file)
            {
                fclose($file);
            }
        }
    }
</code>```

Title: How to resize image in Drupal 7?


问:
On Android 5.0 lollipop maybe due to depricated getRunningTask() method
Application is working with in Kitkat version. After lollipop version application is not working properly. I am thinking problem with getRunningTasks() . Could you please give me guidance ,How to overcome this problem.

```<code>public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //Log.d("Detector", "Auto Start" + AppLockerPreference.getInstance(context).isAutoStart());
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){

        if (AppLockerPreference.getInstance(context).isAutoStart()){

            if (AppLockerPreference.getInstance(context).isServiceEnabled()){

                context.startService(new Intent(context, DetectorService.class));

            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);

            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
         Toast.makeText(context, "App------>6", Toast.LENGTH_SHORT).show();
        context.startService(new Intent(context, DetectorService.class));
    }
}
}
</code>```

DetectorService

```<code>public class DetectorService extends Service {
//public static final String ACTION_DETECTOR_SERVICE = "com.gueei.detector.service";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final Class<?>[] mStartForegroundSignature = new Class[] {
    int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
    boolean.class};

private NotificationManager mNM;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

/**
 * This is a wrapper around the new startForeground method, using the older
 * APIs if it is not available.
 */
void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        try {
            mStartForeground.invoke(this, mStartForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        }
        return;
    }

    // Fall back on the old API.
    stopForeground(true);
    mNM.notify(id, notification);
}

/**
 * This is a wrapper around the new stopForeground method, using the older
 * APIs if it is not available.
 */
void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
        mStopForegroundArgs[0] = Boolean.TRUE;
        try {
            mStopForeground.invoke(this, mStopForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        }
        return;
    }

    // Fall back on the old API.  Note to cancel BEFORE changing the
    // foreground state, since we could be killed at that point.
    mNM.cancel(id);
    stopForeground(false);
}

@Override
public void onCreate() {
    //debug: log.i("Detector","Service.Oncreate");
    initConstant();
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    try {
        mStartForeground = getClass().getMethod("startForeground",
                mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground",
                mStopForegroundSignature);
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
}

@Override
public void onDestroy() {
    //debug: log.i("Detector","Service.Ondestroy");
    mThread.interrupt();

    // Make sure our notification is gone.
    stopForegroundCompat(R.string.service_running);
}

 // This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    //debug: log.i("Detector","Service.Onstart");
    handleCommand(intent);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //debug: log.i("Detector","Service.OnStartCommand");
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return Service.START_STICKY;
}

private void handleCommand(Intent intent){
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.service_running);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.statusbar_icon, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, AppLockerActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, text,
                   text, contentIntent);

    startForegroundCompat(R.string.service_running, notification);

    startMonitorThread((ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE));
}

private void startMonitorThread(final ActivityManager am){
    if (mThread!=null)
        mThread.interrupt();

    mThread = new MonitorlogThread(new ActivityStartingHandler(this));
    mThread.start();
}

private static Thread mThread;
private static boolean constantInited = false;
private static Pattern ActivityNamePattern;
private static String logCatCommand;
private static String ClearlogCatCommand;

private void initConstant() {
    //debug: log.i("Detector","Service.OninitConstant");
    if (constantInited) return;
    String pattern = getResources().getString(R.string.activity_name_pattern);
    //debug: log.d("Detector", "pattern: " + pattern);
    ActivityNamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    logCatCommand = getResources().getString(R.string.logcat_command);
    ClearlogCatCommand = getResources().getString(R.string.logcat_clear_command);
}
</code>```

MonitorlogThread

```<code>private class MonitorlogThread extends Thread{

    ActivityStartingListener mListener;
    public MonitorlogThread(ActivityStartingListener listener){
        //debug: log.i("Detector","Monitor//debug: logThread");
        mListener = listener;
    }

    BufferedReader br;
    private Context context;

    @Override
    public void run() {

        //debug: log.i("Detector","RUN!");

        while(!this.isInterrupted() ){

            try {
                Thread.sleep(100);
                ////debug: log.i("Detector","try!");
                //This is the code I use in my service to identify the current foreground application, its really easy:

                ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
                // The first in the list of RunningTasks is always the foreground task.
                 //Toast.makeText(context, "App------>7", Toast.LENGTH_SHORT).show();
                Log.d("Android", "App------>7----"+am);

                //RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

                Log.d("Android", "App------>8----"+foregroundTaskInfo);

                //Toast.makeText(context, "App------>7"+foregroundTaskInfo, Toast.LENGTH_SHORT).show();

                //Thats it, then you can easily access details of the foreground app/activity:
                String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
                PackageManager pm = getBaseContext().getPackageManager();
                PackageInfo foregroundAppPackageInfo = null;
                String foregroundTaskAppName = null;
                String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
                try {
                    foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
                    foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

                    //debug: log.i("Detector",foregroundTaskAppName);
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (mListener!=null){
                    //mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskAppName);
                    mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskActivityName);
                }

              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
        }

}
}
</code>```

答:
Use this code for above 5.0</p>

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
         try {
        UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
        long milliSecs = 60 * 1000;
        Date date = new Date();
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
        if (queryUsageStats.size() > 0) {
            Log.i(TAG, "UsageStats size: " + queryUsageStats.size());
        }
        long recentTime = 0;
        String recentPkg = "";
        for (int i = 0; i < queryUsageStats.size(); i++) {
            UsageStats stats = queryUsageStats.get(i);
            if (i == 0 && !getPackageName().equals(stats.getPackageName())) {
                Log.i(TAG, "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
            }
            if (stats.getLastTimeStamp() > recentTime) {
                String recentTime = stats.getLastTimeStamp();
                String recentPkg = stats.getPackageName();
            }
        };
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Body:
Application is working with in Kitkat version. After lollipop version application is not working properly. I am thinking problem with getRunningTasks() . Could you please give me guidance ,How to overcome this problem.

public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //Log.d("Detector", "Auto Start" + AppLockerPreference.getInstance(context).isAutoStart());
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){

        if (AppLockerPreference.getInstance(context).isAutoStart()){

            if (AppLockerPreference.getInstance(context).isServiceEnabled()){

                context.startService(new Intent(context, DetectorService.class));

            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);

            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
         Toast.makeText(context, "App------>6", Toast.LENGTH_SHORT).show();
        context.startService(new Intent(context, DetectorService.class));
    }
}
}

DetectorService

public class DetectorService extends Service {
//public static final String ACTION_DETECTOR_SERVICE = "com.gueei.detector.service";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final Class<?>[] mStartForegroundSignature = new Class[] {
    int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
    boolean.class};

private NotificationManager mNM;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

/**
 * This is a wrapper around the new startForeground method, using the older
 * APIs if it is not available.
 */
void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        try {
            mStartForeground.invoke(this, mStartForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        }
        return;
    }

    // Fall back on the old API.
    stopForeground(true);
    mNM.notify(id, notification);
}

/**
 * This is a wrapper around the new stopForeground method, using the older
 * APIs if it is not available.
 */
void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
        mStopForegroundArgs[0] = Boolean.TRUE;
        try {
            mStopForeground.invoke(this, mStopForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        }
        return;
    }

    // Fall back on the old API.  Note to cancel BEFORE changing the
    // foreground state, since we could be killed at that point.
    mNM.cancel(id);
    stopForeground(false);
}

@Override
public void onCreate() {
    //debug: log.i("Detector","Service.Oncreate");
    initConstant();
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    try {
        mStartForeground = getClass().getMethod("startForeground",
                mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground",
                mStopForegroundSignature);
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
}

@Override
public void onDestroy() {
    //debug: log.i("Detector","Service.Ondestroy");
    mThread.interrupt();

    // Make sure our notification is gone.
    stopForegroundCompat(R.string.service_running);
}

 // This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    //debug: log.i("Detector","Service.Onstart");
    handleCommand(intent);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //debug: log.i("Detector","Service.OnStartCommand");
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return Service.START_STICKY;
}

private void handleCommand(Intent intent){
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.service_running);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.statusbar_icon, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, AppLockerActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, text,
                   text, contentIntent);

    startForegroundCompat(R.string.service_running, notification);

    startMonitorThread((ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE));
}

private void startMonitorThread(final ActivityManager am){
    if (mThread!=null)
        mThread.interrupt();

    mThread = new MonitorlogThread(new ActivityStartingHandler(this));
    mThread.start();
}

private static Thread mThread;
private static boolean constantInited = false;
private static Pattern ActivityNamePattern;
private static String logCatCommand;
private static String ClearlogCatCommand;

private void initConstant() {
    //debug: log.i("Detector","Service.OninitConstant");
    if (constantInited) return;
    String pattern = getResources().getString(R.string.activity_name_pattern);
    //debug: log.d("Detector", "pattern: " + pattern);
    ActivityNamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    logCatCommand = getResources().getString(R.string.logcat_command);
    ClearlogCatCommand = getResources().getString(R.string.logcat_clear_command);
}

MonitorlogThread

private class MonitorlogThread extends Thread{

    ActivityStartingListener mListener;
    public MonitorlogThread(ActivityStartingListener listener){
        //debug: log.i("Detector","Monitor//debug: logThread");
        mListener = listener;
    }

    BufferedReader br;
    private Context context;

    @Override
    public void run() {

        //debug: log.i("Detector","RUN!");

        while(!this.isInterrupted() ){

            try {
                Thread.sleep(100);
                ////debug: log.i("Detector","try!");
                //This is the code I use in my service to identify the current foreground application, its really easy:

                ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
                // The first in the list of RunningTasks is always the foreground task.
                 //Toast.makeText(context, "App------>7", Toast.LENGTH_SHORT).show();
                Log.d("Android", "App------>7----"+am);

                //RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

                Log.d("Android", "App------>8----"+foregroundTaskInfo);

                //Toast.makeText(context, "App------>7"+foregroundTaskInfo, Toast.LENGTH_SHORT).show();

                //Thats it, then you can easily access details of the foreground app/activity:
                String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
                PackageManager pm = getBaseContext().getPackageManager();
                PackageInfo foregroundAppPackageInfo = null;
                String foregroundTaskAppName = null;
                String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
                try {
                    foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
                    foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

                    //debug: log.i("Detector",foregroundTaskAppName);
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (mListener!=null){
                    //mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskAppName);
                    mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskActivityName);
                }

              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
        }

}
}

Body:
Use this code for above 5.0

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
         try {
        UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
        long milliSecs = 60 * 1000;
        Date date = new Date();
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
        if (queryUsageStats.size() > 0) {
            Log.i(TAG, "UsageStats size: " + queryUsageStats.size());
        }
        long recentTime = 0;
        String recentPkg = "";
        for (int i = 0; i < queryUsageStats.size(); i++) {
            UsageStats stats = queryUsageStats.get(i);
            if (i == 0 && !getPackageName().equals(stats.getPackageName())) {
                Log.i(TAG, "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
            }
            if (stats.getLastTimeStamp() > recentTime) {
                String recentTime = stats.getLastTimeStamp();
                String recentPkg = stats.getPackageName();
            }
        };
    } catch (Exception e) {
        e.printStackTrace();
    }
}