问:
set a chosen image-file-input as a featured image from wp frontend
SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.

```<code>//insert attachments
    if ($_FILES) {
    foreach ($_FILES as $file => $array) {
        $newupload = insert_attachment($file,$pid);
        }
        }

 //attachment helper function
 function insert_attachment($file_handler,$post_id,$setthumb='false') {
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
        }
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');

        $attach_id = media_handle_upload( $file_handler, $post_id );
        //set post thumbnail
        if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
        return $attach_id;//you will need to comment out this line if you use my solution
            }
</code>```

The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.

If it matters, here is the html that is used in the form, pretty standard.

```<code><input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>
</code>```

REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.

Bottomline is that I do not have an issue with setting post-thumbnail
  but question is about having a choice to choose any of the uploaded
  images as post-thumbnail or at least the first image, instead of the
  last image as set by the current code.

PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.

This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.

```<code>$attachments = get_children(array(
            'post_parent' => $pid,
            'post_status' => 'inherit',
            'post_type' => 'attachment',
            'post_mime_type' => 'image',
            'order' => 'ASC',
            'orderby' => 'ID'
        ));
        if ($attachments) {
            foreach ($attachments as $attachment) {
                set_post_thumbnail($pid, $attachment->ID);
                break;
            }
</code>```

FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.

答:
We can set post featured image from frontend using following function,
simple you need to call this function

post_imgs_update($new_post_id);

after creating new post. and add following function in functions.php

```<code>if ( ! function_exists( 'post_imgs_update' ) ) :
        function post_imgs_update($new_post_id) {

            $data = array();
            $attachment_ids = array();
            // code for save featured image
            if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){  // here nonce text is "image_upload" you need to add in form
                    $files = reArrayFiles($_FILES['files']);

                if(!empty($_FILES['files'])){
                    //$i = 0;
                    $set_featured_img = 0 ;

                    foreach( $files as $file ){
                        if( is_array($file) ){
                            $attachment_id = upload_user_file( $file, basename($file['name']) );
                            if ( is_numeric($attachment_id) ) {
                                if ($set_featured_img == '0') {
                                    set_post_thumbnail($new_post_id, $attachment_id);
                                    $set_featured_img++;
                                    $attachment_ids[] = $attachment_id;
                                }
                                else{
                                    $attachment_ids[] = $attachment_id;
                                }

                            }
                        }
                    }
                    //add to array
                    $mediaurl = array();
                    foreach ($attachment_ids as $img_id) {
                        $imgurl = wp_get_attachment_url( $img_id );
                        $image_gallery[$img_id] = $imgurl;
                    }

                    update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery);      // 2nd arg field key
                }

            }
            else {
                    $data['status'] = false;
                    $data['message'] = __('Nonce verify failed','realestate');
            }

            return $new_post_id;

        }
    endif;

    if ( ! function_exists( 'reArrayFiles' ) ) :
        function reArrayFiles(&$file_post) {
            $file_ary = array();
            $file_count = count($file_post['name']);
            $file_keys = array_keys($file_post);
            for ($i=0; $i<$file_count; $i++) {
                foreach ($file_keys as $key) {
                    $file_ary[$i][$key] = $file_post[$key][$i];
                }
            }
            return $file_ary;
        }
    endif;

    if ( ! function_exists( 'upload_user_file' ) ) :
        function upload_user_file( $file = array(), $title = false ) {
            require_once ABSPATH.'wp-admin/includes/admin.php';
            $file_return = wp_handle_upload($file, array('test_form' => false));
            if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
                return false;
            }else{
                $filename = $file_return['file'];
                $attachment = array(
                    'post_mime_type' => $file_return['type'],
                    'post_content' => '',
                    'post_type' => 'attachment',
                    'post_status' => 'inherit',
                    'guid' => $file_return['url']
                );
                if($title){
                    $attachment['post_title'] = $title;
                }
                $attachment_id = wp_insert_attachment( $attachment, $filename );
                require_once(ABSPATH . 'wp-admin/includes/image.php');

                $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
                wp_update_attachment_metadata( $attachment_id, $attachment_data );
                if( 0 < intval( $attachment_id ) ) {
                    return $attachment_id;
                }
            }
            return false;
        }
    endif;

    function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
        $attachurlarray = array();
        // check to make sure its a successful upload
        if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');

        $attach_id = media_handle_upload( $file_handler, $post_id );
        return $attach_id;
    }
</code>```

Body:
SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.

//insert attachments
    if ($_FILES) {
    foreach ($_FILES as $file => $array) {
        $newupload = insert_attachment($file,$pid);
        }
        }

 //attachment helper function
 function insert_attachment($file_handler,$post_id,$setthumb='false') {
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
        }
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');

        $attach_id = media_handle_upload( $file_handler, $post_id );
        //set post thumbnail
        if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
        return $attach_id;//you will need to comment out this line if you use my solution
            }

The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.

If it matters, here is the html that is used in the form, pretty standard.

<input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>

REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.

Bottomline is that I do not have an issue with setting post-thumbnail
  but question is about having a choice to choose any of the uploaded
  images as post-thumbnail or at least the first image, instead of the
  last image as set by the current code.

PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.

This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.

$attachments = get_children(array(
            'post_parent' => $pid,
            'post_status' => 'inherit',
            'post_type' => 'attachment',
            'post_mime_type' => 'image',
            'order' => 'ASC',
            'orderby' => 'ID'
        ));
        if ($attachments) {
            foreach ($attachments as $attachment) {
                set_post_thumbnail($pid, $attachment->ID);
                break;
            }

FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.

Body:
We can set post featured image from frontend using following function,
simple you need to call this function

post_imgs_update($new_post_id);

after creating new post. and add following function in functions.php

if ( ! function_exists( 'post_imgs_update' ) ) :
        function post_imgs_update($new_post_id) {

            $data = array();
            $attachment_ids = array();
            // code for save featured image
            if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){  // here nonce text is "image_upload" you need to add in form
                    $files = reArrayFiles($_FILES['files']);

                if(!empty($_FILES['files'])){
                    //$i = 0;
                    $set_featured_img = 0 ;

                    foreach( $files as $file ){
                        if( is_array($file) ){
                            $attachment_id = upload_user_file( $file, basename($file['name']) );
                            if ( is_numeric($attachment_id) ) {
                                if ($set_featured_img == '0') {
                                    set_post_thumbnail($new_post_id, $attachment_id);
                                    $set_featured_img++;
                                    $attachment_ids[] = $attachment_id;
                                }
                                else{
                                    $attachment_ids[] = $attachment_id;
                                }

                            }
                        }
                    }
                    //add to array
                    $mediaurl = array();
                    foreach ($attachment_ids as $img_id) {
                        $imgurl = wp_get_attachment_url( $img_id );
                        $image_gallery[$img_id] = $imgurl;
                    }

                    update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery);      // 2nd arg field key
                }

            }
            else {
                    $data['status'] = false;
                    $data['message'] = __('Nonce verify failed','realestate');
            }

            return $new_post_id;

        }
    endif;

    if ( ! function_exists( 'reArrayFiles' ) ) :
        function reArrayFiles(&$file_post) {
            $file_ary = array();
            $file_count = count($file_post['name']);
            $file_keys = array_keys($file_post);
            for ($i=0; $i<$file_count; $i++) {
                foreach ($file_keys as $key) {
                    $file_ary[$i][$key] = $file_post[$key][$i];
                }
            }
            return $file_ary;
        }
    endif;

    if ( ! function_exists( 'upload_user_file' ) ) :
        function upload_user_file( $file = array(), $title = false ) {
            require_once ABSPATH.'wp-admin/includes/admin.php';
            $file_return = wp_handle_upload($file, array('test_form' => false));
            if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
                return false;
            }else{
                $filename = $file_return['file'];
                $attachment = array(
                    'post_mime_type' => $file_return['type'],
                    'post_content' => '',
                    'post_type' => 'attachment',
                    'post_status' => 'inherit',
                    'guid' => $file_return['url']
                );
                if($title){
                    $attachment['post_title'] = $title;
                }
                $attachment_id = wp_insert_attachment( $attachment, $filename );
                require_once(ABSPATH . 'wp-admin/includes/image.php');

                $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
                wp_update_attachment_metadata( $attachment_id, $attachment_data );
                if( 0 < intval( $attachment_id ) ) {
                    return $attachment_id;
                }
            }
            return false;
        }
    endif;

    function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
        $attachurlarray = array();
        // check to make sure its a successful upload
        if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');

        $attach_id = media_handle_upload( $file_handler, $post_id );
        return $attach_id;
    }


来源: stackexchange

问:
How to add multidomain support in CodeIgniter?
I need city1.example.com, city2.example.com, city3.example.com support in CodeIgniter.

Unfortunately, $config['base_url'] in config.php sets the base URL strictly.

What is the best way to learn the framework to support different subdomains?

答:
You should probably just search Codeigniter.com next time, as it's all there in the wiki:

https://github.com/EllisLab/CodeIgniter/wiki/Automatic-base-url

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
file_get_contents in php is not returning E-mail id, why?
Actually I am sending email from php. When I am using file_get_contents() for email body from external file, its not returning email id. Instead email id it's returning '[email protected]'.

Here is my code to call the file with file_get_contents():

