问:
Uploaded file not save in folder
Im using XAMPP to test this codes on my windows laptop and there is no problem. but when i run on my mac book, file that i want upload wasn't save in upload folder. any solution for me?
this is my php code

```<code><?php
$conn=new PDO('mysql:host=localhost; dbname=xxx', 'root', '') or die(mysql_error());
if(isset($_POST['submit'])!=""){

    $title = $_POST['title'];// file title
    $date = $_POST['date'];// file date
    $ref = $_POST['ref'];// file ref
    $ftype = $_POST['ftype'];// file ref
    $from_to = $_POST['from_to'];// person incharge
    $details = $_POST['details'];// details
    $location = $_POST['location'];// file location
    $status = $_POST['status'];// file status

  $name=$_FILES['photo']['name'];
  $size=$_FILES['photo']['size'];
  $type=$_FILES['photo']['type'];
  $temp=$_FILES['photo']['tmp_name'];
  move_uploaded_file($_FILES,"upload/".$name);
$query=$conn->query("INSERT INTO upload(title, date, ref, ftype, from_to, details, location, status, name)VALUES('$title', '$date', '$ref', '$ftype', '$from_to', '$details', '$location', '$status', '$name')");
if($query){
header("location:view.php");
    }
else{
die(mysql_error());
    }
}
?>
</code>```

And this is my form

```<code><form enctype="multipart/form-data" action="" name="form" method="post">

        <table class="table table-bordered table-responsive">

    <tr>
        <td><label class="control-label">Reference Number</label></td>
        <td><input class="form-control" type="text" name="ref" placeholder="Reference Number" required /></td>
    </tr>

    <tr>
        <td><label class="control-label">File Name</label></td>
        <td><input class="form-control" type="text" name="title" placeholder="File Name" required /></td>
    </tr>

    <tr>
        <td><label class="control-label">Type</label></td>
        <td><p><select name="ftype" required >
            <option value="Correspondence">Correspondence</option>
</select></p></td>
    </tr>

    <tr>
        <td><label class="control-label">Date</label></td>
        <td><input class="form-control" type="date" name="date" placeholder="Date" required /></td>
    </tr>
    <tr>

        <td><label class="control-label">Person Incharge</label></td>
        <td><input class="form-control" type="text" name="from_to" placeholder="Person Incharge" required /></td>
    </tr>

        <td><label class="control-label">Details</label></td>
        <td><textarea class="form-control" name="details" placeholder="Details" required ></textarea> </td>
    </tr>

        <td><label class="control-label">Location</label></td>
        <td><p><select name="location" required >
            <option value="Admin">Admin</option>

</select></p></td>
    </tr>

        <td><label class="control-label">Status</label></td>
        <td><p><select name="status" required >
            <option value="Active">Active</option>
</select></p></td>
    </tr>

    <tr>
        <td colspan="2"><p>Attach File<input type="file" name="photo" id="photo" required />
                    <input type="submit" name="submit" id="submit" value="Submit" />

        </td>
    </tr>

    </table>
    </form>
</code>```

答:
It seems you have a problem with your code in this section:

```<code>$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
move_uploaded_file($_FILES,"upload/".$name);
</code>```

move_uploaded_file takes a string for its first parameter, not an associative array. You are passing in the entirety of the $_FILES superglobal. Instead, you need to specify which file to move. You are already setting a variable to the file's tmp_name which is what should be what you pass to move_uploaded_file. Try this updated code.

```<code>$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
move_uploaded_file($temp,"upload/".$name);
</code>```

Title: Uploaded file not save in folder

Body:
Im using XAMPP to test this codes on my windows laptop and there is no problem. but when i run on my mac book, file that i want upload wasn't save in upload folder. any solution for me?
this is my php code

<?php
$conn=new PDO('mysql:host=localhost; dbname=xxx', 'root', '') or die(mysql_error());
if(isset($_POST['submit'])!=""){

    $title = $_POST['title'];// file title
    $date = $_POST['date'];// file date
    $ref = $_POST['ref'];// file ref
    $ftype = $_POST['ftype'];// file ref
    $from_to = $_POST['from_to'];// person incharge
    $details = $_POST['details'];// details
    $location = $_POST['location'];// file location
    $status = $_POST['status'];// file status

  $name=$_FILES['photo']['name'];
  $size=$_FILES['photo']['size'];
  $type=$_FILES['photo']['type'];
  $temp=$_FILES['photo']['tmp_name'];
  move_uploaded_file($_FILES,"upload/".$name);
$query=$conn->query("INSERT INTO upload(title, date, ref, ftype, from_to, details, location, status, name)VALUES('$title', '$date', '$ref', '$ftype', '$from_to', '$details', '$location', '$status', '$name')");
if($query){
header("location:view.php");
    }
else{
die(mysql_error());
    }
}
?>

And this is my form

<form enctype="multipart/form-data" action="" name="form" method="post">

        Reference Number
        <input class="form-control" type="text" name="ref" placeholder="Reference Number" required />

        File Name
        <input class="form-control" type="text" name="title" placeholder="File Name" required />

        Type

<select name="ftype" required >
            <option value="Correspondence">Correspondence</option>
</select>

        Date
        <input class="form-control" type="date" name="date" placeholder="Date" required />

        Person Incharge
        <input class="form-control" type="text" name="from_to" placeholder="Person Incharge" required />

        Details
        <textarea class="form-control" name="details" placeholder="Details" required ></textarea>

        Location

<select name="location" required >
            <option value="Admin">Admin</option>

</select>

        Status

<select name="status" required >
            <option value="Active">Active</option>
</select>

Attach File<input type="file" name="photo" id="photo" required />
                    <input type="submit" name="submit" id="submit" value="Submit" />

    </form>

Body:
It seems you have a problem with your code in this section:

$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
move_uploaded_file($_FILES,"upload/".$name);

move_uploaded_file takes a string for its first parameter, not an associative array. You are passing in the entirety of the $_FILES superglobal. Instead, you need to specify which file to move. You are already setting a variable to the file's tmp_name which is what should be what you pass to move_uploaded_file. Try this updated code.

$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
move_uploaded_file($temp,"upload/".$name);


来源: stackexchange

问:
PowerShell Equivalent for Word ActiveDocument.ConvertNumbersToText
I have a VB script within a Word doc macro that converts autonumber fields to text.  The VB script is as follows:

```<code>Sub ReplaceNumbers()
    ActiveDocument.ConvertNumbersToText
End Sub
</code>```

How can this be launched from within PowerShell to prevent the need to run a macro within Word?  I have tried several things and have been unable to get it to function correctly.

Thanks in advance.

答:
It's going to be a bit different as you're not actually within the context of the "ActiveDocument" so you'd have to open it via the Microsoft Word object, then run createdDocumentObject.ConvertNumbersToText.  Also, you'll want to save the following to a ".VBS" here's an example to be ran when you need it.

```<code>Set objWord = CreateObject("Word.Application")
Set yourDoc = objWord.Documents.Open("c:\YourDocumentHere.doc")

yourDoc.ConvertNumbersToText
yourDoc.Save
objWord.Quit
</code>```

Name this file something like "ConvertNumbersToTextInDocuments.vbs"

Ultimately, from Powershell then you'd need to execute this.

```<code>cscript.exe C:\ConvertNumbersToTextInDocuments.vbs
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a VB script within a Word doc macro that converts autonumber fields to text.  The VB script is as follows:

Sub ReplaceNumbers()
    ActiveDocument.ConvertNumbersToText
End Sub

How can this be launched from within PowerShell to prevent the need to run a macro within Word?  I have tried several things and have been unable to get it to function correctly.

Thanks in advance.

Body:
It's going to be a bit different as you're not actually within the context of the "ActiveDocument" so you'd have to open it via the Microsoft Word object, then run createdDocumentObject.ConvertNumbersToText.  Also, you'll want to save the following to a ".VBS" here's an example to be ran when you need it.

Set objWord = CreateObject("Word.Application")
Set yourDoc = objWord.Documents.Open("c:\YourDocumentHere.doc")

yourDoc.ConvertNumbersToText
yourDoc.Save
objWord.Quit

Name this file something like "ConvertNumbersToTextInDocuments.vbs"

Ultimately, from Powershell then you'd need to execute this.

cscript.exe C:\ConvertNumbersToTextInDocuments.vbs


问:
EF6 application won't store data in SDF database
It's been a while since I used EF and I'm now starting up a small project where I want to create a small database based on my model (classes in Domain folder), so simple EF Code-First.

I've been cracking my head on this, cause for some reason the tables do not get created in the database.

I've ran the project several times and the context does have plenty of seed logic to fill up several tables. The mapping is coded as well, as are the many-to-many relations and the unique constraints.

According to what I could find here the connection string seems correct as well.
It's the first time I'm using SQL Server Compact, as I want it to be an easily deployable WPF app. Maybe I'm overlooking something there?

I've added a screenshot of my environment which should contain all relevant information. If you need more, just ask.

Please help me finding what's wrong or missing, so I can finally start making some progress in this project. I've spend plenty of time trying to get past this hurdle.

答: Look for a copy of your database file in the bin/Debug folder, it will have your data! </p>


问:
Why 0 is omitted in SecFilterForceByteRange , modSecurity?
What is the meaning of SecFilterForceByteRange 1 255, in modSecurity ?
Some web examples provide range 0 255, some 1 255. Why 0 is omitted?

http://www.askapache.com/htaccess/modsecurity-htaccess-tricks/

答:
SecFilterForceByteRange has not been used since ModSecurity v1 which no one should be using anymore!

It has been replaced by validateByteRange in ModSecurity v2.

But to answer your question it will stop the null byte from being allowed in those variables. For most variables the null byte shouldn't be used as this is a string terminator in most languages, so any use of it may be an indicator of an attack attempt by early terminating a string.


问:
Total number of Google Reviews using Google Places API
Now that Google deprecated the user_ratings_total variable in Google Places API, is there a way to get the total number of ratings for a particular business?

I see the answer here user_ratings_total No longer available in google places API. Alternative for getting total number of reviews? , but it suggests using Google My Business API, not Google Places API.

Thanks.

答:
Unfortunately, there's no means to retrieve total user reviews anymore. Below is a list of issue trackers requesting that user_ratings_total be added. The oldest one appears to date back to 2011.

https://issuetracker.google.com/u/1/issues/35820858

https://issuetracker.google.com/u/1/issues/35821787

https://issuetracker.google.com/u/1/issues/35823510

https://issuetracker.google.com/u/1/issues/35828637

Not only has user_ratings_total been removed. But there seems to be no explanation as to why it has been removed. Odds are that Google has no interest in fixing the issue.

EDIT: as of 2019, it's now available in the Google Places API. See answers above.

ContentLicense: CC BY-SA 4.0


问:
Android - How to use SharedPreferences in non-Activity class?
How do you use SharedPreferences in a non-Activity class? I tried making a generic Preferences utility class and importing android.content.Context but Eclipse still wouldn't let me use getSharedPreferences().

答:
use this code to a new class. </p>

```<code>import android.content.Context;
import android.content.SharedPreferences;

