问:
How to add password fields to a default WordPress registration?
I woulrd like to enable users to choose their own passord, but keep a verification email(without reseting password link)?

I am adding an input field for the password in wp-login:

```<code><input type="password" name="user_password" value="" placeholder="Password" id="user_password" class="input" />
</code>```

Than, I have a custom plugin thats sets user's password:

```<code>function myplugin_registration_change_pass( $user_id )

{if ( isset( $_POST['user_password'] ) )
    wp_set_password( $_POST['user_password'], $user_id );}
</code>```

For some reason I keep getting verification email asking the user to set a password.
ANy ideas how I can solve this?

答:
Try this code</p>

```<code>  function frontend_register(){

    $gfemail        = $_POST['user_email'];
    $firstname      = $_POST['user_firstname'];
    $lastname       = $_POST['user_lastname'];
    $password       = $_POST['user_password'];

    if (email_exists( $gfemail ) === false) {

      $password             =   esc_attr( $password );
      $email                =   sanitize_email( $gfemail );
      $first_name               =   sanitize_text_field( $firstname );
      $last_name                =   sanitize_text_field( $lastname );

      $userdata = array(
          'user_login'    =>        $email,
          'user_email'    =>    $email,
          'user_pass'     =>    $password,
          'role'                =>   'subscriber',
          'first_name'    =>    $first_name,
          'last_name'     =>    $last_name,
          );
      $new_user = wp_insert_user ( $userdata );

      if(!is_wp_error($new_user)){

        $headers = 'Content-type: text/html;charset=utf-8' . "\r\n";
        $headers .= 'From: Your SiteName <test@test.com>' . "\r\n";

        $verifyCode = sha1($new_user.$email);

        update_user_meta( $new_user, 'email_confirmation_done', 'No');
        update_user_meta( $new_user, 'email_confirmation_code', $verifyCode);

        $subject = 'Please verify your account' . "\r\n";

        $mkUrl = sprintf('<a href="%s?verifycode=%s&user_login=%s">click here</a>', $wpgsloginpage, $verifyCode, $email);
        $message = sprintf('<p>Dear %s,</p><br> ', $first_name);
        $message .= sprintf('<hr>');
        $message .= sprintf('<p><strong>Please verify your account by clicking on this link %s </strong></p>', $mkUrl);
        $message .= sprintf('<hr>');
        $message .= sprintf('<br><p style="font-size:12.8px">Thank you for registering<br><br>');
        wp_mail($email, $subject, $message, $headers);
        die("success");
      }
    }else{
        die("failure");
    }

}

if ( ! function_exists( 'wp_new_user_notification' ) ) :
function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {
    return;
}
endif;
</code>```

Body:
I woulrd like to enable users to choose their own passord, but keep a verification email(without reseting password link)?

I am adding an input field for the password in wp-login:

<input type="password" name="user_password" value="" placeholder="Password" id="user_password" class="input" />

Than, I have a custom plugin thats sets user's password:

function myplugin_registration_change_pass( $user_id )

{if ( isset( $_POST['user_password'] ) )
    wp_set_password( $_POST['user_password'], $user_id );}

For some reason I keep getting verification email asking the user to set a password.
ANy ideas how I can solve this?

Body:
Try this code

  function frontend_register(){

    $gfemail        = $_POST['user_email'];
    $firstname      = $_POST['user_firstname'];
    $lastname       = $_POST['user_lastname'];
    $password       = $_POST['user_password'];

    if (email_exists( $gfemail ) === false) {

      $password             =   esc_attr( $password );
      $email                =   sanitize_email( $gfemail );
      $first_name               =   sanitize_text_field( $firstname );
      $last_name                =   sanitize_text_field( $lastname );

      $userdata = array(
          'user_login'    =>        $email,
          'user_email'    =>    $email,
          'user_pass'     =>    $password,
          'role'                =>   'subscriber',
          'first_name'    =>    $first_name,
          'last_name'     =>    $last_name,
          );
      $new_user = wp_insert_user ( $userdata );

      if(!is_wp_error($new_user)){

        $headers = 'Content-type: text/html;charset=utf-8' . "\r\n";
        $headers .= 'From: Your SiteName <test@test.com>' . "\r\n";

        $verifyCode = sha1($new_user.$email);

        update_user_meta( $new_user, 'email_confirmation_done', 'No');
        update_user_meta( $new_user, 'email_confirmation_code', $verifyCode);

        $subject = 'Please verify your account' . "\r\n";

        $mkUrl = sprintf('<a href="%s?verifycode=%s&user_login=%s">click here</a>', $wpgsloginpage, $verifyCode, $email);
        $message = sprintf('<p>Dear %s,</p><br> ', $first_name);
        $message .= sprintf('<hr>');
        $message .= sprintf('<p><strong>Please verify your account by clicking on this link %s </strong></p>', $mkUrl);
        $message .= sprintf('<hr>');
        $message .= sprintf('<br><p style="font-size:12.8px">Thank you for registering<br><br>');
        wp_mail($email, $subject, $message, $headers);
        die("success");
      }
    }else{
        die("failure");
    }

}

if ( ! function_exists( 'wp_new_user_notification' ) ) :
function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {
    return;
}
endif;


来源: stackexchange

问:
Issue when embedding image in email body with PHPMailer
I want to generate a QR code using the phpqrcode library and send it as an image embedded in the email body (without attaching it to the email). I am using the PHPMailer library to create and send the email.

The code I am using is as follows

```<code><?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

include ('../phpqrcode/qrlib.php');
ob_start();
QRcode::png('TextToGenerateTheQRCodeFrom');
$imageString = base64_encode( ob_get_contents() );
ob_end_clean();

$mail = new PHPMailer;
$mail->setFrom( 'testqrsend@testqrsend.sdf', 'Test QR sender');
$mail->addAddress('xxxxxxxxxxx', 'John Doe');
$mail->Subject  = 'QR code';
$mail->isHTML(true);
$mail->addStringEmbeddedImage($imageString,'qrcode');

$mail->Body = "<p> Your QR code </p><img src=\"cid:qrcode\" />";

if(!$mail->send()) {
  echo 'Message was not sent.';
  echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
  echo 'Message has been sent.';
}
?>
</code>```

This is the email I receive.

.

As you can see, the image is not embedded within the email body. However there is a file attached. That file is a text file and contains the base64 value of the image.

What am I doing wrong and what can I do to fix it?

答:
It would help if you read the documentation on the function you're using. This is linked from the readme, also on the project page on github.

The reason this is if not working is that you're passing it some binary data without telling it what kind of thing it is, so it falls back to a generic application/octet-stream MIME type, which will appear as a generic attachment, as you're seeing.

Chris' example works because he also supplied a filename containing an extension, and PHPMailer uses that to derive a MIME type (if it can) if you don't provide an explicit MIME type in the call to addStringEmbeddedImage.

In short, change your call to this:

```<code>$mail->addStringEmbeddedImage($imageString, 'qrcode', 'qrcode.png');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to generate a QR code using the phpqrcode library and send it as an image embedded in the email body (without attaching it to the email). I am using the PHPMailer library to create and send the email.

The code I am using is as follows

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

include ('../phpqrcode/qrlib.php');
ob_start();
QRcode::png('TextToGenerateTheQRCodeFrom');
$imageString = base64_encode( ob_get_contents() );
ob_end_clean();

$mail = new PHPMailer;
$mail->setFrom( 'testqrsend@testqrsend.sdf', 'Test QR sender');
$mail->addAddress('xxxxxxxxxxx', 'John Doe');
$mail->Subject  = 'QR code';
$mail->isHTML(true);
$mail->addStringEmbeddedImage($imageString,'qrcode');

$mail->Body = "
 Your QR code
";

if(!$mail->send()) {
  echo 'Message was not sent.';
  echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
  echo 'Message has been sent.';
}
?>

This is the email I receive.

.

As you can see, the image is not embedded within the email body. However there is a file attached. That file is a text file and contains the base64 value of the image.

What am I doing wrong and what can I do to fix it?

Body:
It would help if you read the documentation on the function you're using. This is linked from the readme, also on the project page on github.

The reason this is if not working is that you're passing it some binary data without telling it what kind of thing it is, so it falls back to a generic application/octet-stream MIME type, which will appear as a generic attachment, as you're seeing.

Chris' example works because he also supplied a filename containing an extension, and PHPMailer uses that to derive a MIME type (if it can) if you don't provide an explicit MIME type in the call to addStringEmbeddedImage.

In short, change your call to this:

$mail->addStringEmbeddedImage($imageString, 'qrcode', 'qrcode.png');


问:
WCFclient operation only Async .Net core 2.0
I added wcf services end point in asp.net core 2.0 to connected services and then I try to use that but with client there is only functions which ended with ..async

I don't want to use ...async.But there is no function without .async

What is problem with this?What should I do?

instead of using that

```<code> var response = SystemClient.SearchCountriesAsync(....
</code>```

I want to use that

```<code> var response = SystemClient.SearchCountries(...
</code>```

but it give that error

Error   CS1061  'SystemClient' does not contain a definition for 'SearchCountries' and no extension method 'SearchCountries' accepting a first argument of type 'SystemClient' could be found (are you missing a using directive or an assembly reference?)

答:
Your client does not expose synchronous method but that shouldn't be a problem for you.

Instead of asynchronously calling the method just do this:

```<code>response = SystemClient.SearchAirportsAsync(credentials, SystemHelperLanguageTypes.English, SystemHelperSearchTypes.CodeSearch, "ist").Result;
</code>```

This will call the method synchronously as it will block the call. Check John Skeets answer here.

That being said I would recomend you use the async method that is provided. To support that you would have to change the Action signature to this:

```<code>public async Task<IActionResullt> Index()
{
   SystemClient SystemClient = new SystemClient();
   Credential credential = new Credential();
   credential.UserName = "username";
   credential.UserPassword = "****";

   var response1 = await SystemClient.SearchCountriesAsync(credentials, SystemHelperLanguageTypes.English, SystemHelperSearchTypes.CodeSearch, "TR");
   var response = await SystemClient.SearchAirportsAsync(credentials, SystemHelperLanguageTypes.English, SystemHelperSearchTypes.CodeSearch, "ist");

   //Do whatever you do with those responses

   ViewBag.Language = "ar";
   return View();
}
</code>```

Body:
I added wcf services end point in asp.net core 2.0 to connected services and then I try to use that but with client there is only functions which ended with ..async

I don't want to use ...async.But there is no function without .async

What is problem with this?What should I do?

instead of using that

 var response = SystemClient.SearchCountriesAsync(....

I want to use that

 var response = SystemClient.SearchCountries(...

but it give that error

Error   CS1061  'SystemClient' does not contain a definition for 'SearchCountries' and no extension method 'SearchCountries' accepting a first argument of type 'SystemClient' could be found (are you missing a using directive or an assembly reference?)

Body:
Your client does not expose synchronous method but that shouldn't be a problem for you.

Instead of asynchronously calling the method just do this:

response = SystemClient.SearchAirportsAsync(credentials, SystemHelperLanguageTypes.English, SystemHelperSearchTypes.CodeSearch, "ist").Result;

This will call the method synchronously as it will block the call. Check John Skeets answer here.

That being said I would recomend you use the async method that is provided. To support that you would have to change the Action signature to this:

public async Task<IActionResullt> Index()
{
   SystemClient SystemClient = new SystemClient();
   Credential credential = new Credential();
   credential.UserName = "username";
   credential.UserPassword = "****";

   var response1 = await SystemClient.SearchCountriesAsync(credentials, SystemHelperLanguageTypes.English, SystemHelperSearchTypes.CodeSearch, "TR");
   var response = await SystemClient.SearchAirportsAsync(credentials, SystemHelperLanguageTypes.English, SystemHelperSearchTypes.CodeSearch, "ist");

   //Do whatever you do with those responses

   ViewBag.Language = "ar";
   return View();
}


问:
How Can I read a file at preprocessing time
I need to compile my code based on version number of the project i am working on.
In short, i will read the version number from a file and enable or disable certain part of my code/.

How can i read the version number from a file at compile time in c/c++?.

I am trying to do something like this

```<code>static const unsigned int version =
#include "version"
    ;
</code>```

I am getting compiler error.

答:
file.c

```<code>#include <stdio.h>
static const float version =
#include "file.h"
;

int main()
{
 printf("Version is : %f\n", version);
}
</code>```

file.h

```<code>37.11
</code>```

basically works

Body:
I need to compile my code based on version number of the project i am working on.
In short, i will read the version number from a file and enable or disable certain part of my code/.

How can i read the version number from a file at compile time in c/c++?.

I am trying to do something like this

static const unsigned int version =
#include "version"
    ;

I am getting compiler error.

Body:
file.c

#include <stdio.h>
static const float version =
#include "file.h"
;

int main()
{
 printf("Version is : %f\n", version);
}

file.h

37.11

basically works


问:
In a While loop (php-mysql) can I have it display an entry once that has duplicates?
What I am trying to achieve is for instance I have a 2 companies that have posted 5 products. One company posted 1 product and the second company posted 4 products.

In my while loop it will show the first company that posted one product once and the second company that posted four products 4 times. What I want to do is have it just show the 2 companies that have posted products once. So if there are 5 companies all who have posted multiple products, they will not be multiplied by the amount of products they have posted but just display once as long as they have at least one product posted. Is it possible to achieve that from a query?

```<code><?php
include("database.php");
$id=$_GET['id'];
$query="SELECT * FROM dproducts, thevendor WHERE dproducts.vendor_id=thevendor.thevendor_id AND dproducts.active='1'";
$result=mysql_query($query) or die(mysql_error());
$num_rows = 0;
while($row = mysql_fetch_assoc($result))
{
$num_rows++;
?>
<br><?php echo $row['company_name']; ?><br>
<?php } ?>
</code>```

答:
You can use distinct in your MySql query.

```<code>Select distinct ...
</code>```

Body:
What I am trying to achieve is for instance I have a 2 companies that have posted 5 products. One company posted 1 product and the second company posted 4 products.

In my while loop it will show the first company that posted one product once and the second company that posted four products 4 times. What I want to do is have it just show the 2 companies that have posted products once. So if there are 5 companies all who have posted multiple products, they will not be multiplied by the amount of products they have posted but just display once as long as they have at least one product posted. Is it possible to achieve that from a query?

<?php
include("database.php");
$id=$_GET['id'];
$query="SELECT * FROM dproducts, thevendor WHERE dproducts.vendor_id=thevendor.thevendor_id AND dproducts.active='1'";
$result=mysql_query($query) or die(mysql_error());
$num_rows = 0;
while($row = mysql_fetch_assoc($result))
{
$num_rows++;
?>

<?php echo $row['company_name']; ?>

<?php } ?>

Body:
You can use distinct in your MySql query.

Select distinct ...


问:
How to create a TCP Server in Python?
I started learning networking with python can somebody help me out with this code as I am unable to connect more than 5 clients at a time. Can someone please suggest me a solution for this?</p>

```<code>def main():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', listening_port))
        s.listen(5)
        print "[*] Initializing Sockets ... Done"
        print "[*] Sockets Binded Successfully ..."
        print("[*] Server Started Successfully [%d]\n" % (listening_port))
    except Exception, e:
        print e
        sys.exit(2)
    while 1:
        try:
            conn, addr = s.accept()
            data = conn.recv(buffer_size)
            start_new_thread(conn_string, (conn, data, addr))
        except KeyboardInterrupt:
            s.close()
            print "\n[*] Proxy Server Shutting Down ..."
            sys.exit(1)
    s.close()

def conn_string(conn, data, addr):
    print conn
    print addr
    print data
</code>```

答:
As described in the python socket API:

socket.listen(backlog)

Listen for connections made to the socket. The
backlog argument specifies the maximum number of queued connections
and should be at least 0; the maximum value is system-dependent
(usually 5), the minimum value is forced to 0.

Increase the number from 5 to the number of simultaneous connections you wish to have to the server.

Title: How to create a TCP Server in Python?

Body:
I started learning networking with python can somebody help me out with this code as I am unable to connect more than 5 clients at a time. Can someone please suggest me a solution for this?

def main():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', listening_port))
        s.listen(5)
        print "[*] Initializing Sockets ... Done"
        print "[*] Sockets Binded Successfully ..."
        print("[*] Server Started Successfully [%d]\n" % (listening_port))
    except Exception, e:
        print e
        sys.exit(2)
    while 1:
        try:
            conn, addr = s.accept()
            data = conn.recv(buffer_size)
            start_new_thread(conn_string, (conn, data, addr))
        except KeyboardInterrupt:
            s.close()
            print "\n[*] Proxy Server Shutting Down ..."
            sys.exit(1)
    s.close()

def conn_string(conn, data, addr):
    print conn
    print addr
    print data


问:
Segmentation fault when reading floats from terminal input
After confirming input Segmentation fault pops up and I can't see why. I was told to use fgets and sscanf in loop to read an undefined number of floats from terminal input and this is what i came up with..

Code

```<code>#include "stdio.h"
#include "stdlib.h"
#include "string.h"

#define EMPTY 3.141592
#define BUFFERSIZE 100

void removeSubstring(char *s,const char *toremove){
  while( (s=strstr(s,toremove)) )
    memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove)));
}

int main(){

    int x=0;
    int y=0;
    float a[BUFFERSIZE] = {EMPTY};
    char buffer[BUFFERSIZE] = {EMPTY};
    char *pos;
    char *start = 0;
    int space = ' ';

    printf("Input: ");
    fgets(buffer, BUFFERSIZE, stdin);

    while(x< BUFFERSIZE){
            sscanf(buffer, "%f ", &a[x]);
            pos = strchr(buffer, space);
            removeSubstring(start, pos);
            x++;
            }

    printf("Saved input: ");
    while(y<BUFFERSIZE && a[y] != EMPTY){
            printf("%.2f", a[y]);
            y++;
            }

    printf("\n");

    return 0;
}
</code>```

Edit: Increased both array sizes and removed feof

答: Almost certainly the problem is in the line pos = strchr(buffer, space);.  If the input does not contain a space character, then pos is set equal to NULL.  Passing a NULL to strstr() will likely result in a SEGV.

Body:
After confirming input Segmentation fault pops up and I can't see why. I was told to use fgets and sscanf in loop to read an undefined number of floats from terminal input and this is what i came up with..

Code

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

#define EMPTY 3.141592
#define BUFFERSIZE 100

void removeSubstring(char *s,const char *toremove){
  while( (s=strstr(s,toremove)) )
    memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove)));
}

int main(){

    int x=0;
    int y=0;
    float a[BUFFERSIZE] = {EMPTY};
    char buffer[BUFFERSIZE] = {EMPTY};
    char *pos;
    char *start = 0;
    int space = ' ';

    printf("Input: ");
    fgets(buffer, BUFFERSIZE, stdin);

    while(x< BUFFERSIZE){
            sscanf(buffer, "%f ", &a[x]);
            pos = strchr(buffer, space);
            removeSubstring(start, pos);
            x++;
            }

    printf("Saved input: ");
    while(y<BUFFERSIZE && a[y] != EMPTY){
            printf("%.2f", a[y]);
            y++;
            }

    printf("\n");

    return 0;
}

Edit: Increased both array sizes and removed feof


问:
django - TypeError how to get instance of a foreignkey from the user instance
I am getting the following type error and its due to this instance in view. The model as you can see below where Employee is onetoone relation to User and Company is the foreignkey to the Employee. How would I be able to solve this by getting the instance of company ? Or what is the problem.

This is the problem:

```<code>companysetting_form = CompanySettingEdit(instance = request.user.employee.company)
</code>```

Below is the typeerror

```<code>TypeError at /employee/companysettings/
__init__() got an unexpected keyword argument 'instance'