```<code>$params = 'for=team&name='.urlencode($name).'&email='.urlencode($email).'&phone='.urlencode($phone).'&company='.urlencode($company).'&looking_for='.$looking_for.'&country='.urlencode($country).'&source_page='.urlencode($source_page);
$team_msg = file_get_contents(get_template_directory_uri().'/mail-template/contact_us_email_temp.php?'.$params);
$headers[] = "MIME-Version: 1.0" . "\r\n";
$headers[] .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers[] .= 'From: Someone <someone@domainname.com>';
$to = 'myselft@domainname.com';
$team_subject = 'email subject';
wp_mail($to, $team_subject, $team_msg, $headers );
</code>```

And Here is the 'contact_us_email_temp.php' which is called from function:

```<code>$message = "<table border='0'><tbody>
            <tr><td colspan='2'>Users Detail:</td></tr>
            <tr>
                <td><b>Name</b></td>
                <td>".$_GET['name']."</td>
            </tr>
            <tr>
                <td><b>Official Email</b></td>
                <td>".$_GET['email']."</td>
            </tr>
            <tr>
                <td><b>Company</b></td>
                <td>".$_GET['company']."</td>
            </tr>
            <tr>
                <td><b>Mobile Number</b></td>
                <td>".$_GET['phone']."</td>
            </tr>
            <tr>
                <td><b>Looking For</b></td>
                <td>".$_GET['looking_for']."</td>
            </tr>
            <tr>
                <td><b>Country</b></td>
                <td>".$_GET['country']."</td>
            </tr>
            <tr>
                <td><b>Source Page</b></td>
                <td>".$_GET['source_page']."</td></tr>
            <tr>
            </tbody>
            </table>";
echo $message;
</code>```

I am not sure what's wrong with the function.

Thanks

答:
file_get_contents() doesn't work like a HTTP Request. You're loading a the ACTUAL file as a string and any code isn't executed. So when you send the mail now, the viewer will see the $_GET['name'] for example. What you want to do is create a function out of the contact_us_email_temp.php file and use the GET parameters as function parameters.

```<code>function getEmail($name, $email, $company, $phone, $looking_for, $country, $source_page) {
$message = "
<table border='0'><tbody>

<tr><td colspan='2'>Users Detail:</td></tr>
        <tr>
            <td><b>Name</b></td>
            <td>".$name."</td>
        </tr>
        <tr>
            <td><b>Official Email</b></td>
            <td>".$email."</td>
        </tr>
        <tr>
            <td><b>Company</b></td>
            <td>".$company."</td>
        </tr>
        <tr>
            <td><b>Mobile Number</b></td>
            <td>".$phone."</td>
        </tr>
        <tr>
            <td><b>Looking For</b></td>
            <td>".$looking_for."</td>
        </tr>
        <tr>
            <td><b>Country</b></td>
            <td>".$country."</td>
        </tr>
        <tr>
            <td><b>Source Page</b></td>
            <td>".$source_page."</td></tr>
        <tr>
        </tbody>
        </table>";
return $message;
}
</code>```

Require this script in your main script and run the function instead of file_get_contents

Body:
Actually I am sending email from php. When I am using file_get_contents() for email body from external file, its not returning email id. Instead email id it's returning '[email protected]'.

Here is my code to call the file with file_get_contents():

$params = 'for=team&name='.urlencode($name).'&email='.urlencode($email).'&phone='.urlencode($phone).'&company='.urlencode($company).'&looking_for='.$looking_for.'&country='.urlencode($country).'&source_page='.urlencode($source_page);
$team_msg = file_get_contents(get_template_directory_uri().'/mail-template/contact_us_email_temp.php?'.$params);
$headers[] = "MIME-Version: 1.0" . "\r\n";
$headers[] .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers[] .= 'From: Someone <someone@domainname.com>';
$to = 'myselft@domainname.com';
$team_subject = 'email subject';
wp_mail($to, $team_subject, $team_msg, $headers );

And Here is the 'contact_us_email_temp.php' which is called from function:

$message = "

Users Detail:

                Name
                ".$_GET['name']."

                Official Email
                ".$_GET['email']."

                Company
                ".$_GET['company']."

                Mobile Number
                ".$_GET['phone']."

                Looking For
                ".$_GET['looking_for']."

                Country
                ".$_GET['country']."

                Source Page
                ".$_GET['source_page']."

";
echo $message;

I am not sure what's wrong with the function.

Thanks

Body:
file_get_contents() doesn't work like a HTTP Request. You're loading a the ACTUAL file as a string and any code isn't executed. So when you send the mail now, the viewer will see the $_GET['name'] for example. What you want to do is create a function out of the contact_us_email_temp.php file and use the GET parameters as function parameters.

function getEmail($name, $email, $company, $phone, $looking_for, $country, $source_page) {
$message = "
<table border='0'><tbody>

<tr><td colspan='2'>Users Detail:</td></tr>
        <tr>
            <td><b>Name</b></td>
            <td>".$name."</td>
        </tr>
        <tr>
            <td><b>Official Email</b></td>
            <td>".$email."</td>
        </tr>
        <tr>
            <td><b>Company</b></td>
            <td>".$company."</td>
        </tr>
        <tr>
            <td><b>Mobile Number</b></td>
            <td>".$phone."</td>
        </tr>
        <tr>
            <td><b>Looking For</b></td>
            <td>".$looking_for."</td>
        </tr>
        <tr>
            <td><b>Country</b></td>
            <td>".$country."</td>
        </tr>
        <tr>
            <td><b>Source Page</b></td>
            <td>".$source_page."</td></tr>
        <tr>
        </tbody>
        </table>";
return $message;
}

Require this script in your main script and run the function instead of file_get_contents


问:
Scheme (DrRacket) lambda expression
I do not understand the following program code. Can anyone explain it to me?

```<code>(define myFunction
  (lambda (f x y z)
    (f x y z)))
</code>```

How can I simplify it?

答:
You can't simplify it much, except for making it look a bit syntactic, as

```<code>(define (myFunction f x y z)
        (f x y z))
</code>```

which is a syntactic shortcut for defining the exact same thing.

This way, you can treat it mentally as a rewriting rule: whenever you see

```<code>        (myFunction f x y z)
</code>```

in your code - whatever those f, x, y and z placeholders are referring to - you can replace it with

```<code>        (f x y z)
</code>```

while substituting the actual values, a.k.a. arguments, for the placeholders, a.k.a. function parameters.

Thus you see that for the new code to make sense, f should be a function capable of accepting three arguments, x, y and z.

So for example, if you define (define (f x y z) (+ x y z)), you can call

```<code>(myFunction f 1 2 3)
</code>```

and get a result back - which is the result of calling the function f you've just defined above, with the values 1, 2 and 3.

f inside myFunction will refer to the global name f which refers to a value - a function named f you've defined. The lambda form defines a value - an anonymous function - and define binds a name f to it, so that any use of that name refers to that value, from now on. In Scheme, functions are values like any other.

That global function f is defined to apply + to the three arguments it receives, when it receives them. It in effect is saying, "give me some three values and I'll sum them up for you", and the call (myFunction f 1 2 3) supplies it with the three values of your choosing.

Title: Scheme (DrRacket) lambda expression

Body:
I do not understand the following program code. Can anyone explain it to me?

(define myFunction
  (lambda (f x y z)
    (f x y z)))

How can I simplify it?

Body:
You can't simplify it much, except for making it look a bit syntactic, as

(define (myFunction f x y z)
        (f x y z))

which is a syntactic shortcut for defining the exact same thing.

This way, you can treat it mentally as a rewriting rule: whenever you see

        (myFunction f x y z)

in your code - whatever those f, x, y and z placeholders are referring to - you can replace it with

        (f x y z)

while substituting the actual values, a.k.a. arguments, for the placeholders, a.k.a. function parameters.

Thus you see that for the new code to make sense, f should be a function capable of accepting three arguments, x, y and z.

So for example, if you define (define (f x y z) (+ x y z)), you can call

(myFunction f 1 2 3)

and get a result back - which is the result of calling the function f you've just defined above, with the values 1, 2 and 3.

f inside myFunction will refer to the global name f which refers to a value - a function named f you've defined. The lambda form defines a value - an anonymous function - and define binds a name f to it, so that any use of that name refers to that value, from now on. In Scheme, functions are values like any other.

That global function f is defined to apply + to the three arguments it receives, when it receives them. It in effect is saying, "give me some three values and I'll sum them up for you", and the call (myFunction f 1 2 3) supplies it with the three values of your choosing.


问:
how to resolve Fatal error: Class 'App\Http\Controllers\Controller' not found
I am trying to submit a form to a database using Laravel 5.4 but each time I press the submit button I get this error message:

Fatal error: Class 'App\Http\Controllers\Controller' not found.

Below is my code for controller.php:

```<code><?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function index()
    {
        return view('./');
    }

    public function about()
    {
        $title='About us';
        return view('pages.about')->with('title',$title);
    }

    public function services()
    {
        $data=array(
            'title'=>'Services',
            'services'=>['Mechanic help','book a mechanic','others']
        );
        return view('pages.services')->with ($data);
    }

    public function create()
    {

    }
}
</code>```

答:
That kind of error would mean that you are either missing your Controller.php file in the same folder, or the autoloader isn't loading it, or it is not defining the class Controller. This is the file in the Laravel repo:

https://github.com/laravel-shift/laravel-5.4/blob/master/app/Http/Controllers/Controller.php

Body:
I am trying to submit a form to a database using Laravel 5.4 but each time I press the submit button I get this error message:

Fatal error: Class 'App\Http\Controllers\Controller' not found.