/**
   * Created by Atiar Talukdar on 6/5/2017.
*/

public class TemporaryStorageSharedPreference {
protected final static int DEFAULT = 0;
int temp = 0;

public int readSharedPreference(Context context, String spName,String key){
    SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    return temp = sharedPreferences.getInt(key,DEFAULT);
}

public void writeSharedPreference(Context context,String ammount,String spName,String key ){

    SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, DEFAULT);
    editor.commit();
}
}
</code>```

Body:
use this code to a new class.

import android.content.Context;
import android.content.SharedPreferences;

/**
   * Created by Atiar Talukdar on 6/5/2017.
*/

public class TemporaryStorageSharedPreference {
protected final static int DEFAULT = 0;
int temp = 0;

public int readSharedPreference(Context context, String spName,String key){
    SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    return temp = sharedPreferences.getInt(key,DEFAULT);
}

public void writeSharedPreference(Context context,String ammount,String spName,String key ){

    SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, DEFAULT);
    editor.commit();
}
}


问:
Detect installed certificate on iOS 11 device
I have iOS 11 and this code doesn't detect my installed custom certificate:

```<code>- (BOOL)IsMobileConfigInstalled {
    NSString *certPath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"der"];
    NSData *certData = [NSData dataWithContentsOfFile:certPath];
    SecCertificateRef cert = NULL;
    if ([certData length]) {
         cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certData);
        if (cert != NULL) {
            CFStringRef certSummary = SecCertificateCopySubjectSummary(cert);
            NSString *summaryString = [[NSString alloc] initWithString:(__bridge NSString *) certSummary];
            CFRelease(certSummary);
        }
    }
    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust;
    OSStatus err = SecTrustCreateWithCertificates((__bridge CFArrayRef) @[
            (__bridge id) cert
    ], policy, &trust);
    SecTrustResultType trustResult = (SecTrustResultType) -1;
    err = SecTrustEvaluate(trust, &trustResult);
    CFRelease(trust);
    CFRelease(policy);
    CFRelease(cert);
    return kSecTrustResultUnspecified == trustResult;
}
</code>```

What is the problem?

答:
Problem solved.
Apple just "fixed" result in trustResult.

So, now corrent answer: kSecTrustResultProceed

My fixed code version:
Work on ios 10 and 11.

```<code>- (BOOL)IsMobileConfigInstalled {
    NSString *certPath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"der"];
    NSData *certData = [NSData dataWithContentsOfFile:certPath];
    SecCertificateRef cert = NULL;
    if ([certData length]) {
        cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certData);
        if (cert != NULL) {
            CFStringRef certSummary = SecCertificateCopySubjectSummary(cert);
            NSString *summaryString = [[NSString alloc] initWithString:(__bridge NSString *) certSummary];
            CFRelease(certSummary);
        }
    }
    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust;
    OSStatus err = SecTrustCreateWithCertificates((__bridge CFArrayRef) @[
            (__bridge id) cert
    ], policy, &trust);
    SecTrustResultType trustResult = (SecTrustResultType) -1;
    err = SecTrustEvaluate(trust, &trustResult);
    CFRelease(trust);
    CFRelease(policy);
    CFRelease(cert);
    NSString *ver = [[UIDevice currentDevice] systemVersion];
    float ver_float = [ver floatValue];
    if (ver_float >= 11)
        return kSecTrustResultProceed == trustResult;
    return kSecTrustResultUnspecified == trustResult;
}
</code>```

Body:
I have iOS 11 and this code doesn't detect my installed custom certificate:

- (BOOL)IsMobileConfigInstalled {
    NSString *certPath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"der"];
    NSData *certData = [NSData dataWithContentsOfFile:certPath];
    SecCertificateRef cert = NULL;
    if ([certData length]) {
         cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certData);
        if (cert != NULL) {
            CFStringRef certSummary = SecCertificateCopySubjectSummary(cert);
            NSString *summaryString = [[NSString alloc] initWithString:(__bridge NSString *) certSummary];
            CFRelease(certSummary);
        }
    }
    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust;
    OSStatus err = SecTrustCreateWithCertificates((__bridge CFArrayRef) @[
            (__bridge id) cert
    ], policy, &trust);
    SecTrustResultType trustResult = (SecTrustResultType) -1;
    err = SecTrustEvaluate(trust, &trustResult);
    CFRelease(trust);
    CFRelease(policy);
    CFRelease(cert);
    return kSecTrustResultUnspecified == trustResult;
}

What is the problem?

Body:
Problem solved.
Apple just "fixed" result in trustResult.

So, now corrent answer: kSecTrustResultProceed

My fixed code version:
Work on ios 10 and 11.

- (BOOL)IsMobileConfigInstalled {
    NSString *certPath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"der"];
    NSData *certData = [NSData dataWithContentsOfFile:certPath];
    SecCertificateRef cert = NULL;
    if ([certData length]) {
        cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certData);
        if (cert != NULL) {
            CFStringRef certSummary = SecCertificateCopySubjectSummary(cert);
            NSString *summaryString = [[NSString alloc] initWithString:(__bridge NSString *) certSummary];
            CFRelease(certSummary);
        }
    }
    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust;
    OSStatus err = SecTrustCreateWithCertificates((__bridge CFArrayRef) @[
            (__bridge id) cert
    ], policy, &trust);
    SecTrustResultType trustResult = (SecTrustResultType) -1;
    err = SecTrustEvaluate(trust, &trustResult);
    CFRelease(trust);
    CFRelease(policy);
    CFRelease(cert);
    NSString *ver = [[UIDevice currentDevice] systemVersion];
    float ver_float = [ver floatValue];
    if (ver_float >= 11)
        return kSecTrustResultProceed == trustResult;
    return kSecTrustResultUnspecified == trustResult;
}


问:
Ruby on Rails: split string into hash and insert it to a json
I have a model that looks something like:

```<code>  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
},
  :status => "working"
</code>```

With the  metrics field as a json.

And I want to split a string such as:

```<code>"Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"
</code>```

To be named categories under the metrics field so that each category will hold two numbers, the percentage and the number that follows it.
So in the example above it would look like:

```<code>  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
                "categories" => {
            "Home/Personal Finance": [37.00,55],
            "Computers/Internet/Web Design and Development": [13.77,48],
            ...
            }

},
  :status => "working"
</code>```

Basically I want to save the two numbers for each category (maybe there's a better way to store them by the way?).

Either way can split the string with .split(",") but what next?

答:
Dang, Gerry, you're good!

I was going to say:

```<code>  str.split(',').inject({}) do |to_return, split_line|
    split_line.split('=').tap do |line_parts|
      to_return[line_parts[0]] = [line_parts[1].gsub('%','').to_f,line_parts[2].to_i]
    end
    to_return
  end
</code>```

Output:

```<code>  {
    "Home/Personal Finance"=>[37.0, 55],
    "Computers/Internet/Web Design and Development"=>[13.77, 48],
    "News"=>[8.64, 45],
    "Arts/Television"=>[5.23, 42],
    "Arts/Music"=>[2.99, 39],
    "News/Current Events"=>[2.66, 38],
    "Society/Issues"=>[2.47, 38],
    "Computers/Internet/On the Web"=>[2.46, 38],
    "Business/Investing"=>[1.76, 36],
    "Society"=>[1.7, 36]
  }
</code>```

But, as always, yours is cleaner. I'm still learning!

Body:
I have a model that looks something like:

  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
},
  :status => "working"

With the  metrics field as a json.

And I want to split a string such as:

"Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"

To be named categories under the metrics field so that each category will hold two numbers, the percentage and the number that follows it.
So in the example above it would look like:

  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
                "categories" => {
            "Home/Personal Finance": [37.00,55],
            "Computers/Internet/Web Design and Development": [13.77,48],
            ...
            }

},
  :status => "working"

Basically I want to save the two numbers for each category (maybe there's a better way to store them by the way?).

Either way can split the string with .split(",") but what next?

Body:
Dang, Gerry, you're good!

I was going to say:

  str.split(',').inject({}) do |to_return, split_line|
    split_line.split('=').tap do |line_parts|
      to_return[line_parts[0]] = [line_parts[1].gsub('%','').to_f,line_parts[2].to_i]
    end
    to_return
  end

Output:

  {
    "Home/Personal Finance"=>[37.0, 55],
    "Computers/Internet/Web Design and Development"=>[13.77, 48],
    "News"=>[8.64, 45],
    "Arts/Television"=>[5.23, 42],
    "Arts/Music"=>[2.99, 39],
    "News/Current Events"=>[2.66, 38],
    "Society/Issues"=>[2.47, 38],
    "Computers/Internet/On the Web"=>[2.46, 38],
    "Business/Investing"=>[1.76, 36],
    "Society"=>[1.7, 36]
  }

But, as always, yours is cleaner. I'm still learning!


问:
Spring Batch: JdbcPagingItemReader does not work through setSortKeys and cast(id as unsigned)
I am working with Spring Batch version 3.0.7 with Mysql

I had the problem that the person_reader table has the id column defined how varchar and thus the following happens for a simple select ordered:

```<code>id
--
1
10 <--- !!!
2
3
...
</code>```

What is need it is

```<code>id
--
1
2
3
...
10 <--- ok!
...
</code>```

The solution is use ORDER BY cast(id as unsigned)

If I use JdbcCursorItemReader I can use in peace:

```<code>setSql("SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned)");
</code>```

It works fine. Until here all is ok.

Note: for the batch process, is very important read the data in the correct order.

The problem is with JdbcPagingItemReader

First Try:

```<code>    JdbcPagingItemReader<Person> itemReader = new JdbcPagingItemReader<>();
    itemReader.setDataSource(dataSource);
    itemReader.setPageSize(100);
    itemReader.setRowMapper(new PersonRowMapper());

    MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
    pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name");
    pagingQueryProvider.setFromClause("FROM person_reader ORDER BY cast(id as unsigned)");

    Map<String, Order> sortKeys= new HashMap<>();
    sortKeys.put("id", Order.ASCENDING);
    pagingQueryProvider.setSortKeys(sortKeys);

    itemReader.setQueryProvider(pagingQueryProvider);