Request Method: GET
Request URL:    http://127.0.0.1:8000/employee/companysettings/
Django Version: 1.11.7
Exception Type: TypeError
Exception Value:
__init__() got an unexpected keyword argument 'instance'
Exception Location: /project/railercom/railercomapp/views.py in employee_companysettings, line 83
Python Executable:  /project/myvirtualenv/railercom/bin/python
Python Version: 3.6.3
Python Path:
['/project/railercom',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
 '/project/myvirtualenv/railercom/lib/python3.6/site-packages']
</code>```

Below are my code:

```<code>@login_required(login_url='/employee/sign-in/')
def employee_companysettings(request):

companysetting_form = CompanySettingEdit(instance = request.user.employee.company)  <---- this is the problem

if request.method == "POST":
    companysetting_form = CompanySettingEdit(request.POST, instance = request.user.employee.company)

    if companysetting_form.is_valid():
        companysetting_form.save()

return render(request, 'employee/account.html', {
    "companysetting_form":companysetting_form
    })

class CompanySettingEdit(forms.Form):
    name = forms.CharField(max_length=50, required=False)
    tel = forms.CharField(max_length=50, required=False)
    address_1 = forms.CharField(max_length=50, required=False)
    address_2 = forms.CharField(max_length=50, required=False)
    address_zip = forms.CharField(max_length=50, required=False)
    address_city = forms.CharField(max_length=50, required=False)
    address_state = forms.CharField(max_length=50, required=False)
    address_country = forms.CharField(max_length=50, required=False)

    class Meta:
        model = Company
        fields = ("name", "tel", "address_1", "address_2", "address_zip",
                  "address_city","address_state","address_country")

      <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {% bootstrap_form companysetting_form %}
        <button type="submit" class="btn btn-pink">Update</button>
      </form>