Below is my code for controller.php:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function index()
    {
        return view('./');
    }

    public function about()
    {
        $title='About us';
        return view('pages.about')->with('title',$title);
    }

    public function services()
    {
        $data=array(
            'title'=>'Services',
            'services'=>['Mechanic help','book a mechanic','others']
        );
        return view('pages.services')->with ($data);
    }

    public function create()
    {

    }
}


问:
What is the meaning of the traceback?
I am using  django-email-change-0.2.1 just to change an emailadress in the auth_user-table. When I am going to add the app emailchange in the settings.py. I get an error message!

Actually you can install the app. But I didn't do that in the site-packages of python. I have copied the code into my code of the website.

Root of my Website:
/trunk/website/

In the following path I have installed different apps.
Path:

```<code>/trunk/website/auth/user/emailchange
/trunk/website/auth/user/registraiton
/trunk/website/auth/user/profile
</code>```

The last two apps are working fine. I just want to add the last app for my registration. To change the email address of an user with the app  "emailchange", so I am going to send a a verifaction link when the user is changeing his emailadress.

In my settings.py to run/install the app (model) I added:

```<code>Insalled_apps= {
'auth.user.emailchange'
}
</code>```

But I am getting this errormessage when I add the app and call any site of my website!

```<code>Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  91.                         request.path_info)
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in resolve
  215.             for pattern in self.url_patterns:
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in _get_url_patterns
  244.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in _get_urlconf_module
  239.             self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/workspace/website/trunk/website/urls.py" in <module>
  5. admin.autodiscover()
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/__init__.py" in autodiscover
  24.             import_module('%s.admin' % app)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/trunk/website/auth/user/emailchange/admin.py" in <module>
  33. admin.site.register(cache.get_model('email_change', 'EmailChangeRequest'), EmailChangeRequestAdmin)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in register
  76.         for model in model_or_iterable:

Exception Type: TypeError at /start/
Exception Value: 'NoneType' object is not iterable
</code>```

Any ideas? Why do I have this message?

答:
This:

```<code>Insalled_apps= {
'auth.user.emailchange'
}
</code>```

is wrong in many ways. First, it's not valid Python syntax (curly brackets are for making dicts, not lists) and secondly it's not even close to the valid way of adding an app to a Django settings.py file, which is something like:

```<code>INSTALLED_APPS = (
    'foos',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
 )
</code>```

So basically fix those things and get back to us. Oh, and could you please also consider copying and pasting code into questions so you don't make mistakes typing them in again?

Title: What is the meaning of the traceback?

Body:
I am using  django-email-change-0.2.1 just to change an emailadress in the auth_user-table. When I am going to add the app emailchange in the settings.py. I get an error message!

Actually you can install the app. But I didn't do that in the site-packages of python. I have copied the code into my code of the website.

Root of my Website:
/trunk/website/

In the following path I have installed different apps.
Path:

/trunk/website/auth/user/emailchange
/trunk/website/auth/user/registraiton
/trunk/website/auth/user/profile

The last two apps are working fine. I just want to add the last app for my registration. To change the email address of an user with the app  "emailchange", so I am going to send a a verifaction link when the user is changeing his emailadress.

In my settings.py to run/install the app (model) I added:

Insalled_apps= {
'auth.user.emailchange'
}

But I am getting this errormessage when I add the app and call any site of my website!

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  91.                         request.path_info)
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in resolve
  215.             for pattern in self.url_patterns:
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in _get_url_patterns
  244.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in _get_urlconf_module
  239.             self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/workspace/website/trunk/website/urls.py" in <module>
  5. admin.autodiscover()
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/__init__.py" in autodiscover
  24.             import_module('%s.admin' % app)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/trunk/website/auth/user/emailchange/admin.py" in <module>
  33. admin.site.register(cache.get_model('email_change', 'EmailChangeRequest'), EmailChangeRequestAdmin)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in register
  76.         for model in model_or_iterable:

Exception Type: TypeError at /start/
Exception Value: 'NoneType' object is not iterable

Any ideas? Why do I have this message?

Body:
This:

Insalled_apps= {
'auth.user.emailchange'
}

is wrong in many ways. First, it's not valid Python syntax (curly brackets are for making dicts, not lists) and secondly it's not even close to the valid way of adding an app to a Django settings.py file, which is something like:

INSTALLED_APPS = (
    'foos',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
 )

So basically fix those things and get back to us. Oh, and could you please also consider copying and pasting code into questions so you don't make mistakes typing them in again?


问:
Simple example to send data with lora on mDot
I have multitech conduit set up as packet forwarder to resiot platform and I would like the simplest example to send data via loraWAN with multitech mdot (mbed platform). I have problems with compiling dot examples, and cannot find any documentation for library so a simple example would clarify a lot for me.

Thanks,

答:
Does this work? https://docs.mbed.com/docs/lora-with-mbed/en/latest/intro-to-lora/

Some tips:

Use the same mbed-os version as noted in libmdot commit message.

Use Dot-Examples which is compatible with the libmdot you're using (probably v3).


问:
boost::process how to know when a process exited "gracefully or not"?
While waiting for a boost::process::child, how can you know if it exited "gracefully or not"?

Let's say I create a processus:

```<code>boost::process::child child( "myprg.exe", "5000" );
child.wait();
int res = child.exit_code();
</code>```

Where myprg.exe is:

```<code>int main( int argc, char* argv[] )
{
    if ( argc == 2 )
    {
        boost::this_thread::sleep( boost::posix_time::milliseconds( atoi( argv[1] ) ) );
        return 1;
    }

    return 0;
}
</code>```

Note: This a MCVE that makes no sense, I agree main should return 0 if successfull.

I see that if someone kills the process while it waits (using child.terminate for instance or Windows Process Manager), child.exit_code() will return 1.

So, in the end, when child.exit_code() is 1, how can I know if this is the value returned by the process's main entry function or if the process was killed?

Is it guaranteed that 1 will mean process was killed? Then program should not return 1 and keep this exit code to identify the specific situation where it was killed and did not exit cleanly?

If not, does boost::process API provide something to know if process ended up cleanly or was killed?

答:
So, in the end, when child.exit_code() is 1, how can I know if this is the value returned by the process's main entry function or if the process was killed?

You can't.

Is it guaranteed that 1 will mean process was killed?

It depends. As for Windows, according to this answer, it will be 1, but it is documented nowhere. Note that the return code for a killed process is determined by the instance that is terminating the process. For Boost's terminate function, one finds inside detail/windows/terminate.hpp:

```<code>inline void terminate(child_handle &p)
{
    if (!::boost::winapi::TerminateProcess(p.process_handle(), EXIT_FAILURE))
        boost::process::detail::throw_last_error("TerminateProcess() failed");

    ::boost::winapi::CloseHandle(p.proc_info.hProcess);
    p.proc_info.hProcess = ::boost::winapi::INVALID_HANDLE_VALUE_;
}
</code>```

So it is returning EXIT_FAILURE always, which might be 1. However, one can make a process return any value.

To distinguish whether your process terminated gracefully or not in a completely foolproof and portable manner, you therefore have to implement your own communication mechanism apart from just evaluating the return codes.

Body:
While waiting for a boost::process::child, how can you know if it exited "gracefully or not"?

Let's say I create a processus:

boost::process::child child( "myprg.exe", "5000" );
child.wait();
int res = child.exit_code();

Where myprg.exe is:

int main( int argc, char* argv[] )
{
    if ( argc == 2 )
    {
        boost::this_thread::sleep( boost::posix_time::milliseconds( atoi( argv[1] ) ) );
        return 1;
    }

    return 0;
}

Note: This a MCVE that makes no sense, I agree main should return 0 if successfull.

I see that if someone kills the process while it waits (using child.terminate for instance or Windows Process Manager), child.exit_code() will return 1.

So, in the end, when child.exit_code() is 1, how can I know if this is the value returned by the process's main entry function or if the process was killed?

Is it guaranteed that 1 will mean process was killed? Then program should not return 1 and keep this exit code to identify the specific situation where it was killed and did not exit cleanly?

If not, does boost::process API provide something to know if process ended up cleanly or was killed?

Body:
So, in the end, when child.exit_code() is 1, how can I know if this is the value returned by the process's main entry function or if the process was killed?

You can't.

Is it guaranteed that 1 will mean process was killed?

It depends. As for Windows, according to this answer, it will be 1, but it is documented nowhere. Note that the return code for a killed process is determined by the instance that is terminating the process. For Boost's terminate function, one finds inside detail/windows/terminate.hpp:

inline void terminate(child_handle &p)
{
    if (!::boost::winapi::TerminateProcess(p.process_handle(), EXIT_FAILURE))
        boost::process::detail::throw_last_error("TerminateProcess() failed");

    ::boost::winapi::CloseHandle(p.proc_info.hProcess);
    p.proc_info.hProcess = ::boost::winapi::INVALID_HANDLE_VALUE_;
}

So it is returning EXIT_FAILURE always, which might be 1. However, one can make a process return any value.

To distinguish whether your process terminated gracefully or not in a completely foolproof and portable manner, you therefore have to implement your own communication mechanism apart from just evaluating the return codes.


问:
JDBC Driver and URL
This is my first time using jasperserver and I want to connect to mysql databae, I have been following tutorial videos and looking at the documents but I don't understand where do you get the JDBC Driver and URL. They give the hint: Hint: jdbc:postgresql://localhost:5432/mydb and also Hint: org.postgresql.Driver but I still don't know where to look for it.