</code>```

Observe:

setFromClause("FROM person_reader ORDER BY cast(id as unsigned)")

put("id", Order.ASCENDING)

The following error appears:

```<code>org.springframework.jdbc.BadSqlGrammarException: StatementCallback;
bad SQL grammar [SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned) ORDER BY id ASC LIMIT 100];
nested exception is java.sql.SQLSyntaxErrorException:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY id ASC LIMIT 100' at line 1
</code>```

Has sense, the SQL generated SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned) ORDER BY id ASC LIMIT 100 is not correct.

Second Try

```<code>    JdbcPagingItemReader<Person> itemReader = new JdbcPagingItemReader<>();
    itemReader.setDataSource(dataSource);
    itemReader.setPageSize(100);
    itemReader.setRowMapper(new PersonRowMapper());

    MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
    pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name");
    pagingQueryProvider.setFromClause("FROM person_reader");

    Map<String, Order> sortKeys= new HashMap<>();
    sortKeys.put("cast(id as unsigned)", Order.ASCENDING);
    pagingQueryProvider.setSortKeys(sortKeys);

    itemReader.setQueryProvider(pagingQueryProvider);
</code>```

Observe:

setFromClause("FROM person_reader")

put("cast(id as unsigned)", Order.ASCENDING)

The following error appears:

```<code>org.springframework.jdbc.UncategorizedSQLException: StatementCallback;
uncategorized SQLException for SQL [SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned) ASC LIMIT 100];
SQL state [S0022]; error code [0]; Column 'cast(id as unsigned)' not found.;
nested exception is java.sql.SQLException: Column 'cast(id as unsigned)' not found.
</code>```

Has sense about the 'missing' column

Order is an enum and thus it can't be extended.

What is the correct approach?

Alpha

If I use in MySQL's workbench the following:

SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column FROM person_reader ORDER BY sb_sort_column ASC

It works fine. If I use:

```<code>MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column");
pagingQueryProvider.setFromClause("FROM person_reader");

Map<String, Order> sortKeys= new HashMap<>();
sortKeys.put("sb_sort_column", Order.ASCENDING);
pagingQueryProvider.setSortKeys(sortKeys);

itemReader.setQueryProvider(pagingQueryProvider);
</code>```

The following error arises:

```<code>org.springframework.jdbc.BadSqlGrammarException:
PreparedStatementCallback;
bad SQL grammar [SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column FROM person_reader WHERE ((sb_sort_column > ?)) ORDER BY sb_sort_column ASC LIMIT 100];
nested exception is java.sql.SQLSyntaxErrorException:
Unknown column 'sb_sort_column' in 'where clause'
</code>```

From above see carefully the 3rd line about the sql statement generated.

答:
Solution:

The link provided in the comment was useful.
It from:

Spring batch with column alias as sort key - malformed “where” statement

Therefore the correct configuration is:

```<code>    MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
    pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name, sb_sort_column");
    pagingQueryProvider.setFromClause("FROM (SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column FROM person_reader) person_reader");

    Map<String, Order> sortKeys= new HashMap<>();
    sortKeys.put("sb_sort_column", Order.ASCENDING);
    pagingQueryProvider.setSortKeys(sortKeys);
</code>```

Note: be sure to include in the setSelectClause method the alias column, in this case sb_sort_column

Body:
I am working with Spring Batch version 3.0.7 with Mysql

I had the problem that the person_reader table has the id column defined how varchar and thus the following happens for a simple select ordered:

id
--
1
10 <--- !!!
2
3
...

What is need it is

id
--
1
2
3
...
10 <--- ok!
...

The solution is use ORDER BY cast(id as unsigned)

If I use JdbcCursorItemReader I can use in peace:

setSql("SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned)");

It works fine. Until here all is ok.

Note: for the batch process, is very important read the data in the correct order.

The problem is with JdbcPagingItemReader

First Try:

    JdbcPagingItemReader<Person> itemReader = new JdbcPagingItemReader<>();
    itemReader.setDataSource(dataSource);
    itemReader.setPageSize(100);
    itemReader.setRowMapper(new PersonRowMapper());

    MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
    pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name");
    pagingQueryProvider.setFromClause("FROM person_reader ORDER BY cast(id as unsigned)");

    Map<String, Order> sortKeys= new HashMap<>();
    sortKeys.put("id", Order.ASCENDING);
    pagingQueryProvider.setSortKeys(sortKeys);

    itemReader.setQueryProvider(pagingQueryProvider);

Observe:

setFromClause("FROM person_reader ORDER BY cast(id as unsigned)")

put("id", Order.ASCENDING)

The following error appears:

org.springframework.jdbc.BadSqlGrammarException: StatementCallback;
bad SQL grammar [SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned) ORDER BY id ASC LIMIT 100];
nested exception is java.sql.SQLSyntaxErrorException:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY id ASC LIMIT 100' at line 1

Has sense, the SQL generated SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned) ORDER BY id ASC LIMIT 100 is not correct.

Second Try

    JdbcPagingItemReader<Person> itemReader = new JdbcPagingItemReader<>();
    itemReader.setDataSource(dataSource);
    itemReader.setPageSize(100);
    itemReader.setRowMapper(new PersonRowMapper());

    MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
    pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name");
    pagingQueryProvider.setFromClause("FROM person_reader");

    Map<String, Order> sortKeys= new HashMap<>();
    sortKeys.put("cast(id as unsigned)", Order.ASCENDING);
    pagingQueryProvider.setSortKeys(sortKeys);

    itemReader.setQueryProvider(pagingQueryProvider);

Observe:

setFromClause("FROM person_reader")

put("cast(id as unsigned)", Order.ASCENDING)

The following error appears:

org.springframework.jdbc.UncategorizedSQLException: StatementCallback;
uncategorized SQLException for SQL [SELECT id, first_name, last_name FROM person_reader ORDER BY cast(id as unsigned) ASC LIMIT 100];
SQL state [S0022]; error code [0]; Column 'cast(id as unsigned)' not found.;
nested exception is java.sql.SQLException: Column 'cast(id as unsigned)' not found.

Has sense about the 'missing' column

Order is an enum and thus it can't be extended.

What is the correct approach?

Alpha

If I use in MySQL's workbench the following:

SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column FROM person_reader ORDER BY sb_sort_column ASC

It works fine. If I use:

MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column");
pagingQueryProvider.setFromClause("FROM person_reader");

Map<String, Order> sortKeys= new HashMap<>();
sortKeys.put("sb_sort_column", Order.ASCENDING);
pagingQueryProvider.setSortKeys(sortKeys);

itemReader.setQueryProvider(pagingQueryProvider);

The following error arises:

org.springframework.jdbc.BadSqlGrammarException:
PreparedStatementCallback;
bad SQL grammar [SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column FROM person_reader WHERE ((sb_sort_column > ?)) ORDER BY sb_sort_column ASC LIMIT 100];
nested exception is java.sql.SQLSyntaxErrorException:
Unknown column 'sb_sort_column' in 'where clause'

From above see carefully the 3rd line about the sql statement generated.

Body:
Solution:

The link provided in the comment was useful.
It from:

Spring batch with column alias as sort key - malformed “where” statement

Therefore the correct configuration is:

    MySqlPagingQueryProvider pagingQueryProvider = new MySqlPagingQueryProvider();
    pagingQueryProvider.setSelectClause("SELECT id, first_name, last_name, sb_sort_column");
    pagingQueryProvider.setFromClause("FROM (SELECT id, first_name, last_name, cast(id as unsigned) as sb_sort_column FROM person_reader) person_reader");

    Map<String, Order> sortKeys= new HashMap<>();
    sortKeys.put("sb_sort_column", Order.ASCENDING);
    pagingQueryProvider.setSortKeys(sortKeys);

Note: be sure to include in the setSelectClause method the alias column, in this case sb_sort_column


问:
C++ SDK for MTurk GetAccountBalance API call
I'm a little new to C++ and haven't used SDKs at all. I'm trying to use C++ in Visual Studio 2013 recreate the sample API call provided on the developer page of the MTurk requester site that should return the account balance from the sandbox.
Here's the example for python, copied off of the developer page:

```<code>    import boto3

    region_name = 'us-east-1'
    aws_access_key_id = 'YOUR_ACCESS_ID'
    aws_secret_access_key = 'YOUR_SECRET_KEY'

    endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'

    # Uncomment this line to use in production
    # endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com'

    client = boto3.client('mturk',
        endpoint_url = endpoint_url,
        region_name = region_name,
        aws_access_key_id = aws_access_key_id,
        aws_secret_access_key = aws_secret_access_key,
    )

    # This will return $10,000.00 in the MTurk Developer Sandbox
    print client.get_account_balance()['AvailableBalance']