class Company(models.Model):
    name = models.CharField(max_length=50)
    tel = models.CharField(max_length=15, blank=True)
    address_1 = models.CharField(max_length=50, blank=True)
    address_2 = models.CharField(max_length=50, blank=True)
    address_zip = models.CharField(max_length=20, blank=True)
    address_city = models.CharField(max_length=20, blank=True)
    address_state = models.CharField(max_length=20, blank=True)
    address_country = models.CharField(max_length=20, blank=True)

    logo = models.ImageField(upload_to='company_logo/', blank=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
</code>```

答:
This question doesn't have anything to do with foreign keys.

Plain Form subclasses don't know anything about models, ignore the inner Meta class, don't have a save method, and don't accept an instance argument.

To enable all these things, your form needs to subclass forms.ModelForm.

As a bonus, once you've done that you can remove all the field definitions in the class itself, as they will be taken from the model definition.

ContentLicense: CC BY-SA 4.0

Body:
I am getting the following type error and its due to this instance in view. The model as you can see below where Employee is onetoone relation to User and Company is the foreignkey to the Employee. How would I be able to solve this by getting the instance of company ? Or what is the problem.

This is the problem:

companysetting_form = CompanySettingEdit(instance = request.user.employee.company)

Below is the typeerror

TypeError at /employee/companysettings/
__init__() got an unexpected keyword argument 'instance'

Request Method: GET
Request URL:    http://127.0.0.1:8000/employee/companysettings/
Django Version: 1.11.7
Exception Type: TypeError
Exception Value:
__init__() got an unexpected keyword argument 'instance'
Exception Location: /project/railercom/railercomapp/views.py in employee_companysettings, line 83
Python Executable:  /project/myvirtualenv/railercom/bin/python
Python Version: 3.6.3
Python Path:
['/project/railercom',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
 '/project/myvirtualenv/railercom/lib/python3.6/site-packages']

Below are my code:

@login_required(login_url='/employee/sign-in/')
def employee_companysettings(request):

companysetting_form = CompanySettingEdit(instance = request.user.employee.company)  <---- this is the problem

if request.method == "POST":
    companysetting_form = CompanySettingEdit(request.POST, instance = request.user.employee.company)

    if companysetting_form.is_valid():
        companysetting_form.save()

return render(request, 'employee/account.html', {
    "companysetting_form":companysetting_form
    })

class CompanySettingEdit(forms.Form):
    name = forms.CharField(max_length=50, required=False)
    tel = forms.CharField(max_length=50, required=False)
    address_1 = forms.CharField(max_length=50, required=False)
    address_2 = forms.CharField(max_length=50, required=False)
    address_zip = forms.CharField(max_length=50, required=False)
    address_city = forms.CharField(max_length=50, required=False)
    address_state = forms.CharField(max_length=50, required=False)
    address_country = forms.CharField(max_length=50, required=False)

    class Meta:
        model = Company
        fields = ("name", "tel", "address_1", "address_2", "address_zip",
                  "address_city","address_state","address_country")

      <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {% bootstrap_form companysetting_form %}
        <button type="submit" class="btn btn-pink">Update</button>
      </form>

class Company(models.Model):
    name = models.CharField(max_length=50)
    tel = models.CharField(max_length=15, blank=True)
    address_1 = models.CharField(max_length=50, blank=True)
    address_2 = models.CharField(max_length=50, blank=True)
    address_zip = models.CharField(max_length=20, blank=True)
    address_city = models.CharField(max_length=20, blank=True)
    address_state = models.CharField(max_length=20, blank=True)
    address_country = models.CharField(max_length=20, blank=True)

    logo = models.ImageField(upload_to='company_logo/', blank=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


问:
Failed opening required '/var/www/html/sel/demo/../bootstrap.php' for Nearsoft/php-selenium-client
I have PHP v 7.1.8 / PHPUnit v 6.4.4 successfully installed on my machine.
I dowloaded Nearsoft/php-selenium-client (https://github.com/Nearsoft/php-selenium-client).

After I started selenium standalone server, I tried to run demo Nearsoft Demo test phpunit Demo1.php, but it shows:
"Failed opening required '/var/www/html/sel/demo/../bootstrap.php'"

Not sure why, because it works just fine on my other machine that uses PHPUnit v 4+ amd PHP 5.6

答:
I don't think you can run those demos with PHPUnit v6.4.4, since v6.0 PHPUnit has changed its Class names. Try running it with PHPUnit v5.7.

Take a look at the Release Notes for PHPUnit v6.0.
A quick look at demo1.php at line 10 exposes the "old" naming schema for PHPUnit.


问:
why mybatis not provide pagination query?
Spring data jpa has Pagination query and there are also many need paging scenarios,why mybatis only provide selectList?How to implement pagination in mybatis ?Can anyone give me a help?

答:
To use Mybatis-PageHelper

add in pom.xml

```<code><dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>x.x.x</version>
</dependency>
</code>```

configure in mybatis-config.xml
where database supported are oracle, mysql, mariadb, sqlite, hsqldb, postgresql, db2, sqlserver, informix, h2, sqlserver2012, derby

```<code><!--
    In the configuration file,
    plugins location must meet the requirements as the following order:
    properties?, settings?,
    typeAliases?, typeHandlers?,
    objectFactory?,objectWrapperFactory?,
    plugins?,
    environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- config params as the following -->
        <property name="param1" value="value1"/>
    </plugin>
</plugins>
</code>```

example of usage:

```<code>mybatisTemplate.selectList("query", params, new RowBounds(offset, limit));
</code>```

consequence:
1) you don't have to implement pagination in your sql
2) mybatis-pagehelper will generate the required pagination sql

Hope the above helps

Body:
To use Mybatis-PageHelper

add in pom.xml

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>x.x.x</version>
</dependency>

configure in mybatis-config.xml
where database supported are oracle, mysql, mariadb, sqlite, hsqldb, postgresql, db2, sqlserver, informix, h2, sqlserver2012, derby

<!--
    In the configuration file,
    plugins location must meet the requirements as the following order:
    properties?, settings?,
    typeAliases?, typeHandlers?,
    objectFactory?,objectWrapperFactory?,
    plugins?,
    environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- config params as the following -->
        <property name="param1" value="value1"/>
    </plugin>
</plugins>

example of usage:

mybatisTemplate.selectList("query", params, new RowBounds(offset, limit));

consequence:
1) you don't have to implement pagination in your sql
2) mybatis-pagehelper will generate the required pagination sql

Hope the above helps


问:
Electron app reactivate window using Tray Icon
when we Minimize the application, how reactive the window by using Tray menu

```<code>const tray = new Tray(path.join(__dirname, '/assets/icons/commusoft-squarelogo.png'))
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Active', type:'normal',role: 'front', click:try_click() },
    { label: 'Preferences', type: 'normal',click: try_click()},
    { label: 'Reload', type: 'normal', role: 'reload'},
    { label: 'Reload new', type: 'normal', role: 'reload'},
    { label: 'Quit', type: 'normal', role: 'quit' }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
</code>```

Thanks in advance!!!

答:
now finally figure out the answer</p>

```<code>const contextMenu = Menu.buildFromTemplate([
    { label: 'Active', type:'normal',role: 'front', click:function(){
                                                            win.show()
                                                      }
    },
    { label: 'Preferences', type: 'normal',click: try_click()},
    { label: 'Reload', type: 'normal', role: 'reload'},
    { label: 'Reload new', type: 'normal', role: 'reload'},
    { label: 'Quit', type: 'normal', role: 'quit' }
  ])
</code>```

Body:
when we Minimize the application, how reactive the window by using Tray menu

const tray = new Tray(path.join(__dirname, '/assets/icons/commusoft-squarelogo.png'))
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Active', type:'normal',role: 'front', click:try_click() },
    { label: 'Preferences', type: 'normal',click: try_click()},
    { label: 'Reload', type: 'normal', role: 'reload'},
    { label: 'Reload new', type: 'normal', role: 'reload'},
    { label: 'Quit', type: 'normal', role: 'quit' }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)

Thanks in advance!!!

Body:
now finally figure out the answer

const contextMenu = Menu.buildFromTemplate([
    { label: 'Active', type:'normal',role: 'front', click:function(){
                                                            win.show()
                                                      }
    },
    { label: 'Preferences', type: 'normal',click: try_click()},
    { label: 'Reload', type: 'normal', role: 'reload'},
    { label: 'Reload new', type: 'normal', role: 'reload'},
    { label: 'Quit', type: 'normal', role: 'quit' }
  ])


问:
Reducing shuffle disk usage in Spark aggregations
I have a table in hive which is 100 GB of size. I am trying to group, count function and storing the result as hive table..my hard disk has 600 GB of space, by the time job reaches to 70% all of the disk space is being occupied.

so my job got fails...How can I minimize the shuffle data writes

```<code>hiveCtx.sql("select * from gm.final_orc")
  .repartition(300)
  .groupBy('col1, 'col2).count
  .orderBy('count desc)
  .write.saveAsTable("gm.result")
</code>```

spark_memory

答:
In cloud-based execution environments adding more disk is usually a very easy and cheap option. If your environment does not allow this and you've verified that your shuffles settings are reasonable, e.g., compression (on by default) is not changed, then there is only one solution: implement your own staged map-reduce using the fact that counts can be re-aggregated via sum.

Partition your data in any way that seems fit (by date, by directory, by number of files, etc.)

Perform the counting by col1 and col2 as separate Spark actions.

Re-group and re-aggregate.

Sort.

For simplicity, let's assume that col1 is an integer. Here is how I'd break up processing into 8 separate jobs, re-aggregating their output. If col1 is not an integer, you can hash it or you can use another column.

def splitTableName(i: Int) = s"tmp.gm.result.part-$i"

// Source data
val df = hiveCtx.sql("select col1, col2 from gm.final_orc")

// Number of splits
val splits = 8

// Materialize partial aggregations
val tables = for {
  i <- 0 until splits
  tableName = splitTableName(i)
  // If col1 % splits will create very skewed data, hash it first, e.g.,
  // hash(col1) % splits. hash() uses Murmur3.
  _ = df.filter('col1 % splits === i)
    // repartition only if you need to, e.g., massive partitions are causing OOM
    // better to increase the number of splits and/or hash to un-skew skewed data
    .groupBy('col1, 'col2).count
    .write.saveAsTable(tableName)
} yield hiveCtx.table(tableName)

// Final aggregation
tables.reduce(_ union _)
  .groupBy('col1, 'col2)
  .agg(sum('count).as("count"))
  .orderBy('count.desc)
  .write.saveAsTable("gm.result")

// Cleanup temporary tables
(0 until splits).foreach { i =>
  hiveCtx.sql(s"drop table ${splitTableName(i)}")
}
```

If col1 and col2 are so diverse and/or so large that the partial aggregation storage is causing disk space issues then you have to consider one of the following:

Smaller number of splits will generally use less disk space.

Sorting on col1 will help (because of Parquet run length encoding) but that would slow down execution.

How to create splits that are independent, e.g., find distinct values of col1, partition those into groups.

If you are extremely short on disk space you'd have to implement multi-step re-aggregation. The simplest approach is to generate the splits one at a time and keep a running aggregate. The execution would be much slower but it will use a lot less disk space.

Hope this helps!

Body:
I have a table in hive which is 100 GB of size. I am trying to group, count function and storing the result as hive table..my hard disk has 600 GB of space, by the time job reaches to 70% all of the disk space is being occupied.

so my job got fails...How can I minimize the shuffle data writes

hiveCtx.sql("select * from gm.final_orc")
  .repartition(300)
  .groupBy('col1, 'col2).count
  .orderBy('count desc)
  .write.saveAsTable("gm.result")

spark_memory

Body:
In cloud-based execution environments adding more disk is usually a very easy and cheap option. If your environment does not allow this and you've verified that your shuffles settings are reasonable, e.g., compression (on by default) is not changed, then there is only one solution: implement your own staged map-reduce using the fact that counts can be re-aggregated via sum.

Partition your data in any way that seems fit (by date, by directory, by number of files, etc.)

Perform the counting by col1 and col2 as separate Spark actions.

Re-group and re-aggregate.

Sort.

For simplicity, let's assume that col1 is an integer. Here is how I'd break up processing into 8 separate jobs, re-aggregating their output. If col1 is not an integer, you can hash it or you can use another column.

def splitTableName(i: Int) = s"tmp.gm.result.part-$i"

// Source data
val df = hiveCtx.sql("select col1, col2 from gm.final_orc")

// Number of splits
val splits = 8

// Materialize partial aggregations
val tables = for {
  i <- 0 until splits
  tableName = splitTableName(i)
  // If col1 % splits will create very skewed data, hash it first, e.g.,
  // hash(col1) % splits. hash() uses Murmur3.
  _ = df.filter('col1 % splits === i)
    // repartition only if you need to, e.g., massive partitions are causing OOM
    // better to increase the number of splits and/or hash to un-skew skewed data
    .groupBy('col1, 'col2).count
    .write.saveAsTable(tableName)
} yield hiveCtx.table(tableName)

// Final aggregation
tables.reduce(_ union _)
  .groupBy('col1, 'col2)
  .agg(sum('count).as("count"))
  .orderBy('count.desc)
  .write.saveAsTable("gm.result")

// Cleanup temporary tables
(0 until splits).foreach { i =>
  hiveCtx.sql(s"drop table ${splitTableName(i)}")
}

If col1 and col2 are so diverse and/or so large that the partial aggregation storage is causing disk space issues then you have to consider one of the following:

Smaller number of splits will generally use less disk space.

Sorting on col1 will help (because of Parquet run length encoding) but that would slow down execution.

How to create splits that are independent, e.g., find distinct values of col1, partition those into groups.

If you are extremely short on disk space you'd have to implement multi-step re-aggregation. The simplest approach is to generate the splits one at a time and keep a running aggregate. The execution would be much slower but it will use a lot less disk space.

Hope this helps!


问:
Loading a Fragment from an Activity to another Activity which is already in backstack
I have an activity(let's call it Home Activity) with bottom navigation view where I replace all of my fragments. In Home Activity I have loaded a fragment which has a search icon. That search icon redirects to an activity that is Search Activity.

When I click any of the search result I go to my Home Activity and replace the previous fragment to show my recent search result click implementation.

In this case, the complexity is - when I'm trying to replace the previous fragment - it's visible to the user. And as I have a transition animation - I can see the previous fragment is exiting and the latest fragment is entering.

This is not at all a good experience for the user. How may I improve the functionality so that previous fragment is not visible to the user?

答: Fragments are by default transparent. So you need to give background to your search result fragment. To give backgroind set background on root of your layout.</p>


问:
I want to use bool on button, if i click on button image of imageview changed and if again click on button then image reverse using Swift
my code is:
func PickUpCarCost() {

```<code>        imgCheck.image = UIImage(named: "uncheck.png")
        imgUnCheck.image = UIImage(named: "uncheck.png")
        if CarPickUpButton?.tag == 1 {
            imgCheck.image = UIImage(named: "check.png")
           self.pickupChargelabel.text=self.PickUpFare.text!
        }
        else {
            imgUnCheck.image = UIImage(named: "uncheck.png")

        }

}
</code>```

in this i wants take bool like if button selectes image view image will be check.png if unselect image view image will be uncheck.png how to code for this in swift.

答:
This code worked for me. Globally define var isclick = false

```<code> func CarDeliverCost() {
        if (!isclick){

            imgUnCheck.image = UIImage(named: "check.png")
            isclick=true

        }
        else
        {
            imgUnCheck.image = UIImage(named: "uncheck.png")
            isclick=false

        }
    }
</code>```

Body:
my code is:
func PickUpCarCost() {

        imgCheck.image = UIImage(named: "uncheck.png")
        imgUnCheck.image = UIImage(named: "uncheck.png")
        if CarPickUpButton?.tag == 1 {
            imgCheck.image = UIImage(named: "check.png")
           self.pickupChargelabel.text=self.PickUpFare.text!
        }
        else {
            imgUnCheck.image = UIImage(named: "uncheck.png")

        }

}

in this i wants take bool like if button selectes image view image will be check.png if unselect image view image will be uncheck.png how to code for this in swift.

Body:
This code worked for me. Globally define var isclick = false

 func CarDeliverCost() {
        if (!isclick){

            imgUnCheck.image = UIImage(named: "check.png")
            isclick=true

        }
        else
        {
            imgUnCheck.image = UIImage(named: "uncheck.png")
            isclick=false

        }
    }


问:
how to format time with jquery/javascript
I have a JSON feed that drupal spits out time in this format:   2010-12-16T04:41:35Z

How do I go about formating it to X minutes/hours ago?

答:
You can use regexp object in JS to build your own regular expression, separate hours-minutes-secs from the original string and then do whatever you want.

Tip: actual_date - your original string time

ContentLicense: CC BY-SA 2.5


答:
Use aggregation to have those companies only who have at least one active product</p>

```<code>SELECT
  v.*
FROM
  thevendor v
  JOIN dproducts p
    ON p.vendor_id = v.thevendor_id
WHERE p.active = '1'
GROUP BY v.thevendor_id
HAVING COUNT(p.vendor_id) > 0
</code>```

Title: In a While loop (php-mysql) can I have it display an entry once that has duplicates?

Body:
Use aggregation to have those companies only who have at least one active product

SELECT
  v.*
FROM
  thevendor v
  JOIN dproducts p
    ON p.vendor_id = v.thevendor_id
WHERE p.active = '1'
GROUP BY v.thevendor_id
HAVING COUNT(p.vendor_id) > 0


问:
Hartl's rails tutorial ch11: Why is my account_activation mailer template preview not working?
I am on ch11 of Hartl's rails tutorial, section 11.2.1 Mailer Templates, The preview for the password reset mailer works fine but the account_activation preview does not. the error actually changed even though i didn't make any changes to the code, which was confusing. However the error that I am currently receiving is

```<code>NoMethodError in Rails::Mailers#preview

Showing /home/ubuntu/workspace/sample_app/app/views/user_mailer/account_activation.html.erb where line #3 raised:

undefined method `name' for nil:NilClass

Extracted source (around line #3)

<h1>Sample App</h1>

<p>Hi <%=@user.name %>,</p>

<p>
Welcome to the Sample App! Click on the link below to activate your account:
</code>```

here is my user_mailer.rb

```<code>class UserMailer < ApplicationMailer

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end

  def account_activation
    @greeting = "Hi"

    mail to: "to@example.org"
  end

  def password_reset
    @greeting = "Hi"

    mail to: "to@example.org"
  end
end
</code>```

account_activations_controller.rb (no code has been specified so far in the tutorial)

```<code>class AccountActivationsController < ApplicationController
end
</code>```

and the source of the error account_activation.html.erb

```<code><h1>Sample App</h1>

<p>Hi <%=@user.name %>,</p>

<p>
Welcome to the Sample App! Click on the link below to activate your account:
</p>

<%= link_to "Activate", edit_account_activation_url(@user.activation_token,
                                                    email: @user.email) %>
</code>```

it seems to not be recognising the name of the user. why could this be? (Note: all code is copied from the tutorial so i am at a loss as to the reason for the error)
thanks.

EDIT:As per the comment there wer indeed 2 account_activation methods. i have deleted the second one and kept the first.  Now the error has changed to an argument error.

```<code>ArgumentError in Rails::MailersController#preview
wrong number of arguments (given 0, expected 1)

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end
</code>```

This method seems to be used in the following file without an argument.

/sample_app/test/mailers/previews/user_mailer_preview.rb

```<code>class UserMailerPreview < ActionMailer::Preview

  # Preview this email at http://localhost:3000/rails/mailers/user_mailer/account_activation
  def account_activation
    user = User.first
    user.activation_token = User.new_token
    UserMailer.account_activation(user)
    UserMailer.account_activation
  end

  # Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset
  def password_reset
    UserMailer.password_reset
  end

end
</code>```

答:
In your UserMailer you currently have 2 versions of the account_activation method - one that takes a user parameter and a second one that doesn't. In Ruby you can't have 2 methods in a class with the same name so that second method will be replacing the earlier one.

I'm not familiar with with all the contents of this tutorial, but it seems likely the method without the parameter is from earlier in the tutorial and should have been removed now.

Then you will need to check the code where you're calling UserMailer.account_activation.deliver... and update it to be passing a user.

Update

In user_mailer_preview.rb you are calling account_activation twice:

```<code>...
UserMailer.account_activation(user)
UserMailer.account_activation
...
</code>```

The call without user should be removed.

Body:
I am on ch11 of Hartl's rails tutorial, section 11.2.1 Mailer Templates, The preview for the password reset mailer works fine but the account_activation preview does not. the error actually changed even though i didn't make any changes to the code, which was confusing. However the error that I am currently receiving is

NoMethodError in Rails::Mailers#preview

Showing /home/ubuntu/workspace/sample_app/app/views/user_mailer/account_activation.html.erb where line #3 raised:

undefined method `name' for nil:NilClass

Extracted source (around line #3)

Sample App

Hi <%=@user.name %>,

Welcome to the Sample App! Click on the link below to activate your account:

here is my user_mailer.rb

class UserMailer < ApplicationMailer

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end

  def account_activation
    @greeting = "Hi"

    mail to: "to@example.org"
  end

  def password_reset
    @greeting = "Hi"

    mail to: "to@example.org"
  end
end

account_activations_controller.rb (no code has been specified so far in the tutorial)

class AccountActivationsController < ApplicationController
end

and the source of the error account_activation.html.erb

Sample App

Hi <%=@user.name %>,

Welcome to the Sample App! Click on the link below to activate your account:

<%= link_to "Activate", edit_account_activation_url(@user.activation_token,
                                                    email: @user.email) %>

it seems to not be recognising the name of the user. why could this be? (Note: all code is copied from the tutorial so i am at a loss as to the reason for the error)
thanks.

EDIT:As per the comment there wer indeed 2 account_activation methods. i have deleted the second one and kept the first.  Now the error has changed to an argument error.

ArgumentError in Rails::MailersController#preview
wrong number of arguments (given 0, expected 1)

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end

This method seems to be used in the following file without an argument.

/sample_app/test/mailers/previews/user_mailer_preview.rb

class UserMailerPreview < ActionMailer::Preview

  # Preview this email at http://localhost:3000/rails/mailers/user_mailer/account_activation
  def account_activation
    user = User.first
    user.activation_token = User.new_token
    UserMailer.account_activation(user)
    UserMailer.account_activation
  end

  # Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset
  def password_reset
    UserMailer.password_reset
  end

end

Body:
In your UserMailer you currently have 2 versions of the account_activation method - one that takes a user parameter and a second one that doesn't. In Ruby you can't have 2 methods in a class with the same name so that second method will be replacing the earlier one.

I'm not familiar with with all the contents of this tutorial, but it seems likely the method without the parameter is from earlier in the tutorial and should have been removed now.

Then you will need to check the code where you're calling UserMailer.account_activation.deliver... and update it to be passing a user.

Update

In user_mailer_preview.rb you are calling account_activation twice:

...
UserMailer.account_activation(user)
UserMailer.account_activation
...

The call without user should be removed.


问:
How to do simple google script api with php
I am trying to figure out how to call a google script via the api from php. Here is my script:

```<code>function doGet() {
  return ContentService.createTextOutput("hello world!");
}
</code>```

I can call it as a web app via it's URL but what I am trying to accomplish will require it be called via the API. Google's documentation is so confusing it's almost useless.

This seems like it would be such a simple task but I'm getting nowhere fast. Does anyone know where to find a simple step by step tutorial or can someone detail the steps required to accomplish this?

UPDATE: So, I've given up on the google API to access scripts. I can use all of the drive api calls but it seems it's not possible to call my own script via the API. Here is my ultimate goal:

A google script to zip files:

```<code>function doGet(e) {
  var fileIds = [];
// hard code a couple of file id's just for simplicity now.
  fileIds.push('0BzoYw0RgVVOvU0RqdTFrcGdSSzA');
  fileIds.push('0BzoYw0RgVVOvNEJNcWpmSkNxNTA');
  return ContentService.createTextOutput(zipping(fileIds));
}

function zipping(fileIds) {
  var zipfilename = "sample2.zip";
  var blobs = [];
  var mimeInf = [];
  var accesstoken = ScriptApp.getOAuthToken();
  fileIds.forEach(function(e) {
      try {
          var file = DriveApp.getFileById(e);
          var mime = file.getMimeType();
          var name = file.getName();
      } catch (er) {
          return er
      }
      var blob;
          blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "?alt=media", {
              method: "GET",
              headers: {"Authorization": "Bearer " + accesstoken},
              muteHttpExceptions: true
          }).getBlob().setName(name);
      blobs.push(blob);
  });
  var zip = Utilities.zip(blobs, zipfilename);
  return DriveApp.createFile(zip).getId(); // return the file id of the new zip file.
}
</code>```

Publish -> Deploy as web app...

Select "New"

Select "Me"

Select "Only Myself"

Click "Deploy" and authorize the access as requested.

Call the web app with curl from command line to test:

```<code>curl -L https://script.google.com/macros/u/0/s/### script id ###/exec
</code>```

Get html containing the error: "Sorry, unable to open the file at this time."

Change permissions so anyone can execute the app.

Same error. Even entering the url in the browser as the same user gives the same error.

At this point I think I have to admit defeat and find a solution other than Google.

------------------ UPDATE 2 --------------------

Apparently the error:

"Sorry, unable to open the file at this time. Please check the address and try again."

I think this is some oddball problem with Google. The same script works in some accounts but not others. I see from searching the web, others randomly get this error and there is no definitive solution. If anyone knows one, please let me know.

----------------- UPDATE 3 --------------------

This error is an oddball problem with Google. Apparently a new script in some accounts will get this error until the next day. I have verified this several times so if this happens to you, wait a day and try executing it again. The good thing is that after Google finally is able to "open the file" you can make any changes you want, including additional script files to that project, and it updates instantly.

However, a new project will have to wait until the next day so pre create any you think you might want and a couple extra a day ahead of time.

答:
How about this sample script? When you deploy Web Apps, please copy and paste the URL. And please use it to $url of the following script.

How to deploy Web Apps.

On the Script Editor

File

-> Manage Versions

-> Save New Version

Publish

-> Deploy as Web App

-> "Project version:" is latest one or create as New.

-> At "Execute the app as", select "your account"

-> At "Who has access to the app", select "Anyone, even anonymous"

-> Click "Deploy"

-> Copy "Current web app URL"

-> Click "OK"

Sample script :

```<code><?php
$url = 'https://script.google.com/macros/s/#####/exec';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($curl);
echo $response;
curl_close($curl);
?>
</code>```

Result :

```<code>hello world!
</code>```

References :

Web Apps

cURL Functions

If I misunderstand your question, I'm sorry.

Body:
I am trying to figure out how to call a google script via the api from php. Here is my script:

function doGet() {
  return ContentService.createTextOutput("hello world!");
}

I can call it as a web app via it's URL but what I am trying to accomplish will require it be called via the API. Google's documentation is so confusing it's almost useless.

This seems like it would be such a simple task but I'm getting nowhere fast. Does anyone know where to find a simple step by step tutorial or can someone detail the steps required to accomplish this?

UPDATE: So, I've given up on the google API to access scripts. I can use all of the drive api calls but it seems it's not possible to call my own script via the API. Here is my ultimate goal:

A google script to zip files:

function doGet(e) {
  var fileIds = [];
// hard code a couple of file id's just for simplicity now.
  fileIds.push('0BzoYw0RgVVOvU0RqdTFrcGdSSzA');
  fileIds.push('0BzoYw0RgVVOvNEJNcWpmSkNxNTA');
  return ContentService.createTextOutput(zipping(fileIds));
}

function zipping(fileIds) {
  var zipfilename = "sample2.zip";
  var blobs = [];
  var mimeInf = [];
  var accesstoken = ScriptApp.getOAuthToken();
  fileIds.forEach(function(e) {
      try {
          var file = DriveApp.getFileById(e);
          var mime = file.getMimeType();
          var name = file.getName();
      } catch (er) {
          return er
      }
      var blob;
          blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "?alt=media", {
              method: "GET",
              headers: {"Authorization": "Bearer " + accesstoken},
              muteHttpExceptions: true
          }).getBlob().setName(name);
      blobs.push(blob);
  });
  var zip = Utilities.zip(blobs, zipfilename);
  return DriveApp.createFile(zip).getId(); // return the file id of the new zip file.
}

Publish -> Deploy as web app...

Select "New"

Select "Me"

Select "Only Myself"

Click "Deploy" and authorize the access as requested.

Call the web app with curl from command line to test:

curl -L https://script.google.com/macros/u/0/s/### script id ###/exec

Get html containing the error: "Sorry, unable to open the file at this time."

Change permissions so anyone can execute the app.

Same error. Even entering the url in the browser as the same user gives the same error.

At this point I think I have to admit defeat and find a solution other than Google.

------------------ UPDATE 2 --------------------

Apparently the error:

"Sorry, unable to open the file at this time. Please check the address and try again."

I think this is some oddball problem with Google. The same script works in some accounts but not others. I see from searching the web, others randomly get this error and there is no definitive solution. If anyone knows one, please let me know.

----------------- UPDATE 3 --------------------

This error is an oddball problem with Google. Apparently a new script in some accounts will get this error until the next day. I have verified this several times so if this happens to you, wait a day and try executing it again. The good thing is that after Google finally is able to "open the file" you can make any changes you want, including additional script files to that project, and it updates instantly.

However, a new project will have to wait until the next day so pre create any you think you might want and a couple extra a day ahead of time.

Body:
How about this sample script? When you deploy Web Apps, please copy and paste the URL. And please use it to $url of the following script.

How to deploy Web Apps.

On the Script Editor

File

-> Manage Versions

-> Save New Version

Publish

-> Deploy as Web App

-> "Project version:" is latest one or create as New.

-> At "Execute the app as", select "your account"

-> At "Who has access to the app", select "Anyone, even anonymous"

-> Click "Deploy"

-> Copy "Current web app URL"

-> Click "OK"

Sample script :

<?php
$url = 'https://script.google.com/macros/s/#####/exec';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($curl);
echo $response;
curl_close($curl);
?>

Result :

hello world!

References :

Web Apps

cURL Functions

If I misunderstand your question, I'm sorry.


问:
SSLHandshakeException: No cipher suites in common - spray-can SSL configuration
I'm trying to install my SSL certificate I acquired for my domain from Comodo but am getting a

SSLHandshakeException: No cipher suites in common

I've read through the multiple questions on this topic but none of the proposed answers have helped me yet.

Comodo provided four certificates:

AddTrustExternalCARoot.crt

COMODORSAAddTrustCA.crt

COMODORSADomainValidationSecureServerCA.crt

STAR_example_com.crt

I'm setting up the server in a Dockerfile to isolate the problem from my local development environment:

```<code>from google/debian:wheezy
# Server binary and certificates are copied in before this
RUN apt-get update && apt-get install -y openjdk-7-jre
ADD UnlimitedJCEPolicyJDK7.zip /
RUN unzip UnlimitedJCEPolicyJDK7.zip && cp UnlimitedJCEPolicy/*.jar /usr/lib/jvm/java-1.7.0-openjdk-amd64/jre/lib/security/
RUN keytool -import -trustcacerts -alias root -file AddTrustExternalCARoot.crt -keystore /example.com.jks -storepass changeit -noprompt
RUN keytool -import -trustcacerts -alias int-1 -file COMODORSAAddTrustCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
RUN keytool -import -trustcacerts -alias int-2 -file COMODORSADomainValidationSecureServerCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
RUN keytool -import -trustcacerts -alias mykey -file STAR_example_com.crt -keystore /example.com.jks  -storepass changeit -noprompt
</code>```

Output from keytool commands in Docker:

```<code>Step 10 : RUN keytool -import -trustcacerts -alias root -file AddTrustExternalCARoot.crt -keystore /example.com.jks -storepass changeit -noprompt
 ---> Running in 949afa47c891
Certificate was added to keystore
 ---> 1df5ff85c32a
Removing intermediate container 949afa47c891
Step 11 : RUN keytool -import -trustcacerts -alias int-1 -file COMODORSAAddTrustCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
 ---> Running in 6cc802ee61f9
Certificate was added to keystore
 ---> f6eee577e7d5
Removing intermediate container 6cc802ee61f9
Step 12 : RUN keytool -import -trustcacerts -alias int-2 -file COMODORSADomainValidationSecureServerCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
 ---> Running in 22e6bc1e70a6
Certificate was added to keystore
 ---> d7a0472a9e1f
Removing intermediate container 22e6bc1e70a6
Step 13 : RUN keytool -import -trustcacerts -alias mykey -file STAR_example_com.crt -keystore /example.com.jks  -storepass changeit -noprompt
 ---> Running in 9a812b1182ca
Certificate was added to keystore
</code>```

Comodos instructions say that this last 'Certificate was added to keystore' message should be 'Certificate reply was installed in keystore'. What should I do differently when installing the domain certificate?

The SSL configuration in Spray looks like so:

```<code>trait SslConfiguration {
  implicit def sslContext: SSLContext = {
    val password = "changeit"
    val keyStoreResource = "/example.com.jks"

    val keyStore = KeyStore.getInstance("jks")
    keyStore.load(new FileInputStream(keyStoreResource), password.toCharArray)
    val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
    keyManagerFactory.init(keyStore, password.toCharArray)
    val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
    trustManagerFactory.init(keyStore)
    val context = SSLContext.getInstance("TLS")

    context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom)
    context
  }

  implicit def sslEngineProvider: ServerSSLEngineProvider = {
    ServerSSLEngineProvider { engine =>
      engine.setEnabledCipherSuites(Array("TLS_RSA_WITH_AES_256_CBC_SHA"))
      engine.setEnabledProtocols(Array("SSLv3", "TLSv1"))
      engine
    }
  }
}
</code>```

Server Boot:

```<code>object Server extends SimpleRoutingApp with SprayJsonSupport with SslConfiguration {
  def apply(config: Configuration, router: ActorRef)(implicit actorSystem: ActorSystem) = {
    val settings = ServerSettings(actorSystem).copy(sslEncryption = true)
    startServer("0.0.0.0", config.notifyPort, serviceActorName = "notify-server", settings = Some(settings)) {
      path("ping") {
        complete("OK")
      }
    }
  }
}
</code>```

Handshake Debug output:

curl https://localhost:9082/ping

```<code>Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLSv1.1
[Raw read]: length = 5
0000: 16 03 01 00 BF                                     .....
[Raw read]: length = 191
0000: 01 00 00 BB 03 03 55 9C   69 B9 0E 94 CA 61 A4 3C  ......U.i....a.<
0010: 95 0B A5 81 B6 BA D4 90   3D 4B 8C 4E BB 35 17 8F  ........=K.N.5..
0020: 19 9E B6 D0 2E BB 00 00   5E 00 FF C0 24 C0 23 C0  ........^...$.#.
0030: 0A C0 09 C0 07 C0 08 C0   28 C0 27 C0 14 C0 13 C0  ........(.'.....
0040: 11 C0 12 C0 26 C0 25 C0   2A C0 29 C0 05 C0 04 C0  ....&.%.*.).....
0050: 02 C0 03 C0 0F C0 0E C0   0C C0 0D 00 3D 00 3C 00  ............=.<.
0060: 2F 00 05 00 04 00 35 00   0A 00 67 00 6B 00 33 00  /.....5...g.k.3.
0070: 39 00 16 00 AF 00 AE 00   8D 00 8C 00 8A 00 8B 00  9...............
0080: B1 00 B0 00 2C 00 3B 01   00 00 34 00 00 00 0E 00  ....,.;...4.....
0090: 0C 00 00 09 6C 6F 63 61   6C 68 6F 73 74 00 0A 00  ....localhost...
00A0: 08 00 06 00 17 00 18 00   19 00 0B 00 02 01 00 00  ................
00B0: 0D 00 0C 00 0A 05 01 04   01 02 01 04 03 02 03     ...............
notify-server-akka.actor.default-dispatcher-6, READ: TLSv1 Handshake, length = 191
*** ClientHello, TLSv1.2
RandomCookie:  GMT: 1419536569 bytes = { 14, 148, 202, 97, 164, 60, 149, 11, 165, 129, 182, 186, 212, 144, 61, 75, 140, 78, 187, 53, 23, 143, 25, 158, 182, 208, 46, 187 }
Session ID:  {}
Cipher Suites: [TLS_EMPTY_RENEGOTIATION_INFO_SCSV, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_PSK_WITH_AES_256_CBC_SHA384, TLS_PSK_WITH_AES_128_CBC_SHA256, TLS_PSK_WITH_AES_256_CBC_SHA, TLS_PSK_WITH_AES_128_CBC_SHA, TLS_PSK_WITH_RC4_128_SHA, TLS_PSK_WITH_3DES_EDE_CBC_SHA, TLS_PSK_WITH_NULL_SHA384, TLS_PSK_WITH_NULL_SHA256, TLS_PSK_WITH_NULL_SHA, TLS_RSA_WITH_NULL_SHA256]
Compression Methods:  { 0 }
Extension server_name, server_name: [host_name: localhost]
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA384withRSA, SHA256withRSA, SHA1withRSA, SHA256withECDSA, SHA1withECDSA
***
[read] MD5 and SHA1 hashes:  len = 191
0000: 01 00 00 BB 03 03 55 9C   69 B9 0E 94 CA 61 A4 3C  ......U.i....a.<
0010: 95 0B A5 81 B6 BA D4 90   3D 4B 8C 4E BB 35 17 8F  ........=K.N.5..
0020: 19 9E B6 D0 2E BB 00 00   5E 00 FF C0 24 C0 23 C0  ........^...$.#.
0030: 0A C0 09 C0 07 C0 08 C0   28 C0 27 C0 14 C0 13 C0  ........(.'.....
0040: 11 C0 12 C0 26 C0 25 C0   2A C0 29 C0 05 C0 04 C0  ....&.%.*.).....
0050: 02 C0 03 C0 0F C0 0E C0   0C C0 0D 00 3D 00 3C 00  ............=.<.
0060: 2F 00 05 00 04 00 35 00   0A 00 67 00 6B 00 33 00  /.....5...g.k.3.
0070: 39 00 16 00 AF 00 AE 00   8D 00 8C 00 8A 00 8B 00  9...............
0080: B1 00 B0 00 2C 00 3B 01   00 00 34 00 00 00 0E 00  ....,.;...4.....
0090: 0C 00 00 09 6C 6F 63 61   6C 68 6F 73 74 00 0A 00  ....localhost...
00A0: 08 00 06 00 17 00 18 00   19 00 0B 00 02 01 00 00  ................
00B0: 0D 00 0C 00 0A 05 01 04   01 02 01 04 03 02 03     ...............
%% Initialized:  [Session-1, SSL_NULL_WITH_NULL_NULL]
notify-server-akka.actor.default-dispatcher-6, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-1, SSL_NULL_WITH_NULL_NULL]
notify-server-akka.actor.default-dispatcher-6, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
notify-server-akka.actor.default-dispatcher-6, WRITE: TLSv1.2 Alert, length = 2
notify-server-akka.actor.default-dispatcher-6, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
[ERROR] [07/08/2015 00:07:22.230] [notify-server-akka.actor.default-dispatcher-6] [akka://notify-server/user/IO-HTTP/listener-0/0] Aborting encrypted connection to 10.0.2.2/10.0.2.2:50790 due to [SSLHandshakeException:no cipher suites in common] -> [SSLHandshakeException:no cipher suites in common]
</code>```

I've followed Comodos instructions to a tee EXCEPT for the alias setting. I'm not 100% sure if I should be setting the domain alias to 'mykey' or something else. Could this be the problem?

Any help with this problem would be greatly appreciated!

答:
For me this was caused by wrong keystore being in use.

I had two modules in the same application, and another one initialized javax.net.ssl to its liking and the part throwing the Exception listed above got turn only after that.

And once the javax.net.ssl has initialized once, changing the key- and truststore system properties no longer affect anything.

I figured this out by putting -Djavax.net.debug=ssl to the original application server command line call, to make sure the option was set before anyone else got their turn. Then you can see on STDOUT who initializes the stores and with what.

Body:
I'm trying to install my SSL certificate I acquired for my domain from Comodo but am getting a

SSLHandshakeException: No cipher suites in common

I've read through the multiple questions on this topic but none of the proposed answers have helped me yet.

Comodo provided four certificates:

AddTrustExternalCARoot.crt

COMODORSAAddTrustCA.crt

COMODORSADomainValidationSecureServerCA.crt

STAR_example_com.crt

I'm setting up the server in a Dockerfile to isolate the problem from my local development environment:

from google/debian:wheezy
# Server binary and certificates are copied in before this
RUN apt-get update && apt-get install -y openjdk-7-jre
ADD UnlimitedJCEPolicyJDK7.zip /
RUN unzip UnlimitedJCEPolicyJDK7.zip && cp UnlimitedJCEPolicy/*.jar /usr/lib/jvm/java-1.7.0-openjdk-amd64/jre/lib/security/
RUN keytool -import -trustcacerts -alias root -file AddTrustExternalCARoot.crt -keystore /example.com.jks -storepass changeit -noprompt
RUN keytool -import -trustcacerts -alias int-1 -file COMODORSAAddTrustCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
RUN keytool -import -trustcacerts -alias int-2 -file COMODORSADomainValidationSecureServerCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
RUN keytool -import -trustcacerts -alias mykey -file STAR_example_com.crt -keystore /example.com.jks  -storepass changeit -noprompt

Output from keytool commands in Docker:

Step 10 : RUN keytool -import -trustcacerts -alias root -file AddTrustExternalCARoot.crt -keystore /example.com.jks -storepass changeit -noprompt
 ---> Running in 949afa47c891
Certificate was added to keystore
 ---> 1df5ff85c32a
Removing intermediate container 949afa47c891
Step 11 : RUN keytool -import -trustcacerts -alias int-1 -file COMODORSAAddTrustCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
 ---> Running in 6cc802ee61f9
Certificate was added to keystore
 ---> f6eee577e7d5
Removing intermediate container 6cc802ee61f9
Step 12 : RUN keytool -import -trustcacerts -alias int-2 -file COMODORSADomainValidationSecureServerCA.crt -keystore /example.com.jks  -storepass changeit -noprompt
 ---> Running in 22e6bc1e70a6
Certificate was added to keystore
 ---> d7a0472a9e1f
Removing intermediate container 22e6bc1e70a6
Step 13 : RUN keytool -import -trustcacerts -alias mykey -file STAR_example_com.crt -keystore /example.com.jks  -storepass changeit -noprompt
 ---> Running in 9a812b1182ca
Certificate was added to keystore

Comodos instructions say that this last 'Certificate was added to keystore' message should be 'Certificate reply was installed in keystore'. What should I do differently when installing the domain certificate?

The SSL configuration in Spray looks like so:

trait SslConfiguration {
  implicit def sslContext: SSLContext = {
    val password = "changeit"
    val keyStoreResource = "/example.com.jks"

    val keyStore = KeyStore.getInstance("jks")
    keyStore.load(new FileInputStream(keyStoreResource), password.toCharArray)
    val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
    keyManagerFactory.init(keyStore, password.toCharArray)
    val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
    trustManagerFactory.init(keyStore)
    val context = SSLContext.getInstance("TLS")

    context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom)
    context
  }

  implicit def sslEngineProvider: ServerSSLEngineProvider = {
    ServerSSLEngineProvider { engine =>
      engine.setEnabledCipherSuites(Array("TLS_RSA_WITH_AES_256_CBC_SHA"))
      engine.setEnabledProtocols(Array("SSLv3", "TLSv1"))
      engine
    }
  }
}

Server Boot:

object Server extends SimpleRoutingApp with SprayJsonSupport with SslConfiguration {
  def apply(config: Configuration, router: ActorRef)(implicit actorSystem: ActorSystem) = {
    val settings = ServerSettings(actorSystem).copy(sslEncryption = true)
    startServer("0.0.0.0", config.notifyPort, serviceActorName = "notify-server", settings = Some(settings)) {
      path("ping") {
        complete("OK")
      }
    }
  }
}

Handshake Debug output:

curl https://localhost:9082/ping

Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for SSLv2Hello
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLSv1.1
[Raw read]: length = 5
0000: 16 03 01 00 BF                                     .....
[Raw read]: length = 191
0000: 01 00 00 BB 03 03 55 9C   69 B9 0E 94 CA 61 A4 3C  ......U.i....a.<
0010: 95 0B A5 81 B6 BA D4 90   3D 4B 8C 4E BB 35 17 8F  ........=K.N.5..
0020: 19 9E B6 D0 2E BB 00 00   5E 00 FF C0 24 C0 23 C0  ........^...$.#.
0030: 0A C0 09 C0 07 C0 08 C0   28 C0 27 C0 14 C0 13 C0  ........(.'.....
0040: 11 C0 12 C0 26 C0 25 C0   2A C0 29 C0 05 C0 04 C0  ....&.%.*.).....
0050: 02 C0 03 C0 0F C0 0E C0   0C C0 0D 00 3D 00 3C 00  ............=.<.
0060: 2F 00 05 00 04 00 35 00   0A 00 67 00 6B 00 33 00  /.....5...g.k.3.
0070: 39 00 16 00 AF 00 AE 00   8D 00 8C 00 8A 00 8B 00  9...............
0080: B1 00 B0 00 2C 00 3B 01   00 00 34 00 00 00 0E 00  ....,.;...4.....
0090: 0C 00 00 09 6C 6F 63 61   6C 68 6F 73 74 00 0A 00  ....localhost...
00A0: 08 00 06 00 17 00 18 00   19 00 0B 00 02 01 00 00  ................
00B0: 0D 00 0C 00 0A 05 01 04   01 02 01 04 03 02 03     ...............
notify-server-akka.actor.default-dispatcher-6, READ: TLSv1 Handshake, length = 191
*** ClientHello, TLSv1.2
RandomCookie:  GMT: 1419536569 bytes = { 14, 148, 202, 97, 164, 60, 149, 11, 165, 129, 182, 186, 212, 144, 61, 75, 140, 78, 187, 53, 23, 143, 25, 158, 182, 208, 46, 187 }
Session ID:  {}
Cipher Suites: [TLS_EMPTY_RENEGOTIATION_INFO_SCSV, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_PSK_WITH_AES_256_CBC_SHA384, TLS_PSK_WITH_AES_128_CBC_SHA256, TLS_PSK_WITH_AES_256_CBC_SHA, TLS_PSK_WITH_AES_128_CBC_SHA, TLS_PSK_WITH_RC4_128_SHA, TLS_PSK_WITH_3DES_EDE_CBC_SHA, TLS_PSK_WITH_NULL_SHA384, TLS_PSK_WITH_NULL_SHA256, TLS_PSK_WITH_NULL_SHA, TLS_RSA_WITH_NULL_SHA256]
Compression Methods:  { 0 }
Extension server_name, server_name: [host_name: localhost]
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA384withRSA, SHA256withRSA, SHA1withRSA, SHA256withECDSA, SHA1withECDSA
***
[read] MD5 and SHA1 hashes:  len = 191
0000: 01 00 00 BB 03 03 55 9C   69 B9 0E 94 CA 61 A4 3C  ......U.i....a.<
0010: 95 0B A5 81 B6 BA D4 90   3D 4B 8C 4E BB 35 17 8F  ........=K.N.5..
0020: 19 9E B6 D0 2E BB 00 00   5E 00 FF C0 24 C0 23 C0  ........^...$.#.
0030: 0A C0 09 C0 07 C0 08 C0   28 C0 27 C0 14 C0 13 C0  ........(.'.....
0040: 11 C0 12 C0 26 C0 25 C0   2A C0 29 C0 05 C0 04 C0  ....&.%.*.).....
0050: 02 C0 03 C0 0F C0 0E C0   0C C0 0D 00 3D 00 3C 00  ............=.<.
0060: 2F 00 05 00 04 00 35 00   0A 00 67 00 6B 00 33 00  /.....5...g.k.3.
0070: 39 00 16 00 AF 00 AE 00   8D 00 8C 00 8A 00 8B 00  9...............
0080: B1 00 B0 00 2C 00 3B 01   00 00 34 00 00 00 0E 00  ....,.;...4.....
0090: 0C 00 00 09 6C 6F 63 61   6C 68 6F 73 74 00 0A 00  ....localhost...
00A0: 08 00 06 00 17 00 18 00   19 00 0B 00 02 01 00 00  ................
00B0: 0D 00 0C 00 0A 05 01 04   01 02 01 04 03 02 03     ...............
%% Initialized:  [Session-1, SSL_NULL_WITH_NULL_NULL]
notify-server-akka.actor.default-dispatcher-6, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-1, SSL_NULL_WITH_NULL_NULL]
notify-server-akka.actor.default-dispatcher-6, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
notify-server-akka.actor.default-dispatcher-6, WRITE: TLSv1.2 Alert, length = 2
notify-server-akka.actor.default-dispatcher-6, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
[ERROR] [07/08/2015 00:07:22.230] [notify-server-akka.actor.default-dispatcher-6] [akka://notify-server/user/IO-HTTP/listener-0/0] Aborting encrypted connection to 10.0.2.2/10.0.2.2:50790 due to [SSLHandshakeException:no cipher suites in common] -> [SSLHandshakeException:no cipher suites in common]

I've followed Comodos instructions to a tee EXCEPT for the alias setting. I'm not 100% sure if I should be setting the domain alias to 'mykey' or something else. Could this be the problem?

Any help with this problem would be greatly appreciated!


问:
LINQ to SQL: What gives pain?
I decided to use LINQ to SQL in my personal project after hearing lots of goods. Is there any thing I need to taken care before start using it (during initial design)?</p>

答:
In my opinion the biggest downside of using LINQtoSQL is that if your database schema changes you need to re-generate your classes (and lose your code) unless you use some third-party tool to synch-up your DB model with you db schema.

Have a look at this question for further details.

OwnerDisplayName: Mahesh

Title: LINQ to SQL: What gives pain?

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: JohnIdol


问:
Get style at caret position in a JTextPane
I have a basic text editor that can style documents (bold, underline, italicize, underline, align left/right/center, color, font size/family), and that all works great. The problem I'm having is that I want the style to set my buttons and boxes to the correct styling for where the caret is.

Say, for example, I have the string

the quick brown fox jumps over the lazy dog

When I click between the u and i in quick, I want my italicize button to be toggled on to indicate that the text where the caret is has the italicized styling.

I'm using a JTextPane to hold the text, and a StyledEditorKit for the styling.

Thanks.

答:
Ok, just for anyone still looking for and didnt find the answer :
for example : </p>

```<code>AttributeSet attributeSet = textPane.getCharacterAttributes();
Object bold = attributeSet == null ? null : attributeSet.getAttribute( StyleConstants.Bold );
System.out.println( "Bold : " + bold );
</code>```

Body:
Ok, just for anyone still looking for and didnt find the answer :
for example :

AttributeSet attributeSet = textPane.getCharacterAttributes();
Object bold = attributeSet == null ? null : attributeSet.getAttribute( StyleConstants.Bold );
System.out.println( "Bold : " + bold );


问:
sql time weighted average
I have a table of times and temperatures taken at those times - there is a row for every time the temperature changed. I want the weighted average of the temperature - if it was 1 degree for an hour, and 2 degrees for 9 hours, the weighted average temperature is 1.9 degrees. I know how to calculate weighted averages, and I know a little about select ... over ... order by ... group by, and I think this is how it can be done, but I just can't see how to get what I want.

Here's some data ... many thanks for any help.

```<code>create table dbo.Temps (EffectiveDateTime datetime2(7), Temp float)

insert into dbo.Temps values('2017-04-25 13:51:45.2630000', 0.19)

insert into dbo.Temps values('2017-04-25 14:13:24.1590000', 0.29)

insert into dbo.Temps values('2017-04-25 14:53:10.2590000', 0.39)

insert into dbo.Temps values('2017-04-25 13:46:27.0650000', 0.49)

insert into dbo.Temps values('2017-04-25 14:10:50.2670000', 0.59)

insert into dbo.Temps values('2017-04-25 14:48:10.7570000', 0.69)

insert into dbo.Temps values('2017-04-25 14:04:42.9650000', 0.79)

insert into dbo.Temps values('2017-04-25 14:27:59.5590000', 0.89)

insert into dbo.Temps values('2017-04-25 14:56:38.8550000', 0.99)

insert into dbo.Temps values('2017-04-25 14:08:11.8580000', 1.09)

insert into dbo.Temps values('2017-04-25 14:33:39.4540000', 1.19)
</code>```

答:
In your case, weighted average of the temperature - if it was 1 degree for an hour, and 2 degrees for 9 hours, the weighted average temperature is 1.9 degrees

This would be (1 x 1 + 2 * 9) /  (1 + 9) = 1.9

It would be better/easier if you have another table have an additional column for duration. I.e another table to do the calculation for the difference in time from the next change in temperature (duration).

Then the sql statement would be something like this.

Assuming your new table name is TempDuration with column name duration and temperature.

```<code>select sum(TempDuration.temperature * TempDuration.duration) / sum(TempDuration.duration)
from TempDuration
</code>```

Note: By not have another table need a lot more step to calculate the durations and make the sql more complex.

Title: sql time weighted average

Body:
I have a table of times and temperatures taken at those times - there is a row for every time the temperature changed. I want the weighted average of the temperature - if it was 1 degree for an hour, and 2 degrees for 9 hours, the weighted average temperature is 1.9 degrees. I know how to calculate weighted averages, and I know a little about select ... over ... order by ... group by, and I think this is how it can be done, but I just can't see how to get what I want.

Here's some data ... many thanks for any help.

create table dbo.Temps (EffectiveDateTime datetime2(7), Temp float)

insert into dbo.Temps values('2017-04-25 13:51:45.2630000', 0.19)

insert into dbo.Temps values('2017-04-25 14:13:24.1590000', 0.29)

insert into dbo.Temps values('2017-04-25 14:53:10.2590000', 0.39)

insert into dbo.Temps values('2017-04-25 13:46:27.0650000', 0.49)

insert into dbo.Temps values('2017-04-25 14:10:50.2670000', 0.59)

insert into dbo.Temps values('2017-04-25 14:48:10.7570000', 0.69)

insert into dbo.Temps values('2017-04-25 14:04:42.9650000', 0.79)

insert into dbo.Temps values('2017-04-25 14:27:59.5590000', 0.89)

insert into dbo.Temps values('2017-04-25 14:56:38.8550000', 0.99)

insert into dbo.Temps values('2017-04-25 14:08:11.8580000', 1.09)

insert into dbo.Temps values('2017-04-25 14:33:39.4540000', 1.19)

Body:
In your case, weighted average of the temperature - if it was 1 degree for an hour, and 2 degrees for 9 hours, the weighted average temperature is 1.9 degrees

This would be (1 x 1 + 2 * 9) /  (1 + 9) = 1.9

It would be better/easier if you have another table have an additional column for duration. I.e another table to do the calculation for the difference in time from the next change in temperature (duration).

Then the sql statement would be something like this.

Assuming your new table name is TempDuration with column name duration and temperature.

select sum(TempDuration.temperature * TempDuration.duration) / sum(TempDuration.duration)
from TempDuration

Note: By not have another table need a lot more step to calculate the durations and make the sql more complex.


问:
Error installing TensorFlow GPU on Ubuntu
So I've spent my day trying to install TF GPU, without luck.

I've installed CUDA Toolkit 9.0 and tried CuDNN v7.0.3 (for CUDA 8 and 9) and also the v6.0.

After trying to execute my demo program, the terminal throws this message:

```<code>Traceback (most recent call last):
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "twicetwo.py", line 5, in <module>
import tensorflow
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
from tensorflow.python import *
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 72, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace above this error message when asking for help.
</code>```

I've updated the LD_LIBRARY_PATH variable and also the PATH.

I'm using Anaconda, created a source with Python 3.6, since python --version threw this version.

Can anybody help me with this?

答:
I've managed to run it. If you are here because you are stuck like me do the following:

use CUDA 8.0 (https://developer.nvidia.com/cuda-toolkit-archive)
for me only the runfile install worked!

I have Python 3.6 installed, but when creating your environment you should use python="3.5" instead

Body:
So I've spent my day trying to install TF GPU, without luck.

I've installed CUDA Toolkit 9.0 and tried CuDNN v7.0.3 (for CUDA 8 and 9) and also the v6.0.

After trying to execute my demo program, the terminal throws this message:

Traceback (most recent call last):
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "twicetwo.py", line 5, in <module>
import tensorflow
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
from tensorflow.python import *
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 72, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "/home/gemboly/anaconda3/envs/tensorflow/lib/python3.6/imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace above this error message when asking for help.

I've updated the LD_LIBRARY_PATH variable and also the PATH.

I'm using Anaconda, created a source with Python 3.6, since python --version threw this version.

Can anybody help me with this?


问:
Android studio 3 build apk comflict with previous apk
I am using android studio 2.3 for the development, last week i am completely remove the android studio 2.3 from the system and install the latest android studio 3. The same project imported from android studio 2.3 into android studio 3. the build apk generated using android studio 3 is conflicting with the build apk generated using android studio 2.3. and the db is reset completely erase database. how to fix this issue </p>

答: Restoring the database is a solution for that. I am just copy the .db files for files beside in data/ data / your package name / database/ folder into my computer. Uninstall the old apk and install the latest when generated using android studio 3 gradle version 3, and just copy the previous database files into new one using the android studio 3 device explorer. But its not at all a reliable solution for the problem, but i am using this method for installing the latest update without losing the database </p>