I have already downloaded the drivers using this website, https://learn.microsoft.com/en-us/sql/connect/sql-connection-libraries#anchor-20-drivers-relational-access and transfer sqljdbc42 and sqljdbc41 into apache tomcat/lib folder already

Can someone please guide me in doing this? Thanks a lot.

答:
Each SQL server has a different jdbc url format.

MySQL (and also MariaDB), driver=com.mysql.jdbc.Driver

jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf8&user=myuser&password=mypwd

MSSQL, driver=com.microsoft.jdbc.sqlserver.SQLServerDriver

jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=mydb;user=myuser;password=mypwd

Title: JDBC Driver and URL


问:
Google Map Marker is showing at the left-top side
I am trying to display a google map with draggable marker in bootstrap modal. It works perfectly but the problem is the marker is showing at the left top side of div as shown below in image.

I wants to show in center of div

It will shown at left top of modal. Here is my code for showing google map.

```<code>function init() {
      var mapCanvas = document.getElementById('map_canvas');

      $('.mapModal').on('shown.bs.modal', function () {
          google.maps.event.trigger(mapCanvas, "resize");
      });

        //var myLatlng = new google.maps.LatLng(23.0203135, 72.5561606);
        var myLatlng = {lat: 23.019523540982888, lng: 72.55628934603271};
        /*
          23.019523540982888
          72.55628934603271
          23.0203135
          72.5561606
        */
        var myOptions = {
            zoom: 15,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            draggable: true,
            map: map,
            position: myLatlng,
            title: "Your location"
        });
        //To Fill Lat Long
        google.maps.event.addListener(marker, 'dragend', function (event) {
            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("lng").value = event.latLng.lng();
        });
}
</code>```

答:
Just use map.setCenter(myLatlng); and it will works.

```<code>var map;
    //google.maps.event.addDomListener(window, "load", init());
    function init() {
      var mapCanvas = document.getElementById('map_canvas');
      var myLatlng = {lat: 23.019523540982888, lng: 72.55628934603271};

      $('.mapModal').on('shown.bs.modal', function () {
          google.maps.event.trigger(mapCanvas, "resize");
          map.setCenter(myLatlng);
      });

        //var myLatlng = new google.maps.LatLng(23.019523540982888, 72.55628934603271);
        /*
          23.019523540982888
          72.55628934603271
          23.0203135
          72.5561606
        */
        var myOptions = {
            zoom: 15,
            center: new google.maps.LatLng(23.0203135, 72.5561606),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(mapCanvas, myOptions);

        var marker = new google.maps.Marker({
            draggable: true,
            map: map,
            position: myLatlng,
            title: "Your location"
        });
        //To Fill Lat Long
        google.maps.event.addListener(marker, 'dragend', function (event) {
            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("lng").value = event.latLng.lng();
        });
    }
</code>```

Body:
I am trying to display a google map with draggable marker in bootstrap modal. It works perfectly but the problem is the marker is showing at the left top side of div as shown below in image.

I wants to show in center of div

It will shown at left top of modal. Here is my code for showing google map.

function init() {
      var mapCanvas = document.getElementById('map_canvas');

      $('.mapModal').on('shown.bs.modal', function () {
          google.maps.event.trigger(mapCanvas, "resize");
      });

        //var myLatlng = new google.maps.LatLng(23.0203135, 72.5561606);
        var myLatlng = {lat: 23.019523540982888, lng: 72.55628934603271};
        /*
          23.019523540982888
          72.55628934603271
          23.0203135
          72.5561606
        */
        var myOptions = {
            zoom: 15,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            draggable: true,
            map: map,
            position: myLatlng,
            title: "Your location"
        });
        //To Fill Lat Long
        google.maps.event.addListener(marker, 'dragend', function (event) {
            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("lng").value = event.latLng.lng();
        });
}

Body:
Just use map.setCenter(myLatlng); and it will works.