</code>```

So far, I've written this:

```<code>    #include <aws/core/Aws.h>
    #include <aws/core/auth/awscredentialsprovider.h>
    #include <aws/mturk-requester/MTurkClient.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/mturk-requester/model/getaccountbalancerequest.h>
    #include <aws/mturk-requester/model/getaccountbalanceresult.h>
    #include <aws/core/utils/Outcome.h>
    #include <aws/core/http/HttpRequest.h>
    #include <iostream>

    using std::string;
    using std::cout; using std::endl;
    using namespace Aws::Auth;
    using namespace Aws::MTurk;
    using namespace Aws::MTurk::Model;
    using namespace Aws::Client;

    int main(){
        Aws::SDKOptions options;
        Aws::InitAPI(options);

        const char* access_key = "my key"; //I put the right keys in
        const char* secret_access_key = "my secret key";

        ClientConfiguration config;
        config.region = "us_east_1";
        config.endpointOverride = "https://mturk-requester-sandbox.us-east-1.amazonaws.com";
        //Not sure if I need this to force sandbox mode

        //Uncomment this line to use in production
        //config.endpointOverride = "https://mturk-requester.us-east-1.amazonaws.com"

        AWSCredentials creds;
        creds.SetAWSAccessKeyId(access_key);
        creds.SetAWSSecretKey(secret_access_key);
        creds.SetSessionToken("");

        MTurkClient requester = MTurkClient(creds, config);

        //not entirely sure what to do from here:
        GetAccountBalanceResult bal;
        //const GetAccountBalanceRequest& request = GetAccountBalanceRequest();
        //bal.SetAvailableBalance(); If I set it, it'll return what I set

        //This should return $10, 000.00 in the MTurk Developer Sandbox
        cout << bal.GetAvailableBalance() << endl; //outputs empty string
        cout << config.region << endl; //outputs us_east_1
        //requester.GetAccountBalance(request); I feel like this is what I should be using to get the balance?
        cout << creds.GetAWSAccessKeyId() << endl; //outputs the right key

        system("pause");

        Aws::ShutdownAPI(options);
        return 0;
    }
</code>```

Like this, the code compiles and runs with the commented outputs. I've looked through AWS SDK for C++, the documentation, and also through the SDK .cpp and .h files themselves.
Any help about using the SDK to send information to the website would help as well!

答:
You could turn on log by something like:

    Aws::SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;

Also recommend put sdk related code into bracket:

    InitAPI
    {
        //your code here
    }
    ShutdownAPI

And you need something like:

    GetAccountBalanceOutcome outcome = client->GetAccountBalance(request)

APIs are always in the {ServiceName}Client.h.
Check this S3 example https://github.com/singku/aws-sdk-cpp-test

Body:
I'm a little new to C++ and haven't used SDKs at all. I'm trying to use C++ in Visual Studio 2013 recreate the sample API call provided on the developer page of the MTurk requester site that should return the account balance from the sandbox.
Here's the example for python, copied off of the developer page:

    import boto3

    region_name = 'us-east-1'
    aws_access_key_id = 'YOUR_ACCESS_ID'
    aws_secret_access_key = 'YOUR_SECRET_KEY'

    endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'

    # Uncomment this line to use in production
    # endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com'

    client = boto3.client('mturk',
        endpoint_url = endpoint_url,
        region_name = region_name,
        aws_access_key_id = aws_access_key_id,
        aws_secret_access_key = aws_secret_access_key,
    )

    # This will return $10,000.00 in the MTurk Developer Sandbox
    print client.get_account_balance()['AvailableBalance']

So far, I've written this:

    #include <aws/core/Aws.h>
    #include <aws/core/auth/awscredentialsprovider.h>
    #include <aws/mturk-requester/MTurkClient.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/mturk-requester/model/getaccountbalancerequest.h>
    #include <aws/mturk-requester/model/getaccountbalanceresult.h>
    #include <aws/core/utils/Outcome.h>
    #include <aws/core/http/HttpRequest.h>
    #include <iostream>

    using std::string;
    using std::cout; using std::endl;
    using namespace Aws::Auth;
    using namespace Aws::MTurk;
    using namespace Aws::MTurk::Model;
    using namespace Aws::Client;

    int main(){
        Aws::SDKOptions options;
        Aws::InitAPI(options);

        const char* access_key = "my key"; //I put the right keys in
        const char* secret_access_key = "my secret key";

        ClientConfiguration config;
        config.region = "us_east_1";
        config.endpointOverride = "https://mturk-requester-sandbox.us-east-1.amazonaws.com";
        //Not sure if I need this to force sandbox mode

        //Uncomment this line to use in production
        //config.endpointOverride = "https://mturk-requester.us-east-1.amazonaws.com"

        AWSCredentials creds;
        creds.SetAWSAccessKeyId(access_key);
        creds.SetAWSSecretKey(secret_access_key);
        creds.SetSessionToken("");

        MTurkClient requester = MTurkClient(creds, config);

        //not entirely sure what to do from here:
        GetAccountBalanceResult bal;
        //const GetAccountBalanceRequest& request = GetAccountBalanceRequest();
        //bal.SetAvailableBalance(); If I set it, it'll return what I set

        //This should return $10, 000.00 in the MTurk Developer Sandbox
        cout << bal.GetAvailableBalance() << endl; //outputs empty string
        cout << config.region << endl; //outputs us_east_1
        //requester.GetAccountBalance(request); I feel like this is what I should be using to get the balance?
        cout << creds.GetAWSAccessKeyId() << endl; //outputs the right key

        system("pause");

        Aws::ShutdownAPI(options);
        return 0;
    }

Like this, the code compiles and runs with the commented outputs. I've looked through AWS SDK for C++, the documentation, and also through the SDK .cpp and .h files themselves.
Any help about using the SDK to send information to the website would help as well!


问:
Symbol not found: __PyCodecInfo_GetIncrementalDecoder
Since updating from Homebrew Python 2.7.11 (from 2.7.10) I'm suddenly unable to test register my package on PyPi from the PyCharm IDE console.

Running (as an "External Tool")

```<code>python -B setup.py register -r pypitest
</code>```

I now get

```<code>Traceback (most recent call last):
  File "setup.py", line 22, in <module>
    from setuptools import setup
  File "/usr/local/lib/python2.7/site-packages/setuptools/__init__.py", line 12, in <module>
    from setuptools.extension import Extension
  File "/usr/local/lib/python2.7/site-packages/setuptools/extension.py", line 8, in <module>
    from .dist import _get_unpatched
  File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 16, in <module>
    from setuptools.depends import Require
  File "/usr/local/lib/python2.7/site-packages/setuptools/depends.py", line 6, in <module>
    from setuptools import compat
  File "/usr/local/lib/python2.7/site-packages/setuptools/compat.py", line 17, in <module>
    import httplib
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 80, in <module>
    import mimetools
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/mimetools.py", line 6, in <module>
    import tempfile
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tempfile.py", line 32, in <module>
    import io as _io
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/io.py", line 51, in <module>
    import _io
ImportError: dlopen(/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder
  Referenced from: /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
  Expected in: flat namespace
 in /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so

Process finished with exit code 1
</code>```

I'm not sure how to proceed. I only get this issue if I execute from within my IDE's console. If I do it directly at the system command line (Terminal on OS X) I have no problems.

OS X 10.11.3; Homebrew Python 2.7.11; PyCharm 5.0.3

答:
Another quick workaround if you don't mind sticking with Python 2.7.10 is to specify the path of the Python interpreter executable that will be used for the virtualenv. On OSX that path is usually /usr/bin/python:

```<code>virtualenv venv --python=/usr/bin/python
</code>```

Body:
Since updating from Homebrew Python 2.7.11 (from 2.7.10) I'm suddenly unable to test register my package on PyPi from the PyCharm IDE console.

Running (as an "External Tool")

python -B setup.py register -r pypitest

I now get

Traceback (most recent call last):
  File "setup.py", line 22, in <module>
    from setuptools import setup
  File "/usr/local/lib/python2.7/site-packages/setuptools/__init__.py", line 12, in <module>
    from setuptools.extension import Extension
  File "/usr/local/lib/python2.7/site-packages/setuptools/extension.py", line 8, in <module>
    from .dist import _get_unpatched
  File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 16, in <module>
    from setuptools.depends import Require
  File "/usr/local/lib/python2.7/site-packages/setuptools/depends.py", line 6, in <module>
    from setuptools import compat
  File "/usr/local/lib/python2.7/site-packages/setuptools/compat.py", line 17, in <module>
    import httplib
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 80, in <module>
    import mimetools
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/mimetools.py", line 6, in <module>
    import tempfile
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tempfile.py", line 32, in <module>
    import io as _io
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/io.py", line 51, in <module>
    import _io
ImportError: dlopen(/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder
  Referenced from: /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
  Expected in: flat namespace
 in /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so

Process finished with exit code 1

I'm not sure how to proceed. I only get this issue if I execute from within my IDE's console. If I do it directly at the system command line (Terminal on OS X) I have no problems.

OS X 10.11.3; Homebrew Python 2.7.11; PyCharm 5.0.3

Body:
Another quick workaround if you don't mind sticking with Python 2.7.10 is to specify the path of the Python interpreter executable that will be used for the virtualenv. On OSX that path is usually /usr/bin/python:

virtualenv venv --python=/usr/bin/python


问:
Eigen for c++ calculating wrong eigenvalue
So I am using Eigen for C++ in code blocks to calculate eigenvalues for my matrices. The specific part of the code that deals with this is as follows:-

```<code>EigenSolver<MatrixXd> b(B,false);
cout<<" Eigen values are: \n "<<b.eigenvalues()<<"\n";
</code>```

The problem I have been encountering is is that one of the eigenvalues calculated for my matrix B is nowhere close to the actual eigenvalue I found on calculator.vhex.net.

For example, for the matrix

1 0 0 x

0 1 x 0

0 x 1 y

x 0 y 1

where x = -1/sqrt(2) and y = -0.5 , the eigenvalues are 0, 0.5, 1.5 and 2.

However, my code calculates them to be -4.25e-016 , 0.5, 1.5 and 2.

I also tried this for a 5x5 matrix which should have had an eigenvalue 4e-06 , but the code calculated it as 1.4413e-017 .

What could be the reason(s) for this? Are they approximations?
My guess is memory issues and that a double type value of square root of 2 will not exactly equal to the square root of 2, but I am not sure about this.

What could be a possible fix for this?

答:
Additionally to what @drglove said, for symmetric (or selfadjoint) Eigenvalue problems you should use the SelfAdjointEigenSolver:

```<code>SelfAdjointEigenSolver<MatrixXd> b(B,EigenvaluesOnly);
</code>```

This gives of course still only a numerical solution, so you will still get solutions with a limited precision.

Body:
So I am using Eigen for C++ in code blocks to calculate eigenvalues for my matrices. The specific part of the code that deals with this is as follows:-

EigenSolver<MatrixXd> b(B,false);
cout<<" Eigen values are: \n "<<b.eigenvalues()<<"\n";

The problem I have been encountering is is that one of the eigenvalues calculated for my matrix B is nowhere close to the actual eigenvalue I found on calculator.vhex.net.

For example, for the matrix

1 0 0 x

0 1 x 0

0 x 1 y

x 0 y 1

where x = -1/sqrt(2) and y = -0.5 , the eigenvalues are 0, 0.5, 1.5 and 2.

However, my code calculates them to be -4.25e-016 , 0.5, 1.5 and 2.

I also tried this for a 5x5 matrix which should have had an eigenvalue 4e-06 , but the code calculated it as 1.4413e-017 .

What could be the reason(s) for this? Are they approximations?
My guess is memory issues and that a double type value of square root of 2 will not exactly equal to the square root of 2, but I am not sure about this.

What could be a possible fix for this?

Body:
Additionally to what @drglove said, for symmetric (or selfadjoint) Eigenvalue problems you should use the SelfAdjointEigenSolver:

SelfAdjointEigenSolver<MatrixXd> b(B,EigenvaluesOnly);

This gives of course still only a numerical solution, so you will still get solutions with a limited precision.


问:
Get field values using reflection
I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

```<code>import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}
</code>```

}

EX.class

```<code>public class EX {

private String value;

public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value
 *            the value to set
 */
public void setValue(String value) {
    this.value = value;
}
</code>```

}

答:
You can create instance from class object and that can be used in field get value.</p>

```<code> Class modelClass = Class.forName("com.gati.stackoverflow.EX");
    final Field field = modelClass.getDeclaredField("value");
    field.setAccessible(true);
    Object modelInstance=modelClass.newInstance();
    field.get(modelInstance);
</code>```

Title: Get field values using reflection

Body:
I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}

}

EX.class

public class EX {

private String value;

public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value
 *            the value to set
 */
public void setValue(String value) {
    this.value = value;
}

}

Body:
You can create instance from class object and that can be used in field get value.

 Class modelClass = Class.forName("com.gati.stackoverflow.EX");
    final Field field = modelClass.getDeclaredField("value");
    field.setAccessible(true);
    Object modelInstance=modelClass.newInstance();
    field.get(modelInstance);


问:
pythonpath and omniORB
In README file of omniORBpy-3.4 is written that I have to set PYTHONPATH as

```<code>set PYTHONPATH=%PYTHONPATH%;%TOP%\lib\python;%TOP%\lib\x86_win32
</code>```

Where %TOP% is the top-level omniORBpy directory. (Windows machine)

I have done that and reboot my machine but when I try to run *.py files which have a line like

```<code>import omniORB
</code>```

it gives me an error that no such module omniORB.
What I should do?

答:
Not sure here, but I don't think, that changes made to the environment via a batch script will persist across reboots. Try setting the variable via the Workstation properties (sorry, I have no Windows machine at hand, and cannot give more than a few general directions):

Right click on the Workstation icon on your desktop.
Select "Manage..." (I think it was)

Somewhere in the advanced settings, you can modify environment variables (no need to reboot, but you may have to fire up a new CMD.EXE afterwards, as running apps might not get the change).

Alternatively, you can create a small batch script to start you application, and make it modify the environment before the application is started (I think, this is, what the README actually suggests)

ContentLicense: CC BY-SA 2.5

Title: pythonpath and omniORB

Body:
In README file of omniORBpy-3.4 is written that I have to set PYTHONPATH as

set PYTHONPATH=%PYTHONPATH%;%TOP%\lib\python;%TOP%\lib\x86_win32

Where %TOP% is the top-level omniORBpy directory. (Windows machine)

I have done that and reboot my machine but when I try to run *.py files which have a line like

import omniORB

it gives me an error that no such module omniORB.
What I should do?


问:
Removing from complex custom array
I have array of custom objects

```<code>var shopList = [String: [ShopItem]]()
</code>```

Custom class

```<code>class ShopItem {
var id = ""
var name = ""
var quantity = 0.0
var price = 0.0
var category = ""

init(id: String, name: String, quantity: Double, price: Double, category: String) {
    self.id = id
    self.name = name
    self.quantity = quantity
    self.price = price
    self.category = category
}

var uom: String {

    return "шт."
}

var total: Double {
    return quantity * price
}
</code>```

}

What is right way to remove object from array?
I tried to do it way below

```<code>extension ShopItem: Equatable {}
func ==(left: ShopItem, right: ShopItem) -> Bool {
return left.id == right.id
}
</code>```

But as you see I got error :(

答:
Due to value semantics (objects are copied rather than referenced) the value object is immutable. Even if you assign value to a variable the object is not removed in the shopList dictionary.

You need to remove the object directly in the dictionary (the code is Swift 3)

```<code>func removeItem(item: ShopItem) {
    for (key, value) in shopList {
        if let index = value.index(of: item) {
            shopList[key]!.remove(at: index)
        }
    }
}
</code>```

Title: Removing from complex custom array

Body:
I have array of custom objects

var shopList = [String: [ShopItem]]()

Custom class

class ShopItem {
var id = ""
var name = ""
var quantity = 0.0
var price = 0.0
var category = ""

init(id: String, name: String, quantity: Double, price: Double, category: String) {
    self.id = id
    self.name = name
    self.quantity = quantity
    self.price = price
    self.category = category
}

var uom: String {

    return "шт."
}

var total: Double {
    return quantity * price
}

}

What is right way to remove object from array?
I tried to do it way below

extension ShopItem: Equatable {}
func ==(left: ShopItem, right: ShopItem) -> Bool {
return left.id == right.id
}

But as you see I got error :(

Body:
Due to value semantics (objects are copied rather than referenced) the value object is immutable. Even if you assign value to a variable the object is not removed in the shopList dictionary.

You need to remove the object directly in the dictionary (the code is Swift 3)

func removeItem(item: ShopItem) {
    for (key, value) in shopList {
        if let index = value.index(of: item) {
            shopList[key]!.remove(at: index)
        }
    }
}


问:
Core Data Fetch Predicate "not contains"?
I have two core data entities "Books" and "BookLists" where "Books" objects have a to-many relationship with "BookLists" objects and am trying to fetch all existing objects of type Books which do not have a relationship to a given object of type BooksList.

I'm fetching all Books objects which DO have a relationship to that BookLists object with the predicate

```<code>NSPredicate(format: "booklists CONTAINS %@)", list)
</code>```

so what I'm looking for is basically a negative version of this predicate but I can't find anything on "negative contains" predicates anywhere.

答:
After Martin R linked me to a similar question, I was able to find the solution for my problem by using a subquery:</p>

```<code>NSPredicate(format: "SUBQUERY(booklists, $a, $a CONTAINS %@).@count == 0", list)
</code>```

Body:
I have two core data entities "Books" and "BookLists" where "Books" objects have a to-many relationship with "BookLists" objects and am trying to fetch all existing objects of type Books which do not have a relationship to a given object of type BooksList.

I'm fetching all Books objects which DO have a relationship to that BookLists object with the predicate

NSPredicate(format: "booklists CONTAINS %@)", list)

so what I'm looking for is basically a negative version of this predicate but I can't find anything on "negative contains" predicates anywhere.

Body:
After Martin R linked me to a similar question, I was able to find the solution for my problem by using a subquery:

NSPredicate(format: "SUBQUERY(booklists, $a, $a CONTAINS %@).@count == 0", list)


问:
Why does sqlSave from the RODBC package fail when appending data to an existing table?
I have created an empty table in a mysql database with the following specification

```<code>    Field          Type Null Key           Default                       Extra
1      Id       int(11)   NO PRI              <NA>              auto_increment
2    Date     timestamp   NO     CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
3 Country   varchar(45)  YES                  <NA>
4   Brand   varchar(45)  YES                  <NA>
5   Value decimal(10,0)  YES                  <NA>
</code>```

Now I would like to use sqlSave from RODBC package to append data in a data frame to this table. My data frame looks like this

```<code>     Id       Date Country  Brand Value
591 591 2013-06-22      DK bet365    44
603 603 2013-09-14      DK bet365    69
362 362 2009-01-31      DK bet365    22
296 296 2013-08-31      DK unibet    33
216 216 2012-02-18      DK unibet    24
261 261 2012-12-29      DK unibet    28
326 326 2008-05-24      DK bet365    18
521 521 2012-02-18      DK bet365    71
494 494 2011-08-13      DK bet365    44
558 558 2012-11-03      DK bet365    68
</code>```

and can be recreated by

```<code>mydf<-structure(list(Id = c(591L, 603L, 362L, 296L, 216L, 261L, 326L, 521L, 494L, 558L),
                 Date = c("2013-06-22", "2013-09-14", "2009-01-31", "2013-08-31", "2012-02-18", "2012-12-29", "2008-05-24", "2012-02-18", "2011-08-13", "2012-11-03"), Country = c("DK", "DK", "DK", "DK", "DK", "DK", "DK", "DK", "DK", "DK"),
                 Brand = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
                                   .Label = c("unibet", "bet365", "betsafe"),
                                   class = "factor"),
                 Value = c(44, 69, 22, 33, 24, 28, 18, 71, 44, 68)),
            .Names = c("Id", "Date", "Country", "Brand", "Value"),
            row.names = c(591L, 603L, 362L, 296L, 216L, 261L, 326L, 521L, 494L, 558L),
            class = "data.frame")
</code>```

I then run the following command

```<code>sqlSave(channel, dat=mydf, tablename="GoogleTrends", rownames=FALSE, append=TRUE)
</code>```

which results in an error:

```<code>Error in odbcUpdate(channel, query, mydata, coldata[m, ], test = test,  :
  missing columns in »data«
</code>```

I've tried adding varTypes but still no luck. I've also tried with sqlUpdate but cannot get that to work either. To be clear, I can easily make this work if I allow sqlSave to create the table itself. So I guess there's some convertion problem but I cannot detect it. Anyone knows how to solve this?

答: I ran into a very similar issue and found from here  Problems with RODBC sqlSave that turning fast=F resolves the problem. </p>

Body:
I have created an empty table in a mysql database with the following specification

    Field          Type Null Key           Default                       Extra
1      Id       int(11)   NO PRI              <NA>              auto_increment
2    Date     timestamp   NO     CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
3 Country   varchar(45)  YES                  <NA>
4   Brand   varchar(45)  YES                  <NA>
5   Value decimal(10,0)  YES                  <NA>

Now I would like to use sqlSave from RODBC package to append data in a data frame to this table. My data frame looks like this

     Id       Date Country  Brand Value
591 591 2013-06-22      DK bet365    44
603 603 2013-09-14      DK bet365    69
362 362 2009-01-31      DK bet365    22
296 296 2013-08-31      DK unibet    33
216 216 2012-02-18      DK unibet    24
261 261 2012-12-29      DK unibet    28
326 326 2008-05-24      DK bet365    18
521 521 2012-02-18      DK bet365    71
494 494 2011-08-13      DK bet365    44
558 558 2012-11-03      DK bet365    68

and can be recreated by

mydf<-structure(list(Id = c(591L, 603L, 362L, 296L, 216L, 261L, 326L, 521L, 494L, 558L),
                 Date = c("2013-06-22", "2013-09-14", "2009-01-31", "2013-08-31", "2012-02-18", "2012-12-29", "2008-05-24", "2012-02-18", "2011-08-13", "2012-11-03"), Country = c("DK", "DK", "DK", "DK", "DK", "DK", "DK", "DK", "DK", "DK"),
                 Brand = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
                                   .Label = c("unibet", "bet365", "betsafe"),
                                   class = "factor"),
                 Value = c(44, 69, 22, 33, 24, 28, 18, 71, 44, 68)),
            .Names = c("Id", "Date", "Country", "Brand", "Value"),
            row.names = c(591L, 603L, 362L, 296L, 216L, 261L, 326L, 521L, 494L, 558L),
            class = "data.frame")

I then run the following command

sqlSave(channel, dat=mydf, tablename="GoogleTrends", rownames=FALSE, append=TRUE)

which results in an error:

Error in odbcUpdate(channel, query, mydata, coldata[m, ], test = test,  :
  missing columns in »data«

I've tried adding varTypes but still no luck. I've also tried with sqlUpdate but cannot get that to work either. To be clear, I can easily make this work if I allow sqlSave to create the table itself. So I guess there's some convertion problem but I cannot detect it. Anyone knows how to solve this?


问:
.net web service hosted within my application
I'm migrating an old Delphi application that I wrote into C#. The application is a datalogger that exposes logged data requests via a SOAP web service interface.

The web service is contained with the delphi graphical windows application, i.e. no need to run a web server like IIS, etc I just run the application and it's up and running under the hood.

I'm looking to do the same in my c# Windows form application, I can find loads of resources on writing web services that are ultimately hosted within IIS but am struggling to find a solution for a self contained web service within my application.

Does anyone have any suggestions or can point me towards any resources on this?

The web service does not neceserily have to be SOAP, REST is fine (in fact probably prefered).

答:
The System.Web.Hosting namespace allows you to host ASP.Net pages without using IIS within your applications. I have never used it to host web services but I found a tutorial that seems to provide a guide on doing this-

http://msdn.microsoft.com/en-us/magazine/cc163879.aspx


问:
Override default function in typescript class
I have made this button class in typescript. I have given it a "default" function to handle click events. But what if i instead want to be to pass a function as an argument and call the passed one on click instead?

Here the code:

```<code>abstract class BaseButton {

  element:HTMLElement;
  label:string;

  constructor(element:HTMLElement, label:string) {
    console.log(this);
    this.element = element;
    this.label = label;
    this.init();
  }

  init():void {
    this.setText(this.label);
    this.addListeners();
  }

  setText(label:string):void {
    this.element.innerHTML = label;
  }

  kill():void {
    this.removeListeners();
  }

  addListeners():void {
    this.element.addEventListener("mouseover", this.onMouseOver);
    this.element.addEventListener("click", this.onClick);
    this.element.addEventListener("mouseout", this.onMouseOut);
    this.element.addEventListener('touchstart', this.onTouchStart);
    this.element.addEventListener('touchmove', this.onTouchMove);
    this.element.addEventListener('touchcancel', this.onTouchCancel);
    this.element.addEventListener('touchend', this.onTouchEnd);
  }

  removeListeners():void {
    this.element.removeEventListener("mouseover", this.onMouseOver);
    this.element.removeEventListener("click", this.onClick);
    this.element.removeEventListener("mouseout", this.onMouseOut);
    this.element.removeEventListener('touchstart', this.onTouchStart);
    this.element.removeEventListener('touchmove', this.onTouchMove);
    this.element.removeEventListener('touchcancel', this.onTouchCancel);
    this.element.removeEventListener('touchend', this.onTouchEnd);
  }

  onTouchStart():void {

  }

  onTouchMove():void {

  }

  onTouchCancel():void {

  }

  onTouchEnd():void {

  }

  onMouseOver():void {
    console.log('mouse over');
  }

  onMouseOut():void {
    console.log('mouse out');
  }

  abstract onClick(event:Event):void
}

class Button extends BaseButton {

  element:HTMLElement;
  label:string;
  callback:any;

  constructor(element:HTMLElement, label:string, callback?: () => void) {
    super(element,label);
    this.element = element;
    this.label = label;
    this.callback = callback;
  }

  onClick(event:Event):void {
    if (this.callback) {
      console.log('ddd');
      this.callback();
    }
  }
}

const el = document.getElementById('btn');
const button = new Button(el,'Click');

const ell = document.getElementById('btnn');
const buttonn = new Button(ell,'Click');

const elll = document.getElementById('btnnn');
const buttonnn = new Button(elll,'Click', () => {
  alert('fff');
});
</code>```

答:
You are losing the this reference inside of the onClick function of the subclass when the following event handler runs in the base class:

```<code>this.element.addEventListener("click", this.onClick)
</code>```

Normally this could be solved by using an arrow function:

```<code>class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);
  }

  onClick = (event: Event) => {
    if (this.callback) {
      this.callback();
    }
  }
}
</code>```

But in this particular case you'll get the following error if you try to define it in the subclass:

Class 'BaseButton' defines instance member function 'onClick', but
  extended class 'Button' defines it as instance member property.

And if you try to define an onClick arrow function in the subclass's constructor:

```<code>class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);

    this.onClick = () => {
      // ...
    }
  }
}
</code>```

You'll get the following error:

Non-abstract class 'Button' does not implement inherited abstract
  member 'onClick' from class 'BaseButton'

And if you try to create a stub method just to make the error go away, and create the real method as an arrow function in the constructor:

```<code>class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);

    this.onClick = () => {
      // ...
    }
  }

  onClick(event: Event) { }
}
</code>```

It won't work because the base class would pass the wrong onClick function reference to addEventListener because that code runs before the subclass's constructor.

Here is one workaround. Bind this in the base class by creating a separate function there which calls this.onClick(), and keep a reference to that new function so you can de-register it.

```<code>abstract class BaseButton {
  private onClickBound;

  constructor(protected element: HTMLElement, protected label: string) {
    this.init();
  }

  init(): void {
    this.addListeners();
  }

  kill(): void {
    this.removeListeners();
  }

  addListeners(): void {
    this.onClickBound = (e: Event) => this.onClick(e);

    // Or you can do this:
    // this.onClickBound = this.onClick.bind(this)

    this.element.addEventListener("click", this.onClickBound);
  }

  removeListeners(): void {
    this.element.removeEventListener("click", this.onClickBound);
  }

  abstract onClick(event: Event);
}