var map;
    //google.maps.event.addDomListener(window, "load", init());
    function init() {
      var mapCanvas = document.getElementById('map_canvas');
      var myLatlng = {lat: 23.019523540982888, lng: 72.55628934603271};

      $('.mapModal').on('shown.bs.modal', function () {
          google.maps.event.trigger(mapCanvas, "resize");
          map.setCenter(myLatlng);
      });

        //var myLatlng = new google.maps.LatLng(23.019523540982888, 72.55628934603271);
        /*
          23.019523540982888
          72.55628934603271
          23.0203135
          72.5561606
        */
        var myOptions = {
            zoom: 15,
            center: new google.maps.LatLng(23.0203135, 72.5561606),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(mapCanvas, myOptions);

        var marker = new google.maps.Marker({
            draggable: true,
            map: map,
            position: myLatlng,
            title: "Your location"
        });
        //To Fill Lat Long
        google.maps.event.addListener(marker, 'dragend', function (event) {
            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("lng").value = event.latLng.lng();
        });
    }


问:
File upload and delete
I'm trying to upload a file, and have the name of the uploaded file displayed along with a "remove" link to remove the uploaded file (in order to uploaded another one). Here is what I've got so far. Everything works fine except that when I remove the uploaded file, and try to upload another one by clicking on "Choose file" button, the same file name pops up. How can I remove the file name from the memory (I guess), so button works like new, and also no file gets sent when the form is submitted WITHOUT the file name, but if the uploaded file ISN'T DELETED, it should be available for submit.
Many thanks for your help in advance.</p>

答:
Add $this.val('') after you delete so you set the value off the input to empty.

```<code>SITE.fileInputs = function() {
    var $this = $(this),
        $val = $this.val(),
        valArray = $val.split('\\'),
        newVal = valArray[valArray.length - 1],
        $button = $this.siblings('.button'),
        $fakeFile = $this.siblings('.file-holder');
    if (newVal !== '') {
        $button.text('File chosen');
        if ($fakeFile.length === 0) {
            $('.place').html('<div><span class="file-holder">' + newVal + '</span><a href="#" class="delete_upload">Remove</a></div>');
            $this.val('');
        } else {
            $fakeFile.text(newVal);
        }
    }
};
</code>```

Check the result here: http://jsfiddle.net/kTNuB/3/

Title: File upload and delete

Body:
Add $this.val('') after you delete so you set the value off the input to empty.

SITE.fileInputs = function() {
    var $this = $(this),
        $val = $this.val(),
        valArray = $val.split('\\'),
        newVal = valArray[valArray.length - 1],
        $button = $this.siblings('.button'),
        $fakeFile = $this.siblings('.file-holder');
    if (newVal !== '') {
        $button.text('File chosen');
        if ($fakeFile.length === 0) {
            $('.place').html('<div><span class="file-holder">' + newVal + '</span><a href="#" class="delete_upload">Remove</a></div>');
            $this.val('');
        } else {
            $fakeFile.text(newVal);
        }
    }
};

Check the result here: http://jsfiddle.net/kTNuB/3/


问:
My Variable won't change on a label? (python)
In my program there are four labels. 3 are stand-alone variables, but the 4th is a division of one of the variables by 100.0, and works fine.

My program works fine and runs fine, but I add in a 5th (which is a multiplication of 2 variables), but it does not change from 0. It is in the same place in the program's code as the 4th, but I still can't figure out why it won't work. The only thing that I can think of is that I did not reload it, but I looked and I have. I am really stuck so can someone please help? Here is the code:

```<code>import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---

def moar_eggz():
    global eggzps, chookz

    chookz += 1

def update_labels():
    try:
        label1.config(text="Eggs: " + str(round(eggz)))
        if eggzps >= 10:
            label2.config(text="Eggs Per Second: " + str(round(int(eggzps))))
        elif eggzps < 10:
            label2.config(text="Eggs Per Second: " + str(eggzps))
        label3.config(text="Egg Value: " + str(eggvalue))
        label4.config(text="Chickens: " + str(chookz))
        label5.config(text="Money: " + str(money))
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 20ms
    root.after(20, update_labels)

def main_loop():
    global eggz, eggzps
    eggzps = chookz / 100.0
    money = eggz * eggvalue
    update_labels()
    try:
        eggz += eggzps
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 1000ms
    root.after(1000, main_loop)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

eggz = 0
eggvalue = 0.2
chookz = 0
eggzps = 0.0
eggzpms = 0
money = eggz * eggvalue

# empty labels - `update_labels` will add text
label5 = tk.Label(root)
label4 = tk.Label(root)
label3 = tk.Label(root)
label2 = tk.Label(root)
label1 = tk.Label(root)
label5.pack()
label4.pack()
label3.pack()
label2.pack()
label1.pack()

chickencnv = Image.open("img\\1.png")
chicken = ImageTk.PhotoImage(chickencnv)

openbutton6= tk.Button(root, image=chicken, width=500, height=500, command=moar_eggz)
openbutton6.pack()

# run it first time at once
main_loop()

root.mainloop()
</code>```

I have tried many changes with the code in my game, but all have failed to change anything, so I came here.

Any unrelated or related answers or suggestions to the topic will be highly appreciated.

Thanks in advance!

答:
You just have forgotten to add money to the global variables in main_loop. So in update_labels, its always its initial value 0 which is displayed.

```<code>def main_loop():
    global eggz, eggzps, money
    ...
</code>```

Body:
In my program there are four labels. 3 are stand-alone variables, but the 4th is a division of one of the variables by 100.0, and works fine.

My program works fine and runs fine, but I add in a 5th (which is a multiplication of 2 variables), but it does not change from 0. It is in the same place in the program's code as the 4th, but I still can't figure out why it won't work. The only thing that I can think of is that I did not reload it, but I looked and I have. I am really stuck so can someone please help? Here is the code:

import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---

def moar_eggz():
    global eggzps, chookz

    chookz += 1

def update_labels():
    try:
        label1.config(text="Eggs: " + str(round(eggz)))
        if eggzps >= 10:
            label2.config(text="Eggs Per Second: " + str(round(int(eggzps))))
        elif eggzps < 10:
            label2.config(text="Eggs Per Second: " + str(eggzps))
        label3.config(text="Egg Value: " + str(eggvalue))
        label4.config(text="Chickens: " + str(chookz))
        label5.config(text="Money: " + str(money))
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 20ms
    root.after(20, update_labels)

def main_loop():
    global eggz, eggzps
    eggzps = chookz / 100.0
    money = eggz * eggvalue
    update_labels()
    try:
        eggz += eggzps
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 1000ms
    root.after(1000, main_loop)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

eggz = 0
eggvalue = 0.2
chookz = 0
eggzps = 0.0
eggzpms = 0
money = eggz * eggvalue

# empty labels - `update_labels` will add text
label5 = tk.Label(root)
label4 = tk.Label(root)
label3 = tk.Label(root)
label2 = tk.Label(root)
label1 = tk.Label(root)
label5.pack()
label4.pack()
label3.pack()
label2.pack()
label1.pack()

chickencnv = Image.open("img\\1.png")
chicken = ImageTk.PhotoImage(chickencnv)

openbutton6= tk.Button(root, image=chicken, width=500, height=500, command=moar_eggz)
openbutton6.pack()

# run it first time at once
main_loop()

root.mainloop()

I have tried many changes with the code in my game, but all have failed to change anything, so I came here.

Any unrelated or related answers or suggestions to the topic will be highly appreciated.

Thanks in advance!

Body:
You just have forgotten to add money to the global variables in main_loop. So in update_labels, its always its initial value 0 which is displayed.

def main_loop():
    global eggz, eggzps, money
    ...


问:
'sed' command does not work normally in PBS scripts
I use torque to submit the test script shown blow

```<code>#!/bin/bash
#PBS -N test
#PBS -l nodes=1:ppn=1
#PBS -q ser
#PBS -V
#PBS -S /bin/bash

sed 's/a//' <<< aaabbbaaa
sed 's/\(a\)//' <<< aaabbbaaa
sed 's/a\+//' <<< aaabbbaaa
</code>```

The expect output should be

```<code>aabbbaaa
aabbbaaa
bbbaaa
</code>```

but actually when i use qsub to submit this file, the output becomes

```<code>aabbbaaa
aaabbbaaa
aaabbbaaa
</code>```

The last two commands do not work. And it seems that the character '\' leads to the fault. But why does this happen.

答:
The sed implementation on the server probably has a different syntax than what you have locally.

Without details about the remote system, this is mildly speculative; but look for the manual page and search for an option to enable Extended Regular Expression syntax (usually -E or -r; if available, probably lose the backslash before the regex specials then).

As a partial and obvious workaround, aa* is equivalent to a\+ but no similar workaround exists for grouping.

Maybe also read up on the differences between POSIX Basic Regular Expression syntax (BRE) and ERE; though chances are your PBS system is using something which even predates POSIX if it's legacy big iron.

If you want to write code which is portable between Linux, MacOS, and whatever behemoth dinosaur OS you have on the PBS system, maybe try Perl instead of sed.  Even if you can only rely on Perl 4.x constructs, that's a platform which is a lot more uniform (and also a lot more versatile) than trying to figure out how to write portable sed scripts.

```<code>perl -pe 's/(a+)//'
</code>```

Body:
I use torque to submit the test script shown blow

#!/bin/bash
#PBS -N test
#PBS -l nodes=1:ppn=1
#PBS -q ser
#PBS -V
#PBS -S /bin/bash

sed 's/a//' <<< aaabbbaaa
sed 's/\(a\)//' <<< aaabbbaaa
sed 's/a\+//' <<< aaabbbaaa

The expect output should be

aabbbaaa
aabbbaaa
bbbaaa

but actually when i use qsub to submit this file, the output becomes

aabbbaaa
aaabbbaaa
aaabbbaaa

The last two commands do not work. And it seems that the character '\' leads to the fault. But why does this happen.

Body:
The sed implementation on the server probably has a different syntax than what you have locally.

Without details about the remote system, this is mildly speculative; but look for the manual page and search for an option to enable Extended Regular Expression syntax (usually -E or -r; if available, probably lose the backslash before the regex specials then).

As a partial and obvious workaround, aa* is equivalent to a\+ but no similar workaround exists for grouping.

Maybe also read up on the differences between POSIX Basic Regular Expression syntax (BRE) and ERE; though chances are your PBS system is using something which even predates POSIX if it's legacy big iron.

If you want to write code which is portable between Linux, MacOS, and whatever behemoth dinosaur OS you have on the PBS system, maybe try Perl instead of sed.  Even if you can only rely on Perl 4.x constructs, that's a platform which is a lot more uniform (and also a lot more versatile) than trying to figure out how to write portable sed scripts.

perl -pe 's/(a+)//'


问:
How to specify a Column for VBA's Autofilter function by name rather than by its index?
I am new to VBA and trying to autofilter a column range. The column is named "Vlookup" and sits at index position 27.

```<code>rData.AutoFilter field:=27, Criteria1:="Class" ' filter criterion
</code>```

In order to make this dynamic, I need to be able to filter according to column name rather than column index.

However, when I do

```<code>rData.AutoFilter field:=Application.Match("Vlookup", Selection.Rows(1), 0), Criteria1:="Class"  ' filter criterion
</code>```

I yield

Runtime Error '424' - Object Required

How to correctly Autofilter by column name in VBA?

答:
You can use helper UDF which will return column's index:

```<code>Function GetIndex(colName As String)
    GetIndex = WorksheetFunction.Match(colName, ActiveSheet.AutoFilter.Range.Rows(1), 0)
End Function
</code>```

UPD

You can substitute ActiveSheet with your sheet.

Body:
I am new to VBA and trying to autofilter a column range. The column is named "Vlookup" and sits at index position 27.

rData.AutoFilter field:=27, Criteria1:="Class" ' filter criterion

In order to make this dynamic, I need to be able to filter according to column name rather than column index.

However, when I do

rData.AutoFilter field:=Application.Match("Vlookup", Selection.Rows(1), 0), Criteria1:="Class"  ' filter criterion

I yield

Runtime Error '424' - Object Required

How to correctly Autofilter by column name in VBA?

Body:
You can use helper UDF which will return column's index:

Function GetIndex(colName As String)
    GetIndex = WorksheetFunction.Match(colName, ActiveSheet.AutoFilter.Range.Rows(1), 0)
End Function

UPD

You can substitute ActiveSheet with your sheet.


问:
SQL Server 2012: dynamic SQL limitation ( > 4000 chars) (split)
I have this dynamic SQL in a stored procedure:

```<code>Declare @template nvarchar(max)
Declare @publishdetails nvarchar(max)

set @publishdetails= ',B.[PublishedBy]=suser_name(),
  B.[PublishedDate]=GETDATE() '

set @template='if NOT EXISTS(select * from ' +@DestinationDB+ '.[CLs] where id='+ str(@slid)+')
insert into  ' +@DestinationDB+ '.CLs (id,slid,slversion) VALUES ( '+ str(@id)+','+ str(@slid)+','+str(@slversion)+')

update  B set
      B.[Clientid]=A.clientid,
        --.........
      B.[CreatedDate] = A.CreatedDate,
      B.[ModifiedDate] = A.ModifiedDate,
      B.[CreatedBy] = A.CreatedBy,
      B.[ModifiedBy] = A.ModifiedBy '+@publishdetails+ --Added publishdetails
    'FROM  ' + @SourceDB + '.[CLs] as A, '+ @DestinationDB+ '.[CLs] as B
        where A.slversion = '+ str(@slversion)+' and A.id='+str(@slid) + 'B.slversion = '+ str(@slversion)+' and B.id='+str(@slid)

        print 'template is: ' + @template
exec sp_Executesql @template
</code>```

When exec sp_Executesql @template is executing, it fails. Because @template is > 4000 chars and is truncated. How can I split it in chunks and execute it the correct way?

答:
You don't need to split the text into parts. You do need to make sure that truncation doesn't occur whilst you're concatenating strings:

If the result of the concatenation of strings exceeds the limit of 8,000 bytes, the result is truncated. However, if at least one of the strings concatenated is a large value type, truncation does not occur.

So, make sure that the first concatenation is working with a large value type (and thus produces a large value type as its result) and every subsequent concatenation should be saved from truncation:

```<code>set @template=CONVERT(nvarchar(max),'if NOT EXISTS(select * from ' ) + @DestinationDB + ...
</code>```

(In this way, you don't have to insert conversions everywhere)

This generates an error:

```<code>declare @t nvarchar(max)

set @t = 'select LEN(''' + REPLICATE('A',3000) + REPLICATE('B',3000) + REPLICATE('C',3000) + ''')'

exec sp_executesql @t
</code>```

And this produces the result 9000:

```<code>declare @t nvarchar(max)

set @t = CONVERT(nvarchar(max),'select LEN(''') + REPLICATE('A',3000) + REPLICATE('B',3000) + REPLICATE('C',3000) + ''')'

exec sp_executesql @t
</code>```

Body:
I have this dynamic SQL in a stored procedure:

Declare @template nvarchar(max)
Declare @publishdetails nvarchar(max)

set @publishdetails= ',B.[PublishedBy]=suser_name(),
  B.[PublishedDate]=GETDATE() '

set @template='if NOT EXISTS(select * from ' +@DestinationDB+ '.[CLs] where id='+ str(@slid)+')
insert into  ' +@DestinationDB+ '.CLs (id,slid,slversion) VALUES ( '+ str(@id)+','+ str(@slid)+','+str(@slversion)+')

update  B set
      B.[Clientid]=A.clientid,
        --.........
      B.[CreatedDate] = A.CreatedDate,
      B.[ModifiedDate] = A.ModifiedDate,
      B.[CreatedBy] = A.CreatedBy,
      B.[ModifiedBy] = A.ModifiedBy '+@publishdetails+ --Added publishdetails
    'FROM  ' + @SourceDB + '.[CLs] as A, '+ @DestinationDB+ '.[CLs] as B
        where A.slversion = '+ str(@slversion)+' and A.id='+str(@slid) + 'B.slversion = '+ str(@slversion)+' and B.id='+str(@slid)

        print 'template is: ' + @template
exec sp_Executesql @template

When exec sp_Executesql @template is executing, it fails. Because @template is > 4000 chars and is truncated. How can I split it in chunks and execute it the correct way?

Body:
You don't need to split the text into parts. You do need to make sure that truncation doesn't occur whilst you're concatenating strings:

If the result of the concatenation of strings exceeds the limit of 8,000 bytes, the result is truncated. However, if at least one of the strings concatenated is a large value type, truncation does not occur.

So, make sure that the first concatenation is working with a large value type (and thus produces a large value type as its result) and every subsequent concatenation should be saved from truncation:

set @template=CONVERT(nvarchar(max),'if NOT EXISTS(select * from ' ) + @DestinationDB + ...

(In this way, you don't have to insert conversions everywhere)

This generates an error:

declare @t nvarchar(max)

set @t = 'select LEN(''' + REPLICATE('A',3000) + REPLICATE('B',3000) + REPLICATE('C',3000) + ''')'

exec sp_executesql @t

And this produces the result 9000:

declare @t nvarchar(max)

set @t = CONVERT(nvarchar(max),'select LEN(''') + REPLICATE('A',3000) + REPLICATE('B',3000) + REPLICATE('C',3000) + ''')'

exec sp_executesql @t


问:
Connection refused to MongoDB errno 111
I have a Linode server running Ubuntu 12.04 LTS and MongoDB instance (service is running and CAN connect locally) that I can't connect to from an outside source.

I have added these two rules to my IP tables, where < ip address > is the server I want to connect FROM (as outlined in this MongoDB reference):

iptables -A INPUT -s < ip-address > -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT

iptables -A OUTPUT -d < ip-address > -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT

And I see the rule in my IP table allowing connections on 27017 to and from < ip address > however when I try to connect from , < ip address > to my mongo database using a command like this:

mongo databasedomain/databasename -u username -p password

I get this error:

2014-07-22T23:54:03.093+0000 warning: Failed to connect to databaseserverip:27017, reason: errno:111 Connection refused
2014-07-22T23:54:03.094+0000 Error: couldn't connect to server < ip address >:27017 (databaseserverip), connection attempt failed at src/mongo/shell/mongo.js:148
exception: connect failed

Any help is VERY APPRECIATED!!!! Thanks!!!

答: I also had the same issue.Make a directory in dbpath.In my case there wasn't a directory in /data/db .So i created one.Now its working.Make sure to give permission to that directory. </p>

Title: Connection refused to MongoDB errno 111


问:
property inside local date time in thymeleaf
LocalDateTime as application.property

My application.properties looks like this:

date.format='dd-MM-yyyy'

```<code><p th:text="${#temporals.format(localDateTime, 'dd-MM-yyyy')}"></p>
</code>```

How to replace 'dd-MM-yyyy' wit my property?

答:
You can get property from @environment.

```<code>@environment.getProperty('date.format')
</code>```

But this will not solve it for you, next step is to preprocess this expression with __ notation

```<code><p th:text="${#temporals.format(localDateTime, __${@environment.getProperty('date.format')}__)}">
</code>```

But even this version will not work, because you format needs quotes
format(localDateTime, 'dd-MM-yyyy') and you are passing
format(localDateTime, dd-MM-yyyy) so the final working version
should look like this:

```<code><p th:text="${#temporals.format(localDateTime, __${''''+@environment.getProperty('date.format')+''''}__)}">
</code>```

So as you can see it is much easier to just pass format from controller)

Body:
LocalDateTime as application.property

My application.properties looks like this:

date.format='dd-MM-yyyy'

How to replace 'dd-MM-yyyy' wit my property?

Body:
You can get property from @environment.

@environment.getProperty('date.format')

But this will not solve it for you, next step is to preprocess this expression with __ notation

<p th:text="${#temporals.format(localDateTime, __${@environment.getProperty('date.format')}__)}">

But even this version will not work, because you format needs quotes
format(localDateTime, 'dd-MM-yyyy') and you are passing
format(localDateTime, dd-MM-yyyy) so the final working version
should look like this:

<p th:text="${#temporals.format(localDateTime, __${''''+@environment.getProperty('date.format')+''''}__)}">

So as you can see it is much easier to just pass format from controller)


问:
Java - Search and Delete an object from Arraylist
so I have class Customer and class Bank , a bank class has methods of adding Customer to an arraylist of Customers , and also must have a method to search a Customer in an arraylist and delete it (Remove from arraylist) , How can I do it?

Bank class -

```<code>private ArrayList<Customer> customers = new ArrayList<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.add(customer);
    System.out.println("new customer " + customer.getName() + " added");
}

public void deleteAccount(String name){

}
</code>```

Customer class -

```<code>private String name;
private double balance;

public Customer(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return "Customer " +
            "name :'" + name + '\'' +
            '}';
}
</code>```

Main -

```<code>public static void deleteAccount(){
    System.out.println("Enter the name you want to delete");
    String name = scanner.nextLine();
    scanner.nextLine();
    bank.deleteAccount(name);
}
</code>```

As you can see, the main class has method which takes input type String from user and then calles Bank class's method of deleteAccount with that input , but I don't know how to proceed with the deleteAccount method, how to make it work ?

I need something that firstly checks if the user input is in the Arraylist, and then remove it from there if there is.

I do realize that input is String and Arraylist is Customer instances , but Customer only takes String name in constractor, so can I make it work this way?

答:
Deleting account by name is not proper way. Because there is chance of multiple customers with same name. So delete account wiht account number will be right option.

Still you want delete account by customer name then check following:

```<code>Customer custToDelete = null;
for(Customer customer:customers){
        if(customer.getName().equals(name))
        custToDelete = customer;
}

if(custToDelete==null)
    System.out.println("No customer found");
else
    customers.remove(custToDelete);
</code>```

Body:
so I have class Customer and class Bank , a bank class has methods of adding Customer to an arraylist of Customers , and also must have a method to search a Customer in an arraylist and delete it (Remove from arraylist) , How can I do it?

Bank class -

private ArrayList<Customer> customers = new ArrayList<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.add(customer);
    System.out.println("new customer " + customer.getName() + " added");
}

public void deleteAccount(String name){

}

Customer class -

private String name;
private double balance;

public Customer(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return "Customer " +
            "name :'" + name + '\'' +
            '}';
}

Main -

public static void deleteAccount(){
    System.out.println("Enter the name you want to delete");
    String name = scanner.nextLine();
    scanner.nextLine();
    bank.deleteAccount(name);
}

As you can see, the main class has method which takes input type String from user and then calles Bank class's method of deleteAccount with that input , but I don't know how to proceed with the deleteAccount method, how to make it work ?

I need something that firstly checks if the user input is in the Arraylist, and then remove it from there if there is.

I do realize that input is String and Arraylist is Customer instances , but Customer only takes String name in constractor, so can I make it work this way?

Body:
Deleting account by name is not proper way. Because there is chance of multiple customers with same name. So delete account wiht account number will be right option.

Still you want delete account by customer name then check following:

Customer custToDelete = null;
for(Customer customer:customers){
        if(customer.getName().equals(name))
        custToDelete = customer;
}

if(custToDelete==null)
    System.out.println("No customer found");
else
    customers.remove(custToDelete);


问:
How to trigger update action in Phoenix Controller?
Under the update test I use:

```<code>%{resp_body: body} = conn
|> sign_in
|> patch(asset_path(conn, :update), Poison.encode!(payload))
</code>```

I get this error:

```<code> ** (ArgumentError) No action :update for helper Web.Router.Helpers.asset_path/2. The following actions/clauses are supported:

     asset_path(conn_or_endpoint, :create, , opts \\ [])
     asset_path(conn_or_endpoint, :delete, id, opts \\ [])
     asset_path(conn_or_endpoint, :edit, id, opts \\ [])
     asset_path(conn_or_endpoint, :index, , opts \\ [])
     asset_path(conn_or_endpoint, :new, , opts \\ [])
     asset_path(conn_or_endpoint, :show, id, opts \\ [])
     asset_path(conn_or_endpoint, :update, id, opts \\ [])
 code: |> post(asset_path(conn, :update), Poison.encode!(payload))
 stacktrace:
   (phoenix) lib/phoenix/router/helpers.ex:299: Phoenix.Router.Helpers.raise_route_error/5
   test/controllers/asset_controller_test.exs:167: (test)
</code>```

When I use Postman to test it directly it works fine though.

I have used post(asset_path(conn, :create), Poison.encode!(payload)) in the insert action and it works fine.

Here is the snapshot of postman to show that code works fine, test fails.

答: You can check by typing mix phx.routes. The update action always require id to work. so pass the id and it should work

Body:
Under the update test I use:

%{resp_body: body} = conn
|> sign_in
|> patch(asset_path(conn, :update), Poison.encode!(payload))

I get this error:

 ** (ArgumentError) No action :update for helper Web.Router.Helpers.asset_path/2. The following actions/clauses are supported:

     asset_path(conn_or_endpoint, :create, , opts \\ [])
     asset_path(conn_or_endpoint, :delete, id, opts \\ [])
     asset_path(conn_or_endpoint, :edit, id, opts \\ [])
     asset_path(conn_or_endpoint, :index, , opts \\ [])
     asset_path(conn_or_endpoint, :new, , opts \\ [])
     asset_path(conn_or_endpoint, :show, id, opts \\ [])
     asset_path(conn_or_endpoint, :update, id, opts \\ [])
 code: |> post(asset_path(conn, :update), Poison.encode!(payload))
 stacktrace:
   (phoenix) lib/phoenix/router/helpers.ex:299: Phoenix.Router.Helpers.raise_route_error/5
   test/controllers/asset_controller_test.exs:167: (test)

When I use Postman to test it directly it works fine though.

I have used post(asset_path(conn, :create), Poison.encode!(payload)) in the insert action and it works fine.

Here is the snapshot of postman to show that code works fine, test fails.


问:
class library security & license technology
I asked a question regarding assembly security and someone told me few things:

You could invoke a licensing technology when the library was to be instantiated. What I've done in the past is include a public key as a resource to the dll, and then look for a license xml document with a cryptographic signature signed with my private key. As long as I keep close track of my private key, it's pretty difficult to defeat.

After reading this I have some questions:

How to invoke my licensing technology when I'm developing a class library?

How to add a public key as a resource to the assembly?

How to look for a license xml document with a cryptographic signature signed with my private key and from where & when to look?

It will be better if anyone please help me to understand the things in detail to implement the above security. Thanks a lot.

答:
"Licensing technology" is basically the methods he goes into more detail about in the rest of the paragraph. A "license" is little more than proof of permission for an actor (either the user themselves, or other code being run on their behalf) to use your code. It doesn't have to be some universal standard like an SSL certificate. It just needs to be known to you, and difficult to fake by others.

As for resources, this is just something inherent in .Net. in VS Solution Explorer, go to the project you want to be able to access your restricted DLL from. The first item in its expanded contents will be a Properties folder; under that you should find an item Resources.resx. Open it up and you'll get a GUI that will allow you to reference strings, images, plain text files, etc. which can be compiled into or kept alongside the DLL when the solution is built. This is where you'd specify a string that is some encrypted, known value. Probably the most secure string to encrypt would be the strong name or GUID of the assembly, because then you could compare what you decrypt with the assembly information of the caller, preventing someone from getting the encrypted string out of one of your libraries and using it in theirs. In your restricted DLL, you can use the same feature to store the decryption key you will use to decode the string provided by calling DLLs.

There are numerous resources available for tutorials on how to use RSA encryption (the encryption method inferred here) in .NET. There is an RsaCryptoServiceProvider that will perform encryption/decryption, generate keys, etc; all you have to do is drop it in. Something that may be confusing is that in asymmetric-key algorithms like RSA, data is usually encrypted using the "public" key and decrypted using the "private" key. This is because assymmetric keys are usually used over public communication channels, and you need to give the remote party a key they can use to write messages that you will then decode. However, in this case, your restricted DLL must decrypt the data it needs to compare, and so it needs a fixed "private key". This makes the decryption key "public" to anyone with .NET Reflector or some similar disassembler. However, if you, the developer, are the only one that can provide encrypted strings to DLLs that are authorized to access your DLL, then you can keep the encryption key secret.


问:
Bash-shell two file match successfully , but output wrong
```<code>cat file1.txt
cheng 600
huang 500
pan 400
yin 300

cat file2.txt
600 a
300 c
</code>```

when  I execute the command:

```<code>awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$1]}' f2.txt f1.txt
</code>```

The output is below:

```<code> cheng 600
 yin 300
</code>```

But i expected should be like this:

```<code> cheng 600 a
 yin 300 c
</code>```

what's wrong?

答:
You can use:</p>

```<code>awk 'NR==FNR{a[$1]=$2; next} $2 in a{print $0, a[$2]}' f2.txt f1.txt

cheng 600 a
yin 300 c
</code>```

Body:
cat file1.txt
cheng 600
huang 500
pan 400
yin 300

cat file2.txt
600 a
300 c

when  I execute the command:

awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$1]}' f2.txt f1.txt

The output is below:

 cheng 600
 yin 300

But i expected should be like this:

 cheng 600 a
 yin 300 c

what's wrong?

Body:
You can use:

awk 'NR==FNR{a[$1]=$2; next} $2 in a{print $0, a[$2]}' f2.txt f1.txt

cheng 600 a
yin 300 c


问:
How to get comparable and reproducible results from LogisticRegressionCV and GridSearchCV
I want to score different classifiers with different parameters.

For speedup on LogisticRegression I use LogisticRegressionCV (which at least 2x faster) and plan use GridSearchCV for others.

But problem while it give me equal C parameters, but not the AUC ROC scoring.

I'll try fix many parameters like scorer, random_state, solver, max_iter, tol...
Please look at example (real data have no mater):

Test data and common part:

```<code>from sklearn import datasets
boston = datasets.load_boston()
X = boston.data
y = boston.target
y[y <= y.mean()] = 0; y[y > 0] = 1

import numpy as np
from sklearn.cross_validation import KFold
from sklearn.linear_model import LogisticRegression
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegressionCV

fold = KFold(len(y), n_folds=5, shuffle=True, random_state=777)
</code>```

GridSearchCV

```<code>grid = {
    'C': np.power(10.0, np.arange(-10, 10))
     , 'solver': ['newton-cg']
}
clf = LogisticRegression(penalty='l2', random_state=777, max_iter=10000, tol=10)
gs = GridSearchCV(clf, grid, scoring='roc_auc', cv=fold)
gs.fit(X, y)

print ('gs.best_score_:', gs.best_score_)
</code>```

gs.best_score_: 0.939162082194

LogisticRegressionCV

```<code>searchCV = LogisticRegressionCV(
    Cs=list(np.power(10.0, np.arange(-10, 10)))
    ,penalty='l2'
    ,scoring='roc_auc'
    ,cv=fold
    ,random_state=777
    ,max_iter=10000
    ,fit_intercept=True
    ,solver='newton-cg'
    ,tol=10
)
searchCV.fit(X, y)

print ('Max auc_roc:', searchCV.scores_[1].max())
</code>```

Max auc_roc: 0.970588235294

Solver newton-cg used just to provide fixed value, other tried too.
What I forgot?

P.S. In both cases I also got warning "/usr/lib64/python3.4/site-packages/sklearn/utils/optimize.py:193: UserWarning: Line Search failed
warnings.warn('Line Search failed')" which I can't understand too. I'll be happy if someone also describe what it mean, but I hope it is not relevant to my main question.

EDIT UPDATES

By @joeln comment add max_iter=10000 and tol=10 parameters too. It does not change result in any digit, but the warning disappeared.

答:
Here is a copy of the answer by Tom on the scikit-learn issue tracker:

LogisticRegressionCV.scores_ gives the score for all the folds.
GridSearchCV.best_score_ gives the best mean score over all the folds.

To get the same result, you need to change your code:

```<code>print('Max auc_roc:', searchCV.scores_[1].max())  # is wrong
print('Max auc_roc:', searchCV.scores_[1].mean(axis=0).max())  # is correct
</code>```

By also using the default tol=1e-4 instead of your tol=10, I get:

```<code>('gs.best_score_:', 0.939162082193857)
('Max auc_roc:', 0.93915947999923843)
</code>```

The (small) remaining difference might come from warm starting in LogisticRegressionCV (which is actually what makes it faster than GridSearchCV).

ContentLicense: CC BY-SA 4.0

Body:
I want to score different classifiers with different parameters.

For speedup on LogisticRegression I use LogisticRegressionCV (which at least 2x faster) and plan use GridSearchCV for others.

But problem while it give me equal C parameters, but not the AUC ROC scoring.

I'll try fix many parameters like scorer, random_state, solver, max_iter, tol...
Please look at example (real data have no mater):

Test data and common part:

from sklearn import datasets
boston = datasets.load_boston()
X = boston.data
y = boston.target
y[y <= y.mean()] = 0; y[y > 0] = 1

import numpy as np
from sklearn.cross_validation import KFold
from sklearn.linear_model import LogisticRegression
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegressionCV

fold = KFold(len(y), n_folds=5, shuffle=True, random_state=777)

GridSearchCV

grid = {
    'C': np.power(10.0, np.arange(-10, 10))
     , 'solver': ['newton-cg']
}
clf = LogisticRegression(penalty='l2', random_state=777, max_iter=10000, tol=10)
gs = GridSearchCV(clf, grid, scoring='roc_auc', cv=fold)
gs.fit(X, y)

print ('gs.best_score_:', gs.best_score_)

gs.best_score_: 0.939162082194

LogisticRegressionCV

searchCV = LogisticRegressionCV(
    Cs=list(np.power(10.0, np.arange(-10, 10)))
    ,penalty='l2'
    ,scoring='roc_auc'
    ,cv=fold
    ,random_state=777
    ,max_iter=10000
    ,fit_intercept=True
    ,solver='newton-cg'
    ,tol=10
)
searchCV.fit(X, y)

print ('Max auc_roc:', searchCV.scores_[1].max())

Max auc_roc: 0.970588235294

Solver newton-cg used just to provide fixed value, other tried too.
What I forgot?

P.S. In both cases I also got warning "/usr/lib64/python3.4/site-packages/sklearn/utils/optimize.py:193: UserWarning: Line Search failed
warnings.warn('Line Search failed')" which I can't understand too. I'll be happy if someone also describe what it mean, but I hope it is not relevant to my main question.

EDIT UPDATES

By @joeln comment add max_iter=10000 and tol=10 parameters too. It does not change result in any digit, but the warning disappeared.

Body:
Here is a copy of the answer by Tom on the scikit-learn issue tracker:

LogisticRegressionCV.scores_ gives the score for all the folds.
GridSearchCV.best_score_ gives the best mean score over all the folds.

To get the same result, you need to change your code:

print('Max auc_roc:', searchCV.scores_[1].max())  # is wrong
print('Max auc_roc:', searchCV.scores_[1].mean(axis=0).max())  # is correct

By also using the default tol=1e-4 instead of your tol=10, I get:

('gs.best_score_:', 0.939162082193857)
('Max auc_roc:', 0.93915947999923843)

The (small) remaining difference might come from warm starting in LogisticRegressionCV (which is actually what makes it faster than GridSearchCV).


问:
i don't understand where i am doing the mistake. i am using eclipse neon IDE for this code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${'Welcome to SevenMentor'}"/>
```

<p>Output:</p>

```HTTP Status 500 – Internal Server Error
```

<p>Type Exception Report</p>

<pre class="lang-none prettyprint-override"><code>Message The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Description The server encountered an unexpected condition that prevented it from fulfilling the request.
</code>```

Exception

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:55)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:293)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:80)
    org.apache.jasper.compiler.TagLibraryInfoImpl.generateTldResourcePath(TagLibraryInfoImpl.java:251)
    org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:122)
    org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:434)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:492)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1448)
    org.apache.jasper.compiler.Parser.parse(Parser.java:145)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:244)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:105)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:201)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:372)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:349)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:333)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:600)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:368)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Note The full stack trace of the root cause is available in the server logs.
```

Apache Tomcat/8.5.14

答:
Your error basically says that necessary jar files are missing.

If it's a maven project then please add the dependencies.

If it's a normal project. please download and add the jar files in the eclipse
  web directory.

Seeing the error, i guess you need jsp libraries and jstl libraries.

Body:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${'Welcome to SevenMentor'}"/>

Output:

HTTP Status 500 – Internal Server Error

Type Exception Report

Message The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:55)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:293)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:80)
    org.apache.jasper.compiler.TagLibraryInfoImpl.generateTldResourcePath(TagLibraryInfoImpl.java:251)
    org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:122)
    org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:434)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:492)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1448)
    org.apache.jasper.compiler.Parser.parse(Parser.java:145)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:244)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:105)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:201)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:372)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:349)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:333)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:600)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:368)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Note The full stack trace of the root cause is available in the server logs.

Apache Tomcat/8.5.14


问:
Input date prefilled with current year
I have input date field and I want to prefilled it with current year only, so that whenever user want to update that field, he/she don't have to specify year each time, the field always prefilled with current year and user will edit date and month. If user want to edit year it is possible.

```<code><input type="date" />
</code>```

It is about year only, what i want to do is when specifically editing with keyboard, user shouldn't type year everytime, because in most of the cases the year will be current year.

答:
use following code to manage it</p>

```<code>var date = new Date();
var fullYear = date.getFullYear();
$("input[type='date']").val(fullYear);
</code>```

Title: Input date prefilled with current year

Body:
I have input date field and I want to prefilled it with current year only, so that whenever user want to update that field, he/she don't have to specify year each time, the field always prefilled with current year and user will edit date and month. If user want to edit year it is possible.

<input type="date" />

It is about year only, what i want to do is when specifically editing with keyboard, user shouldn't type year everytime, because in most of the cases the year will be current year.

Body:
use following code to manage it

var date = new Date();
var fullYear = date.getFullYear();
$("input[type='date']").val(fullYear);


答:
I prefer using Map so delete/exists will be in O(1) instead of O(n)

```<code>public class Bank {
private Map<String,Customer> customers = new HashMap<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.put(customer.getName(),customer);
    System.out.println("new customer " + customer.getName() + " added");
}

// O(1) -- no need to iterate over an array for deleting customer
public boolean deleteAccount(String name){
    if(customers.containsKey(name)){
        customers.remove(name);
        return true;
    }
    return false;
}

@Override
public String toString() {
    return "Bank{" +
            "customers=" + customers +
            '}';
}

public static void main(String[] args){

    Bank bank = new Bank();                 // create Bank object

    bank.addCustomer("Jhon");       // insert some customer
    bank.addCustomer("Doe");
    System.out.println(bank);
    bank.deleteAccount("Yossi");    // not exists - return false
    bank.deleteAccount("Doe");      // removed - return true

    System.out.println(bank);

}
</code>```

}

Hop this help a bit...

Title: Java - Search and Delete an object from Arraylist

Body:
I prefer using Map so delete/exists will be in O(1) instead of O(n)

public class Bank {
private Map<String,Customer> customers = new HashMap<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.put(customer.getName(),customer);
    System.out.println("new customer " + customer.getName() + " added");
}

// O(1) -- no need to iterate over an array for deleting customer
public boolean deleteAccount(String name){
    if(customers.containsKey(name)){
        customers.remove(name);
        return true;
    }
    return false;
}

@Override
public String toString() {
    return "Bank{" +
            "customers=" + customers +
            '}';
}

public static void main(String[] args){

    Bank bank = new Bank();                 // create Bank object

    bank.addCustomer("Jhon");       // insert some customer
    bank.addCustomer("Doe");
    System.out.println(bank);
    bank.deleteAccount("Yossi");    // not exists - return false
    bank.deleteAccount("Doe");      // removed - return true

    System.out.println(bank);

}

}

Hop this help a bit...


问:
How to make overflow-y scroll without changing overflow-x to auto?
I know this is a duplicated question.

And below link is the answer the most nearest with my question that I've found.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

In this link, the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as
  their specified values, except that some combinations with ‘visible’
  are not possible: if one is specified as ‘visible’ and the other is
  ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed
  value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if
  ‘overflow-y’ is the same; otherwise it is the pair of computed values
  of ‘overflow-x’ and ‘overflow-y’.

What I want to know is, are there any new solution of this.

The problem of mine is in this fiddle.

I made 'sidebar' class of 'BootStrap' simple in a fiddle of mine.

```<code>overflow-x: visible;
//overflow-y: scroll;
</code>```

You can see that I commented out 'overflow-y: scroll' of class '.panel' in css part.

In this case, 'hover' will work but 'scroll' won't.

When if I clear that comment out, 'hover' won't work but 'scroll' will.

What I wanna see is, 'hover' and 'scroll' working together.

Does anyone have any ways or ideas to fix this?

Or are there still no way to solve this problem?

答:
I liked this question.

So, I have created a fiddle here: https://jsfiddle.net/n4tvvora/4/

Its comes pretty close to what you need (I think). Let me know if it does NOT suit your requirement. We can make it better.

Code highlights:

```<code>.panel:hover ul.list:first-child {
    position: absolute;
    display: inline-block;
    height: 100%;
    width: auto;
    overflow-y: auto;
    overflow-x: hidden;
}

.panel ul.list:first-child {
    display: block;
}
</code>```

Body:
I know this is a duplicated question.

And below link is the answer the most nearest with my question that I've found.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

In this link, the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as
  their specified values, except that some combinations with ‘visible’
  are not possible: if one is specified as ‘visible’ and the other is
  ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed
  value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if
  ‘overflow-y’ is the same; otherwise it is the pair of computed values
  of ‘overflow-x’ and ‘overflow-y’.

What I want to know is, are there any new solution of this.

The problem of mine is in this fiddle.

I made 'sidebar' class of 'BootStrap' simple in a fiddle of mine.

overflow-x: visible;
//overflow-y: scroll;

You can see that I commented out 'overflow-y: scroll' of class '.panel' in css part.

In this case, 'hover' will work but 'scroll' won't.

When if I clear that comment out, 'hover' won't work but 'scroll' will.

What I wanna see is, 'hover' and 'scroll' working together.

Does anyone have any ways or ideas to fix this?

Or are there still no way to solve this problem?

Body:
I liked this question.

So, I have created a fiddle here: https://jsfiddle.net/n4tvvora/4/

Its comes pretty close to what you need (I think). Let me know if it does NOT suit your requirement. We can make it better.

Code highlights:

.panel:hover ul.list:first-child {
    position: absolute;
    display: inline-block;
    height: 100%;
    width: auto;
    overflow-y: auto;
    overflow-x: hidden;
}

.panel ul.list:first-child {
    display: block;
}