class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);
  }

  onClick(event: Event) {
    if (this.callback) {
      this.callback();
    }
  }
}
</code>```

I'll try to come up with a cleaner solution as I'm not crazy about this one.

Body:
I have made this button class in typescript. I have given it a "default" function to handle click events. But what if i instead want to be to pass a function as an argument and call the passed one on click instead?

Here the code:

abstract class BaseButton {

  element:HTMLElement;
  label:string;

  constructor(element:HTMLElement, label:string) {
    console.log(this);
    this.element = element;
    this.label = label;
    this.init();
  }

  init():void {
    this.setText(this.label);
    this.addListeners();
  }

  setText(label:string):void {
    this.element.innerHTML = label;
  }

  kill():void {
    this.removeListeners();
  }

  addListeners():void {
    this.element.addEventListener("mouseover", this.onMouseOver);
    this.element.addEventListener("click", this.onClick);
    this.element.addEventListener("mouseout", this.onMouseOut);
    this.element.addEventListener('touchstart', this.onTouchStart);
    this.element.addEventListener('touchmove', this.onTouchMove);
    this.element.addEventListener('touchcancel', this.onTouchCancel);
    this.element.addEventListener('touchend', this.onTouchEnd);
  }

  removeListeners():void {
    this.element.removeEventListener("mouseover", this.onMouseOver);
    this.element.removeEventListener("click", this.onClick);
    this.element.removeEventListener("mouseout", this.onMouseOut);
    this.element.removeEventListener('touchstart', this.onTouchStart);
    this.element.removeEventListener('touchmove', this.onTouchMove);
    this.element.removeEventListener('touchcancel', this.onTouchCancel);
    this.element.removeEventListener('touchend', this.onTouchEnd);
  }

  onTouchStart():void {

  }

  onTouchMove():void {

  }

  onTouchCancel():void {

  }

  onTouchEnd():void {

  }

  onMouseOver():void {
    console.log('mouse over');
  }

  onMouseOut():void {
    console.log('mouse out');
  }

  abstract onClick(event:Event):void
}

class Button extends BaseButton {

  element:HTMLElement;
  label:string;
  callback:any;

  constructor(element:HTMLElement, label:string, callback?: () => void) {
    super(element,label);
    this.element = element;
    this.label = label;
    this.callback = callback;
  }

  onClick(event:Event):void {
    if (this.callback) {
      console.log('ddd');
      this.callback();
    }
  }
}

const el = document.getElementById('btn');
const button = new Button(el,'Click');

const ell = document.getElementById('btnn');
const buttonn = new Button(ell,'Click');

const elll = document.getElementById('btnnn');
const buttonnn = new Button(elll,'Click', () => {
  alert('fff');
});

Body:
You are losing the this reference inside of the onClick function of the subclass when the following event handler runs in the base class:

this.element.addEventListener("click", this.onClick)

Normally this could be solved by using an arrow function:

class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);
  }

  onClick = (event: Event) => {
    if (this.callback) {
      this.callback();
    }
  }
}

But in this particular case you'll get the following error if you try to define it in the subclass:

Class 'BaseButton' defines instance member function 'onClick', but
  extended class 'Button' defines it as instance member property.

And if you try to define an onClick arrow function in the subclass's constructor:

class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);

    this.onClick = () => {
      // ...
    }
  }
}

You'll get the following error:

Non-abstract class 'Button' does not implement inherited abstract
  member 'onClick' from class 'BaseButton'

And if you try to create a stub method just to make the error go away, and create the real method as an arrow function in the constructor:

class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);

    this.onClick = () => {
      // ...
    }
  }

  onClick(event: Event) { }
}

It won't work because the base class would pass the wrong onClick function reference to addEventListener because that code runs before the subclass's constructor.

Here is one workaround. Bind this in the base class by creating a separate function there which calls this.onClick(), and keep a reference to that new function so you can de-register it.

abstract class BaseButton {
  private onClickBound;

  constructor(protected element: HTMLElement, protected label: string) {
    this.init();
  }

  init(): void {
    this.addListeners();
  }

  kill(): void {
    this.removeListeners();
  }

  addListeners(): void {
    this.onClickBound = (e: Event) => this.onClick(e);

    // Or you can do this:
    // this.onClickBound = this.onClick.bind(this)

    this.element.addEventListener("click", this.onClickBound);
  }

  removeListeners(): void {
    this.element.removeEventListener("click", this.onClickBound);
  }

  abstract onClick(event: Event);
}

class Button extends BaseButton {
  constructor(element: HTMLElement, label: string, private callback?: () => void) {
    super(element, label);
  }

  onClick(event: Event) {
    if (this.callback) {
      this.callback();
    }
  }
}

I'll try to come up with a cleaner solution as I'm not crazy about this one.


问:
QCoreApplication.processEvents behavior
I'm doing work where timing is extremely important, and have a question about the behavior of processEvents(). When I call processEvents(), is it run on a seperate thread/process, such that it may still be running as more of my code is executed?

If not, is there any chance that my code continues executing after processEvents() but before all the pixels on my monitor are updated to the newest scene (perhaps because the operating system handles pixel drawing)? Pseudo code below

```<code>app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.drawScene()
app.processEvents() #Force window to update to scene
print("Hi!") #Is there any chance of this being called before my screen's pixels are all set to the newest scene?
</code>```

If the code after processEvents() does run before the screen's pixels are all updated, is there a way to guarantee that the screen is updated before continuing?

答:
QCoreApplication::processEvents() runs in the same thread as you call it from, it does not use a seperate thread. It will process all events currently queued up in the event queue. If there is an event of type QEvent::Paint in the queue, it will trigger a repaint of the window. Your drawScene() will probably put a paint event into the event queue, by directly or indirectly calling QWidget::update().

So yes, a call to processEvents() will finish a pending repaint and only return once the repaint event has been processed.

FWIW, QProgressDialog::setValue() internally calls processEvents() to make sure the progress bar is updated, so this has to work there as well.

The only reason I can think of that would cause the pixels not to be shown is the platform-specific code in the so-called platform plugin doing something asynchronous when repainting. One would need to double-check the platform plugin code of the OS you are using to be absolutely sure.

This actually seems to be the case on X11, which is async. Check the docs for QTest::qWaitForWindowExposed - internally it calls processEvents() in a loop, until QWindow::isExposed() returns true. So at least for initially showing windows, you need to run processEvents() in a loop to make sure the window is actually shown. I do not know if the same is needed for repainting.
See the section "Visibility and Windowing System Exposure" in the docs of QWindow for more details.

Title: QCoreApplication.processEvents behavior

Body:
I'm doing work where timing is extremely important, and have a question about the behavior of processEvents(). When I call processEvents(), is it run on a seperate thread/process, such that it may still be running as more of my code is executed?

If not, is there any chance that my code continues executing after processEvents() but before all the pixels on my monitor are updated to the newest scene (perhaps because the operating system handles pixel drawing)? Pseudo code below

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.drawScene()
app.processEvents() #Force window to update to scene
print("Hi!") #Is there any chance of this being called before my screen's pixels are all set to the newest scene?

If the code after processEvents() does run before the screen's pixels are all updated, is there a way to guarantee that the screen is updated before continuing?


问:
What's the right Fluent NHibernate ConventionBuilder for differing name on child-parent? for brownfield systems too
What code need to go here:

```<code>,ConventionBuilder.HasMany.Always(x =>
          x.Key.Column( /* what code need to go here? */ ))
</code>```

Aside from making this...

```<code>public virtual Person Owner { get; set; }
</code>```

...to(which is ideal only on greenfield systems):

```<code>public virtual Person Person { get; set; }
</code>```

How can I prevent NHibernate from producing the extraneous Person_id in its DDL creation?

Note the Person_id was produced by NH(or FNH?) even there's already an owner_ref, and note the two references:

```<code>create table contact (contact_id int4 not null,
                      number text, type text, owner_ref int4,
                      Person_id int4, primary key (contact_id));
create table person (person_id int4 not null, person_name text not null, birthdate timestamp not null, primary key (person_id));
alter table contact
      add constraint FK38B7242018FA494F
      foreign key (owner_ref) references person;
alter table contact
      add constraint FK38B724202B329A0D
      foreign key (Person_id) references person;
</code>```

I tried this just to make sure that it's feasible to prevent extraneous reference

```<code>,ConventionBuilder.HasMany.Always(x => x.Key.Column("owner_ref"))
</code>```

Here's NHibernate DDL Creation when I add that ConventionBuilder:

```<code>create table contact (contact_id int4 not null, number text, type text,
                      owner_ref int4, primary key (contact_id));
create table person (person_id int4 not null, person_name text not null, birthdate timestamp not null, primary key (person_id));
alter table contact
      add constraint FK38B7242018FA494F
      foreign key (owner_ref) references person;
</code>```

Note there are no more Person_id field, and there's only one references now, which is correct. So it prevent duplicate references, it's possible, but what I still doesn't know is how to change the KeyColumn's name of the collection(IList<Contact>) under Person in ConventionBuilder

Another way is to just change the KeyColumn in ClassMap directly, prevents duplicate reference in contact table...

```<code>HasMany(x => x.Contacts).Inverse().KeyColumn("owner_ref");
</code>```

..., achieved the same SQL as above, but it's better if I can make it automatic on ConventionBuilder.

How can I tell NHibernate from producing two references? Here's the mapping code (note this: public virtual Person Owner { get; set; }.  It's not Person Person { get; set; }

```<code>    public class Person
    {
        public virtual int PersonId { get; set; }

        public virtual string PersonName { get; set; }
        public virtual DateTime Birthdate { get; set; }

        public virtual IList<Contact> Contacts { get; set; }
    }

    public class Contact
    {
        public virtual Person Owner { get; set; }

        public virtual int ContactId { get; set; }
        public virtual string Number { get; set; }
        public virtual string Type { get; set; }
    }

    public class PersonMap : ClassMap<Person>
    {
        public PersonMap()
        {

            Id(x => x.PersonId);
            Map(x => x.PersonName).Not.Nullable();
            Map(x => x.Birthdate).Not.Nullable();
            HasMany(x => x.Contacts).Inverse();
        }
    }

    public class ContactMap : ClassMap<Contact>
    {
        public ContactMap()
        {
            References(x => x.Owner);
            Id(x => x.ContactId).GeneratedBy.Sequence("contact_contact_id_seq");
            Map(x => x.Number);
            Map(x => x.Type);
        }

    }
</code>```

What's the right ConventionBuilder on that design pattern("_ref" suffix for child table's field referencing parent table). That potentially happen on brownfield systems too.

答:
You can't make it automatic. NH can't know that you want to use the same foreign key for the two references.

EDIT theoretical solution:

You need to pass the inverse property somehow, because this is the missing part.

```<code>ConventionBuilder
  .HasMany(x => x.Contacts)
  .KeyColumn(x => GetColumnNameOf((Contact c) => c.Owner));
</code>```

I don't know how to implement it to get this syntax, but this is basically the information you need to pass. If you are lucky you can obtain the Type (Contact) by the compiler from the property you are mapping.

Ideally, you get it like this:

```<code>ConventionBuilder
  .HasMany(x => x.Contacts)
  .InverseOf(c => c.Owner));
</code>```

Body:
What code need to go here:

,ConventionBuilder.HasMany.Always(x =>
          x.Key.Column( /* what code need to go here? */ ))

Aside from making this...

public virtual Person Owner { get; set; }

...to(which is ideal only on greenfield systems):

public virtual Person Person { get; set; }

How can I prevent NHibernate from producing the extraneous Person_id in its DDL creation?

Note the Person_id was produced by NH(or FNH?) even there's already an owner_ref, and note the two references:

create table contact (contact_id int4 not null,
                      number text, type text, owner_ref int4,
                      Person_id int4, primary key (contact_id));
create table person (person_id int4 not null, person_name text not null, birthdate timestamp not null, primary key (person_id));
alter table contact
      add constraint FK38B7242018FA494F
      foreign key (owner_ref) references person;
alter table contact
      add constraint FK38B724202B329A0D
      foreign key (Person_id) references person;

I tried this just to make sure that it's feasible to prevent extraneous reference

,ConventionBuilder.HasMany.Always(x => x.Key.Column("owner_ref"))

Here's NHibernate DDL Creation when I add that ConventionBuilder:

create table contact (contact_id int4 not null, number text, type text,
                      owner_ref int4, primary key (contact_id));
create table person (person_id int4 not null, person_name text not null, birthdate timestamp not null, primary key (person_id));
alter table contact
      add constraint FK38B7242018FA494F
      foreign key (owner_ref) references person;

Note there are no more Person_id field, and there's only one references now, which is correct. So it prevent duplicate references, it's possible, but what I still doesn't know is how to change the KeyColumn's name of the collection(IList<Contact>) under Person in ConventionBuilder

Another way is to just change the KeyColumn in ClassMap directly, prevents duplicate reference in contact table...

HasMany(x => x.Contacts).Inverse().KeyColumn("owner_ref");

..., achieved the same SQL as above, but it's better if I can make it automatic on ConventionBuilder.

How can I tell NHibernate from producing two references? Here's the mapping code (note this: public virtual Person Owner { get; set; }.  It's not Person Person { get; set; }

    public class Person
    {
        public virtual int PersonId { get; set; }

        public virtual string PersonName { get; set; }
        public virtual DateTime Birthdate { get; set; }

        public virtual IList<Contact> Contacts { get; set; }
    }

    public class Contact
    {
        public virtual Person Owner { get; set; }

        public virtual int ContactId { get; set; }
        public virtual string Number { get; set; }
        public virtual string Type { get; set; }
    }

    public class PersonMap : ClassMap<Person>
    {
        public PersonMap()
        {

            Id(x => x.PersonId);
            Map(x => x.PersonName).Not.Nullable();
            Map(x => x.Birthdate).Not.Nullable();
            HasMany(x => x.Contacts).Inverse();
        }
    }

    public class ContactMap : ClassMap<Contact>
    {
        public ContactMap()
        {
            References(x => x.Owner);
            Id(x => x.ContactId).GeneratedBy.Sequence("contact_contact_id_seq");
            Map(x => x.Number);
            Map(x => x.Type);
        }

    }

What's the right ConventionBuilder on that design pattern("_ref" suffix for child table's field referencing parent table). That potentially happen on brownfield systems too.

Body:
You can't make it automatic. NH can't know that you want to use the same foreign key for the two references.

EDIT theoretical solution:

You need to pass the inverse property somehow, because this is the missing part.

ConventionBuilder
  .HasMany(x => x.Contacts)
  .KeyColumn(x => GetColumnNameOf((Contact c) => c.Owner));

I don't know how to implement it to get this syntax, but this is basically the information you need to pass. If you are lucky you can obtain the Type (Contact) by the compiler from the property you are mapping.

Ideally, you get it like this:

ConventionBuilder
  .HasMany(x => x.Contacts)
  .InverseOf(c => c.Owner));


问:
MySQL query is very slow when adding JOIN into WHERE
The following query runs quickly except when I add in the 'areacode.hours = 2'. Instead of taking a second it now takes close to a minute.

```<code>SELECT lead.id, first, last, lead.phone, valid_phone, mobile_phone
FROM lead
LEFT JOIN dnt ON dnt.phone = lead.phone
LEFT JOIN areacode ON areacode.code = LEFT(lead.phone, 3)
LEFT JOIN campaign ON campaign.id = lead.campaign_id
WHERE dnt.id IS NULL
AND campaign.lft BETWEEN 0 AND 1000
AND lead.datetime BETWEEN '2017-06-01 00:00:00' AND '2017-06-01 23:59:59'
AND areacode.hours = 2
GROUP BY lead.phone
ORDER BY lead.phone DESC
LIMIT 1,1000
</code>```

Results of EXPLAIN

```<code>1   SIMPLE  lead    index   campaign_id,datetime    phone   13  NULL    181181  Using where
1   SIMPLE  campaign    eq_ref  PRIMARY PRIMARY 4   data3_db.lead.campaign_id   1   Using where
1   SIMPLE  areacode    ref code,hours  code    11  func    1   Using index condition; Using where
1   SIMPLE  dnt ref phone   phone   12  data3_db.lead.phone 1   Using where; Using index; Not exists
</code>```

答:
Your where clause limits are being executed after the joins complete.  This will result in your left joins acting like INNER joins.  I would recommend moving the limits for those tables on the right side of a left join to the joins themselves; so the limits are applied before the join occurs. (or as part of it)

Exception would be if you're checking for Null on a field; That could remain in the where clause.  but you have no way to distinguish between dnt.ids which are are  null in the table, and those which are null as part of the left join if you put it in the where clause.  However, given this is an "ID" field I'll assume it can't be null and leaving it in the where makes sense.

At times the compiler may attempt to apply the filter after the join when you have thousands of records * 4 tables you record growth could be large; by moving the limits to occur before/on join, the engine can reduce the temporary datset it has to build before it filters out the records. On Inner joins this doesn't matter but on outer joins it can not only effect performance; but desired results.

```<code>SELECT lead.id, first, last, lead.phone, valid_phone, mobile_phone
FROM lead
LEFT JOIN dnt
  ON dnt.phone = lead.phone
LEFT JOIN areacode
  ON areacode.code = LEFT(lead.phone, 3)
 AND areacode.hours = 2
LEFT JOIN campaign
  ON campaign.id = lead.campaign_id
 AND campaign.lft BETWEEN 0 AND 1000
WHERE lead.datetime BETWEEN '2017-06-01 00:00:00' AND '2017-06-01 23:59:59'
  AND dnt.id IS NULL
GROUP BY lead.phone
ORDER BY lead.phone DESC
LIMIT 1,1000
</code>```

If that still doesn't produce the desired results and time, then i'd look at desired indexes.

Body:
The following query runs quickly except when I add in the 'areacode.hours = 2'. Instead of taking a second it now takes close to a minute.

SELECT lead.id, first, last, lead.phone, valid_phone, mobile_phone
FROM lead
LEFT JOIN dnt ON dnt.phone = lead.phone
LEFT JOIN areacode ON areacode.code = LEFT(lead.phone, 3)
LEFT JOIN campaign ON campaign.id = lead.campaign_id
WHERE dnt.id IS NULL
AND campaign.lft BETWEEN 0 AND 1000
AND lead.datetime BETWEEN '2017-06-01 00:00:00' AND '2017-06-01 23:59:59'
AND areacode.hours = 2
GROUP BY lead.phone
ORDER BY lead.phone DESC
LIMIT 1,1000

Results of EXPLAIN

1   SIMPLE  lead    index   campaign_id,datetime    phone   13  NULL    181181  Using where
1   SIMPLE  campaign    eq_ref  PRIMARY PRIMARY 4   data3_db.lead.campaign_id   1   Using where
1   SIMPLE  areacode    ref code,hours  code    11  func    1   Using index condition; Using where
1   SIMPLE  dnt ref phone   phone   12  data3_db.lead.phone 1   Using where; Using index; Not exists

Body:
Your where clause limits are being executed after the joins complete.  This will result in your left joins acting like INNER joins.  I would recommend moving the limits for those tables on the right side of a left join to the joins themselves; so the limits are applied before the join occurs. (or as part of it)

Exception would be if you're checking for Null on a field; That could remain in the where clause.  but you have no way to distinguish between dnt.ids which are are  null in the table, and those which are null as part of the left join if you put it in the where clause.  However, given this is an "ID" field I'll assume it can't be null and leaving it in the where makes sense.

At times the compiler may attempt to apply the filter after the join when you have thousands of records * 4 tables you record growth could be large; by moving the limits to occur before/on join, the engine can reduce the temporary datset it has to build before it filters out the records. On Inner joins this doesn't matter but on outer joins it can not only effect performance; but desired results.

SELECT lead.id, first, last, lead.phone, valid_phone, mobile_phone
FROM lead
LEFT JOIN dnt
  ON dnt.phone = lead.phone
LEFT JOIN areacode
  ON areacode.code = LEFT(lead.phone, 3)
 AND areacode.hours = 2
LEFT JOIN campaign
  ON campaign.id = lead.campaign_id
 AND campaign.lft BETWEEN 0 AND 1000
WHERE lead.datetime BETWEEN '2017-06-01 00:00:00' AND '2017-06-01 23:59:59'
  AND dnt.id IS NULL
GROUP BY lead.phone
ORDER BY lead.phone DESC
LIMIT 1,1000

If that still doesn't produce the desired results and time, then i'd look at desired indexes.


问:
How to add datetime picker in angular4 CLI project
I need help with date time picker. I have tried https://github.com/dalelotts/angular-bootstrap-datetimepicker in angular4 but not able to show properly. In other words it is not working at all.

I tried to add following in .angularcli.json file, still not able to make it work.

```<code>     "styles": [
            "../node_modules/bootstrap/dist/css/bootstrap.min.css",
            "styles.css",
            "../node_modules/angular-bootstrap-datetimepicker/src/css/datetimepicker.css"
          ],
          "scripts": [
            "../node_modules/jquery/dist/jquery.js",
            "../node_modules/angular/angular.min.js",
            "../node_modules/moment/moment.js",
            "../node_modules/angular-bootstrap-datetimepicker/src/js/datetimepicker.js",
            "../node_modules/angular-bootstrap-datetimepicker/src/js/datetimepicker.templates.js"
          ]
</code>```

答:
I am a big fan of PrimeNG. They have good documentation and the components are easy to use.

Check out their Date Time Picker

Body:
I need help with date time picker. I have tried https://github.com/dalelotts/angular-bootstrap-datetimepicker in angular4 but not able to show properly. In other words it is not working at all.

I tried to add following in .angularcli.json file, still not able to make it work.

     "styles": [
            "../node_modules/bootstrap/dist/css/bootstrap.min.css",
            "styles.css",
            "../node_modules/angular-bootstrap-datetimepicker/src/css/datetimepicker.css"
          ],
          "scripts": [
            "../node_modules/jquery/dist/jquery.js",
            "../node_modules/angular/angular.min.js",
            "../node_modules/moment/moment.js",
            "../node_modules/angular-bootstrap-datetimepicker/src/js/datetimepicker.js",
            "../node_modules/angular-bootstrap-datetimepicker/src/js/datetimepicker.templates.js"
          ]