问:
Angular 2 101: defining and using a variable
All I'm trying to do is get my head around Angular 2 syntax. The examples I find seem to use different methods.

Look at foo:

Is this how I set up every single variable I want to use?

I define it using : syntax, and specify its type?
Then later I refer to it with this.?

```<code>export class SwitchClientComponent implements OnInit {
    filterString: string = '';
    foo: string ='';

    ngOnInit() {

        this.foo = localStorage.getItem('bar') || '!';
    }
</code>```

.

```<code>    <span>[{{foo}}]</span>
</code>```

答:
Please refer to the Angular 2 Docs, there's a section about Template Variables

Interpolation

The way you show a variable in the template using {{}} is called interpolation.

  The title is: {{title}}

```

<p>As you see you can use interpolated variables even in attributes, even mixed to static Text</p>

<p><strong>Attribute Binding</strong></p>

<p>Some attributes can be surrounded by square brackets which tells Angular to bind the value passed to that variable. In this case you don't need to use the <code>{{}}</code> syntax.</p>

<pre class="lang-html prettyprint-override"><code><img [src]="heroImageUrl">
</code>```

Template Expressions

Also you can perform expressions and use the returning value of functions

The sum of 1 + 1 is not {{1 + 1 + getVal()}}

```

<p>Of course <code>getVal()</code> will be a function that needs to be defined as public in the component.</p>

<p><strong>Local Template Variables</strong></p>

<p>Also keep in mind you can define template variables on the fly, for example using an <code>ngFor</code> directive</p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let hero of heroes">{{hero.name}}</div>
</code>```

In this example hero is not defined in the Component (and will NOT be visible inside the component class by calling this.hero) but it will be local to the context of the ngFor block. Meaning: all the children elements of the div containing ngFor.

The array heores instead need to exist and be public in the Component. As you can see in this case you don't need to use the {{}} syntax. This is because Angular is already expecting a variable there and automatically interpolates anything you will put in there.

<input #heroInput> {{heroInput.value}}
```

<p>This syntax instead provides a reference to the <code>input</code> DOM element.
<code>heroInput</code> will then be visible inside the template but cannot be accessed directly from inside the component (there is a way to use it from the component though).</p>

<p>There are some more rules around but reading that article should give you all the info you need.</p>

<p><strong>Define Component public variables</strong></p>

<p>The component to use all the examples above would look like this:</p>

<pre class="lang-js prettyprint-override"><code>export class MyComponent {
    title: string = 'My title';
    heroImageUrl: string ='http://www.myurl.com/img.jpg';
    heroes: any[] = [{name: 'a'}, {name: 'b'}];

    getVal() {
        return 3;
    }
}
</code>```

Body:
All I'm trying to do is get my head around Angular 2 syntax. The examples I find seem to use different methods.

Look at foo:

Is this how I set up every single variable I want to use?

I define it using : syntax, and specify its type?
Then later I refer to it with this.?

export class SwitchClientComponent implements OnInit {
    filterString: string = '';
    foo: string ='';

    ngOnInit() {

        this.foo = localStorage.getItem('bar') || '!';
    }

.

    [{{foo}}]

Body:
Please refer to the Angular 2 Docs, there's a section about Template Variables

Interpolation

The way you show a variable in the template using {{}} is called interpolation.

<h3>
  The title is: {{title}}
  <img src="{{heroImageUrl}}" style="height:30px">
</h3>

As you see you can use interpolated variables even in attributes, even mixed to static Text

Attribute Binding

Some attributes can be surrounded by square brackets which tells Angular to bind the value passed to that variable. In this case you don't need to use the {{}} syntax.

<img [src]="heroImageUrl">

Template Expressions

Also you can perform expressions and use the returning value of functions

<p>The sum of 1 + 1 is not {{1 + 1 + getVal()}}</p>

Of course getVal() will be a function that needs to be defined as public in the component.

Local Template Variables

Also keep in mind you can define template variables on the fly, for example using an ngFor directive

<div *ngFor="let hero of heroes">{{hero.name}}</div>

In this example hero is not defined in the Component (and will NOT be visible inside the component class by calling this.hero) but it will be local to the context of the ngFor block. Meaning: all the children elements of the div containing ngFor.

The array heores instead need to exist and be public in the Component. As you can see in this case you don't need to use the {{}} syntax. This is because Angular is already expecting a variable there and automatically interpolates anything you will put in there.

<input #heroInput> {{heroInput.value}}

This syntax instead provides a reference to the input DOM element.
heroInput will then be visible inside the template but cannot be accessed directly from inside the component (there is a way to use it from the component though).

There are some more rules around but reading that article should give you all the info you need.

Define Component public variables

The component to use all the examples above would look like this:

export class MyComponent {
    title: string = 'My title';
    heroImageUrl: string ='http://www.myurl.com/img.jpg';
    heroes: any[] = [{name: 'a'}, {name: 'b'}];

    getVal() {
        return 3;
    }
}


来源: stackexchange

问:
Is it considered accepted using var's as "shortcuts" in c#?
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

```<code>using MyApp.Properties;
</code>```

-- or --

```<code>using appsettings = MyAppp.Properties.Settings;
</code>```

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

```<code>var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;
</code>```

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)

答: It's acceptable code in that the compiler will take it and know what to do with it. It's acceptable code logically in that it shortens code later. It's really not any different than actually defining the variable type (int/bool/whatever) rather than saying var. When you're in the studio, putting your mouse of the variable gives you its compiled type, so there shouldn't be any real issue with it. Some might call it lazy, but laziness is the mother of invention. As long as your code doesn't become unreadable, I can't see how it would be much of a problem.</p>

ContentLicense: CC BY-SA 2.5

Body:
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

using MyApp.Properties;

-- or --

using appsettings = MyAppp.Properties.Settings;

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)


问:
Image Quality Issues with App Engine Image Processing (JAVA)
I'm trying to process and save a series of images to Google Cloud Storage and am running into serious image quality issues when resizing images with App Engine.

The original image always saves without any quality issues, but when resizing using ImageServiceFactory the image saves out extremely pixelated. I realize I should be buffering the input stream, but can't imagine that's effecting the image quality.

Is the ImageServiceFactory just garbage?

Thanks for the help!

Here's the code:

```<code>  public static void process(String path) {

    Cover cover = null;
    URL url = UrlBuilder.coverUrl(path);

    try {

      HttpURLConnection connection = (HttpURLConnection)
      url.openConnection();
      connection.setRequestMethod("HEAD");
      connection.connect();
      String contentType = connection.getContentType();
      FileOutput output = new FileOutput(contentType);
      OutputEncoding encoding = output.encoding;

      // create Image object from InputStream.
      InputStream imgStream = url.openStream();
      byte[] imageBytes = ByteStreams.toByteArray(imgStream);
      Image image = ImagesServiceFactory.makeImage(imageBytes);

      // generated details for image path and file name.
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String dir = sdf.format(book.getRelease());
      String ext = output.extension;

      // save original image
      Image ogImage = resizeImage(image, encoding, image.getHeight(), 100);
      String ogPath = dir + "/" + book.getItemCode() + "." + ext;
      String ogLocation = saveImage(ogPath, ogImage);

      // save md image
      Image mdImage = resizeImage(image, encoding, MD_HEIGHT, 100);
      String mdPath = dir + "/" + book.getItemCode() + "_MD." + ext;
      String mdLocation = saveImage(mdPath, mdImage);

    } catch(IOException e) {
      e.printStackTrace();
    }

  }

  private static Image resizeImage(Image image, OutputEncoding encoding, int height, int quality) {

    // create output settings and set image quality.
    OutputSettings settings = new OutputSettings(encoding);
    settings.setQuality(quality);

    // Get an instance of the imagesService to transform images.
    ImagesService imagesService = ImagesServiceFactory.getImagesService();

    int width = (int) Math.floor(height * image.getWidth() / image.getHeight());

    Transform transform = ImagesServiceFactory.makeResize(width, height, false);
    Image resizedImage = imagesService.applyTransform(transform, image, settings);

    return resizedImage;

  }

  private static String saveImage(String fileName, Image image) {

    byte[] content = image.getImageData();
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Modify access list to allow all users with link to read file
    List<Acl> acls = new ArrayList<>();
    acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));

    BlobInfo info = BlobInfo.newBuilder(bucket, fileName).setAcl(acls).build();

    // the inputstream is closed by default, so we don't need to close it here
    Blob blob = storage.create(info, content);

    // return the public download link
    return blob.getMediaLink();

  }

  private static class FileOutput {

    public String extension;
    public OutputEncoding encoding;

    public FileOutput(String mimeType) {

      switch(mimeType) {
        case "image/png":
          extension = "png";
          encoding = ImagesService.OutputEncoding.PNG;
          break;
        case "image/jpeg":
        default:
          extension = "jpg";
          encoding = ImagesService.OutputEncoding.JPEG;
          break;
      }

    }

  }
</code>```

答: This was an order of operations issue. Absent from the code, I was saving out multiple sizes of the image (sm, md, lg, etc). I was processing and saving the images from smallest to largest. Reversing the order has fixed the issue.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to process and save a series of images to Google Cloud Storage and am running into serious image quality issues when resizing images with App Engine.

The original image always saves without any quality issues, but when resizing using ImageServiceFactory the image saves out extremely pixelated. I realize I should be buffering the input stream, but can't imagine that's effecting the image quality.

Is the ImageServiceFactory just garbage?

Thanks for the help!

Here's the code:

  public static void process(String path) {

    Cover cover = null;
    URL url = UrlBuilder.coverUrl(path);

    try {

      HttpURLConnection connection = (HttpURLConnection)
      url.openConnection();
      connection.setRequestMethod("HEAD");
      connection.connect();
      String contentType = connection.getContentType();
      FileOutput output = new FileOutput(contentType);
      OutputEncoding encoding = output.encoding;

      // create Image object from InputStream.
      InputStream imgStream = url.openStream();
      byte[] imageBytes = ByteStreams.toByteArray(imgStream);
      Image image = ImagesServiceFactory.makeImage(imageBytes);

      // generated details for image path and file name.
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String dir = sdf.format(book.getRelease());
      String ext = output.extension;

      // save original image
      Image ogImage = resizeImage(image, encoding, image.getHeight(), 100);
      String ogPath = dir + "/" + book.getItemCode() + "." + ext;
      String ogLocation = saveImage(ogPath, ogImage);

      // save md image
      Image mdImage = resizeImage(image, encoding, MD_HEIGHT, 100);
      String mdPath = dir + "/" + book.getItemCode() + "_MD." + ext;
      String mdLocation = saveImage(mdPath, mdImage);

    } catch(IOException e) {
      e.printStackTrace();
    }

  }

  private static Image resizeImage(Image image, OutputEncoding encoding, int height, int quality) {

    // create output settings and set image quality.
    OutputSettings settings = new OutputSettings(encoding);
    settings.setQuality(quality);

    // Get an instance of the imagesService to transform images.
    ImagesService imagesService = ImagesServiceFactory.getImagesService();

    int width = (int) Math.floor(height * image.getWidth() / image.getHeight());

    Transform transform = ImagesServiceFactory.makeResize(width, height, false);
    Image resizedImage = imagesService.applyTransform(transform, image, settings);

    return resizedImage;

  }

  private static String saveImage(String fileName, Image image) {

    byte[] content = image.getImageData();
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Modify access list to allow all users with link to read file
    List<Acl> acls = new ArrayList<>();
    acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));

    BlobInfo info = BlobInfo.newBuilder(bucket, fileName).setAcl(acls).build();

    // the inputstream is closed by default, so we don't need to close it here
    Blob blob = storage.create(info, content);

    // return the public download link
    return blob.getMediaLink();

  }

  private static class FileOutput {

    public String extension;
    public OutputEncoding encoding;

    public FileOutput(String mimeType) {

      switch(mimeType) {
        case "image/png":
          extension = "png";
          encoding = ImagesService.OutputEncoding.PNG;
          break;
        case "image/jpeg":
        default:
          extension = "jpg";
          encoding = ImagesService.OutputEncoding.JPEG;
          break;
      }

    }

  }


问:
Why destructors does not accept parameters in C++?
Recently, I came across an example that my destructor needs to take a parameter.

I am working on a C package that manages memory internally and keeps track of allocating and freeing with parameters of its own. I do not want to break that.

I wrote a C code, that initializes my own data structures and frees them at the end. When I decided to migrate to C++ I realized that allocating data structures and freeing them should be placed in constructor and destructors. So I changed those functions to constructor and destructor.
My problem now is that I need to use a parameter to pass to destructor to free allocated data; that parameter is not in my own code and is C and I do not want to mess with that.

My question is twofold:

Why C++ decided not to accept parameters in destructors in the first place?
and
What are my options?
(I can save a pointer to that parameter or somehow call that function in my destructor, but it seems not a good practice of C++ programming)

Update: adding some code
Here is my imaginary class:

```<code>class paru_symbolic/* paru_symbolic*/
{
    public:
        paru_symbolic ( cholmod_sparse *A, cholmod_common *cc ); // constructor
        ~paru_symbolic (cholmod_common *cc ); // destructor

        // -------------------------------------------------------------------------
        // row-form of the input matrix and its permutations
        // -----------------------------------------------------------------------
              //--- other stuff
                     ...
};
</code>```

Here is my current C constructor:

```<code>#include "Parallel_LU.hpp"
paru_symbolic *paru_sym_analyse
(
 // inputs, not modified
   cholmod_sparse *A,
 // workspace and parameters
   cholmod_common *cc ){

    DEBUGLEVEL(0);
...
   aParent = (Int*) paru_alloc (m+nf, sizeof(Int),cc);

...
}
</code>```

and destructor:

```<code>void paru_freesym (paru_symbolic **LUsym_handle,
            // workspace and parameters
    cholmod_common *cc
){
    DEBUGLEVEL (0);
    if (LUsym_handle == NULL || *LUsym_handle == NULL){
        // nothing to do; caller probably ran out of memory
        return;
    }

    paru_symbolic *LUsym;
    LUsym = *LUsym_handle;

    Int m, n, anz, nf, rjsize;
...
    cholmod_l_free (m+nf, sizeof (Int), LUsym->aParent, cc);

...
    cholmod_l_free (1, sizeof (paru_symbolic), LUsym, cc);

   *LUsym_handle = NULL;
}
</code>```

The parameter cc is used inside the SuiteSparse package for tracking allocations and freeing data. It has been used all over in SuiteSparse package and is a useful tool for tracking memory.
Some people mentioned that who wants to pass a parameter to the destructor.That is a fair point, but we could have the same parameters that we have in the constructor as a default.

答:
@Vittorio's answer has the general approach. I'll just tailor it to your added sample code.

The way you presented the issue is as follows:

You use a utility type cholmod_common to do some useful work for your type.

The instance of that type can be passed to several paru_symbolic objects you create.

No single instance of paru_symbolic owns it uniquely, but they all depend on it at the start and end of their lifetime. It must exist for the same duration as all of those objects.

That screams std::shared_ptr to me.

```<code>class paru_symbolic
{
    std::shared_ptr<cholmod_common> _cc;
    public:
        paru_symbolic ( cholmod_sparse *A, std::shared_ptr<cholmod_common> cc)
         : _cc(cc) {
           // constructor
         }
        ~paru_symbolic () {
          // use _cc , it's guaranteed to live until the closing brace at the least.
        }
};
</code>```

That's it. The ownership is now shared. The last object that depends on the instance of cholmod_common will be the one to clean it up with no extra work from you.

Body:
Recently, I came across an example that my destructor needs to take a parameter.

I am working on a C package that manages memory internally and keeps track of allocating and freeing with parameters of its own. I do not want to break that.

I wrote a C code, that initializes my own data structures and frees them at the end. When I decided to migrate to C++ I realized that allocating data structures and freeing them should be placed in constructor and destructors. So I changed those functions to constructor and destructor.
My problem now is that I need to use a parameter to pass to destructor to free allocated data; that parameter is not in my own code and is C and I do not want to mess with that.

My question is twofold:

Why C++ decided not to accept parameters in destructors in the first place?
and
What are my options?
(I can save a pointer to that parameter or somehow call that function in my destructor, but it seems not a good practice of C++ programming)

Update: adding some code
Here is my imaginary class:

class paru_symbolic/* paru_symbolic*/
{
    public:
        paru_symbolic ( cholmod_sparse *A, cholmod_common *cc ); // constructor
        ~paru_symbolic (cholmod_common *cc ); // destructor

        // -------------------------------------------------------------------------
        // row-form of the input matrix and its permutations
        // -----------------------------------------------------------------------
              //--- other stuff
                     ...
};

Here is my current C constructor:

#include "Parallel_LU.hpp"
paru_symbolic *paru_sym_analyse
(
 // inputs, not modified
   cholmod_sparse *A,
 // workspace and parameters
   cholmod_common *cc ){

    DEBUGLEVEL(0);
...
   aParent = (Int*) paru_alloc (m+nf, sizeof(Int),cc);

...
}

and destructor:

void paru_freesym (paru_symbolic **LUsym_handle,
            // workspace and parameters
    cholmod_common *cc
){
    DEBUGLEVEL (0);
    if (LUsym_handle == NULL || *LUsym_handle == NULL){
        // nothing to do; caller probably ran out of memory
        return;
    }

    paru_symbolic *LUsym;
    LUsym = *LUsym_handle;

    Int m, n, anz, nf, rjsize;
...
    cholmod_l_free (m+nf, sizeof (Int), LUsym->aParent, cc);

...
    cholmod_l_free (1, sizeof (paru_symbolic), LUsym, cc);

   *LUsym_handle = NULL;
}

The parameter cc is used inside the SuiteSparse package for tracking allocations and freeing data. It has been used all over in SuiteSparse package and is a useful tool for tracking memory.
Some people mentioned that who wants to pass a parameter to the destructor.That is a fair point, but we could have the same parameters that we have in the constructor as a default.

Body:
@Vittorio's answer has the general approach. I'll just tailor it to your added sample code.

The way you presented the issue is as follows:

You use a utility type cholmod_common to do some useful work for your type.

The instance of that type can be passed to several paru_symbolic objects you create.

No single instance of paru_symbolic owns it uniquely, but they all depend on it at the start and end of their lifetime. It must exist for the same duration as all of those objects.

That screams std::shared_ptr to me.

class paru_symbolic
{
    std::shared_ptr<cholmod_common> _cc;
    public:
        paru_symbolic ( cholmod_sparse *A, std::shared_ptr<cholmod_common> cc)
         : _cc(cc) {
           // constructor
         }
        ~paru_symbolic () {
          // use _cc , it's guaranteed to live until the closing brace at the least.
        }
};

That's it. The ownership is now shared. The last object that depends on the instance of cholmod_common will be the one to clean it up with no extra work from you.


问:
Align elements vertically inside a div
I'm trying to align elements vertically inside a div, but I'm stuck with circles.
The red div is 100% width, with my code, but the vertical line does not show, and the circles (that are divs or spans with background images) are not in the middle.

My code:

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="welcomeArea">
<div class="welcomeAreaContent">
       <div class="welcomeName">
         TEXT TEXT
         <span class ="circle twittericon"></span>
       </div>
        <div class="verticalLine">
</div>
     </div>
  </div></code>```

The result looks like the following which is not good at all:

答:
There are several ways to do so

Use margin-top to the current div

Use padding-top to the parent div

Use position:relative; top:__px; to the current div

Refer https://www.w3schools.com/css/css_align.asp

Hope it helps

Title: Align elements vertically inside a div

Body:
I'm trying to align elements vertically inside a div, but I'm stuck with circles.
The red div is 100% width, with my code, but the vertical line does not show, and the circles (that are divs or spans with background images) are not in the middle.

My code:

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}

         TEXT TEXT

The result looks like the following which is not good at all:


问:
Apache + SpringBoot + SSL
I'm trying to configure my spring boot app on apache2 with a SSL certificate but i cannot understand if all the steps i'm doing are correct, before putting it in production. I need to use https and redirect all calls from 80 to 443

So, my jar application is deployed on port 8080, so I have first edited my /etc/apache2/sites_available/000-default.conf in this way

```<code><VirtualHost *:80>
       ServerName www.example.com

        ServerAdmin webmaster@localhost

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        ProxyPreserveHost On
        ProxyPass / http://localhost:8080/

</VirtualHost>
</code>```

And this was working great when i needed just plain http

Now i have a CA-certificate, i put the crt and the key in /etc/apache2/ssl/certs/ and /etc/apache2/ssl/private/ and edited the

```<code>default-ssl.conf
</code>```

in this way

```<code><IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerAdmin webmaster@localhost

                DocumentRoot /var/www/html

                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined

                SSLEngine on
                SSLCertificateFile      /etc/ssl/certs/xxxxxxxxxxxx.crt
                SSLCertificateKeyFile /etc/ssl/private/yyyyyyyyyyy.key
                SSLCertificateChainFile /etc/apache2/ssl/certs/sf_bundle-g2-g1.crt

     <FilesMatch "\.(cgi|shtml|phtml|php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /usr/lib/cgi-bin>
                                SSLOptions +StdEnvVars
                </Directory>
    </VirtualHost>
</IfModule>
</code>```

In this way, i should have enabled SSL on Apache, right?
Now i need to understand how to redirect all call from 80 to 443, and if the workflow i followed is correct

答:
Sorry if I'm missing the point but I'm not sure how exactly your question relates to Spring Boot.

Apache is "just" an HTTP server. Spring applications run in an application server like Tomcat or Wildfly or as a standalone JAR with an embedded Tomcat.

I guess you want to use the Apache as a proxy in front of the Spring application, but as far as I can see, its configuration in terms of SSL is not connected to Spring then.

One possible answer to your question would then be to do it like this (as described here: http to https apache redirection):

```<code>NameVirtualHost *:80
<VirtualHost *:80>
  ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
  ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
</VirtualHost>
</code>```

Title: Apache + SpringBoot + SSL

Body:
I'm trying to configure my spring boot app on apache2 with a SSL certificate but i cannot understand if all the steps i'm doing are correct, before putting it in production. I need to use https and redirect all calls from 80 to 443

So, my jar application is deployed on port 8080, so I have first edited my /etc/apache2/sites_available/000-default.conf in this way

<VirtualHost *:80>
       ServerName www.example.com

        ServerAdmin webmaster@localhost

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        ProxyPreserveHost On
        ProxyPass / http://localhost:8080/

</VirtualHost>

And this was working great when i needed just plain http

Now i have a CA-certificate, i put the crt and the key in /etc/apache2/ssl/certs/ and /etc/apache2/ssl/private/ and edited the

default-ssl.conf

in this way

<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerAdmin webmaster@localhost

                DocumentRoot /var/www/html

                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined

                SSLEngine on
                SSLCertificateFile      /etc/ssl/certs/xxxxxxxxxxxx.crt
                SSLCertificateKeyFile /etc/ssl/private/yyyyyyyyyyy.key
                SSLCertificateChainFile /etc/apache2/ssl/certs/sf_bundle-g2-g1.crt

     <FilesMatch "\.(cgi|shtml|phtml|php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /usr/lib/cgi-bin>
                                SSLOptions +StdEnvVars
                </Directory>
    </VirtualHost>
</IfModule>

In this way, i should have enabled SSL on Apache, right?
Now i need to understand how to redirect all call from 80 to 443, and if the workflow i followed is correct

Body:
Sorry if I'm missing the point but I'm not sure how exactly your question relates to Spring Boot.

Apache is "just" an HTTP server. Spring applications run in an application server like Tomcat or Wildfly or as a standalone JAR with an embedded Tomcat.

I guess you want to use the Apache as a proxy in front of the Spring application, but as far as I can see, its configuration in terms of SSL is not connected to Spring then.

One possible answer to your question would then be to do it like this (as described here: http to https apache redirection):

NameVirtualHost *:80
<VirtualHost *:80>
  ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
  ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
</VirtualHost>


问:
Tensorflow One Hot Encoder?
Does tensorflow have something similar to scikit learn's one hot encoder for processing categorical data?  Would using a placeholder of tf.string behave as categorical data?

I realize I can manually pre-process the data before sending it to tensorflow, but having it built in is very convenient.

答:
As mentioned above by @dga, Tensorflow has tf.one_hot now:

```<code>labels = tf.constant([5,3,2,4,1])
highest_label = tf.reduce_max(labels)
labels_one_hot = tf.one_hot(labels, highest_label + 1)

array([[ 0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.]], dtype=float32)
</code>```

You need to specify depth, otherwise you'll get a pruned one-hot tensor.

If you like to do it manually:

```<code>labels = tf.constant([5,3,2,4,1])
size = tf.shape(labels)[0]
highest_label = tf.reduce_max(labels)
labels_t = tf.reshape(labels, [-1, 1])
indices = tf.reshape(tf.range(size), [-1, 1])
idx_with_labels = tf.concat([indices, labels_t], 1)
labels_one_hot = tf.sparse_to_dense(idx_with_labels, [size, highest_label + 1], 1.0)

array([[ 0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.]], dtype=float32)
</code>```

Note arguments order in tf.concat()

Title: Tensorflow One Hot Encoder?

Body:
As mentioned above by @dga, Tensorflow has tf.one_hot now:

labels = tf.constant([5,3,2,4,1])
highest_label = tf.reduce_max(labels)
labels_one_hot = tf.one_hot(labels, highest_label + 1)

array([[ 0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.]], dtype=float32)

You need to specify depth, otherwise you'll get a pruned one-hot tensor.

If you like to do it manually:

labels = tf.constant([5,3,2,4,1])
size = tf.shape(labels)[0]
highest_label = tf.reduce_max(labels)
labels_t = tf.reshape(labels, [-1, 1])
indices = tf.reshape(tf.range(size), [-1, 1])
idx_with_labels = tf.concat([indices, labels_t], 1)
labels_one_hot = tf.sparse_to_dense(idx_with_labels, [size, highest_label + 1], 1.0)

array([[ 0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.]], dtype=float32)

Note arguments order in tf.concat()


问:
adding a row for missing data
Between a date range 2017-02-01 - 2017-02-10, i'm calculating a running balance.
I have days where we have missing data, how would I include these missing dates with the previous days balance ?

Example data:

we are missing data for 2017-02-04,2017-02-05 and 2017-02-06, how would i add a row in the query with the previous balance?
The date range is a parameter, so could change....

Can i use something like the lag function?

答:
Adding to the date range & CTE solutions, I have created Date Dimension tables in numerous databases where I just left join to them.

There are free scripts online to create date dimension tables for SQL Server. I highly recommend them. Plus, it makes aggregation by other time periods much more efficient (e.g. Quarter, Months, Year, etc....)

Title: adding a row for missing data


答:
Update below css part use flex to get inline and vertically center

```<code>.welcomeAreaContent .welcomeName {
  font-weight: bold;
  font-size: 1.7em;
  display: flex; /*Add this*/
  align-items: center; /*Add this*/
}
</code>```

.welcomeArea {
  margin-top: 70px;
  max-height: 98px;
  height: 98px;
  background-color: #293847;
}

.welcomeAreaContent {
  line-height: 98px;
  color: white;
  margin-left: 5%;
  margin-right: 5%;
}

.welcomeAreaContent>span {
  display: inline-block;
}

.welcomeAreaContent .welcomeName {
  font-weight: bold;
  font-size: 1.7em;
  display: flex;
  align-items: center;
}

.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  behavior: url(PIE.htc);
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  border-radius: 50px;
  margin-left: 32px;
  display: inline-block;
}

.twittericon {
  background: url('data:image/png;base64,...') no-repeat center;
  background-color: white;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="welcomeArea">
  <div class="welcomeAreaContent">
    <div class="welcomeName">
      TEXT TEXT
      <span class="circle twittericon"></span>
    </div>
    <div class="verticalLine">
    </div>
  </div>
</div></code>```

Title: Align elements vertically inside a div

Body:
Update below css part use flex to get inline and vertically center

.welcomeAreaContent .welcomeName {
  font-weight: bold;
  font-size: 1.7em;
  display: flex; /*Add this*/
  align-items: center; /*Add this*/
}

.welcomeArea {
  margin-top: 70px;
  max-height: 98px;
  height: 98px;
  background-color: #293847;
}

.welcomeAreaContent {
  line-height: 98px;
  color: white;
  margin-left: 5%;
  margin-right: 5%;
}

.welcomeAreaContent>span {
  display: inline-block;
}

.welcomeAreaContent .welcomeName {
  font-weight: bold;
  font-size: 1.7em;
  display: flex;
  align-items: center;
}

.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  behavior: url(PIE.htc);
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  border-radius: 50px;
  margin-left: 32px;
  display: inline-block;
}

.twittericon {
  background: url('data:image/png;base64,...') no-repeat center;
  background-color: white;
  background-size: cover;
}

<div class="welcomeArea">
  <div class="welcomeAreaContent">
    <div class="welcomeName">
      TEXT TEXT
      <span class="circle twittericon"></span>
    </div>
    <div class="verticalLine">
    </div>
  </div>
</div>


问:
How to prevent escaping of an ENV variable passed into ruby application in docker container
keys.env contains private key:

```<code>KEY="-----BEGIN PRIVATE KEY-----\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\n4FaPDsZ2icg0N5i2y/2Sa0w=\n-----END PRIVATE KEY-----\n"
</code>```

(The value of KEY should be enclosed in quotes because it contains \n)

docker-compose.yml contains env_file parameter:

```<code>version: '2'

services:
  testenv:
    image: ruby:2.4-slim
    env_file:
      - ./keys.env
</code>```

I run the container with ruby app:

```<code>docker-compose run testenv
</code>```

and try to use ENV['KEY'] variable:

```<code>irb(main):001:0> ENV['KEY']
=> "\"-----BEGIN PRIVATE KEY-----\\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\\n4FaPDsZ2icg0N5i2y/2Sa0w=\\n-----END PRIVATE KEY-----\\n\""
</code>```

The variable is escaped, but I need clean private_key.

I have not found the answer in the Docker documentations.

I see two working solutions, but none seems to me right.

Store private_key in the .env file encoded and without quotes. A
module in the app will decode this value.

Unescape value in the app (like this
Best way to escape and unescape strings in Ruby?)

Is there a way to solve this problem with built-in capabilities of Docker?

答:
You've hit a known issue of docker:

https://github.com/moby/moby/issues/11443

Sorry for the inconvenience but I would rather go the conservative route on this one :(
  The problem can be solved with echo -e like you mentioned and I think the benefit of keeping env-file simple is higher.
  I'm going to close this issue, but feel free to continue the discussion and speak up if you disagree.

The equivalent in ruby of that echo -e is replacing literal '\n' with a real newline:

```<code>ENV['KEY'].gsub('\n', "\n")
</code>```

And remove the double quotes, leave it as this:

```<code>KEY=-----BEGIN PRIVATE KEY-----\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\n4FaPDsZ2icg0N5i2y/2Sa0w=\n-----END PRIVATE KEY-----\n
</code>```

But I recommend to just mount a file:

```<code>version: '2'

services:
  testenv:
    image: ruby:2.4-slim
    volumes:
      - ./keys.pem:/root/keys.pem
</code>```

Then do a simple file read from ruby.

Body:
keys.env contains private key:

KEY="-----BEGIN PRIVATE KEY-----\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\n4FaPDsZ2icg0N5i2y/2Sa0w=\n-----END PRIVATE KEY-----\n"

(The value of KEY should be enclosed in quotes because it contains \n)

docker-compose.yml contains env_file parameter:

version: '2'

services:
  testenv:
    image: ruby:2.4-slim
    env_file:
      - ./keys.env

I run the container with ruby app:

docker-compose run testenv

and try to use ENV['KEY'] variable:

irb(main):001:0> ENV['KEY']
=> "\"-----BEGIN PRIVATE KEY-----\\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\\n4FaPDsZ2icg0N5i2y/2Sa0w=\\n-----END PRIVATE KEY-----\\n\""

The variable is escaped, but I need clean private_key.

I have not found the answer in the Docker documentations.

I see two working solutions, but none seems to me right.

Store private_key in the .env file encoded and without quotes. A
module in the app will decode this value.

Unescape value in the app (like this
Best way to escape and unescape strings in Ruby?)

Is there a way to solve this problem with built-in capabilities of Docker?

Body:
You've hit a known issue of docker:

https://github.com/moby/moby/issues/11443

Sorry for the inconvenience but I would rather go the conservative route on this one :(
  The problem can be solved with echo -e like you mentioned and I think the benefit of keeping env-file simple is higher.
  I'm going to close this issue, but feel free to continue the discussion and speak up if you disagree.

The equivalent in ruby of that echo -e is replacing literal '\n' with a real newline:

ENV['KEY'].gsub('\n', "\n")

And remove the double quotes, leave it as this:

KEY=-----BEGIN PRIVATE KEY-----\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\n4FaPDsZ2icg0N5i2y/2Sa0w=\n-----END PRIVATE KEY-----\n

But I recommend to just mount a file:

version: '2'

services:
  testenv:
    image: ruby:2.4-slim
    volumes:
      - ./keys.pem:/root/keys.pem

Then do a simple file read from ruby.


问:
Can I run E2E test with Nightwatch.js on CircleCI?
I'm developing web sites and want to run test automatically on CircleCI.

I wrote config files and a js file for test, and run E2E test on my machine local. It works.

And then, I wrote circleci.yml and build project on CircleCI. It doesn't work.

Error log

```<code>$ npm run test

> static_web_site@0.0.0 test /home/ubuntu/static_web_site
> nightwatch

Starting selenium server... started - PID:  17970

[Test] Test Suite
=====================

Running:  Demo test Google

Error retrieving a new session from the selenium server

Connection refused! Is selenium server started?
{ state: 'session not created',
  sessionId: null,
  hCode: 537979030,
  value:
   { additionalInformation: '\nDriver info: driver.version: ChromeDriver',
     localizedMessage: 'session not created exception: Chrome version must be >= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 3.13.0-119-generic x86_64) (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 746 milliseconds\nBuild info: version: \'3.4.0\', revision: \'unknown\', time: \'unknown\'\nSystem info: host: \'box2107\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'3.13.0-119-generic\', java.version: \'1.8.0_102\'\nDriver info: driver.version: ChromeDriver',
     systemInformation: 'System info: host: \'box2107\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'3.13.0-119-generic\', java.version: \'1.8.0_102\'',
     supportUrl: null,
     cause: null,
     suppressed: [],
     message: 'session not created exception: Chrome version must be >= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 3.13.0-119-generic x86_64) (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 746 milliseconds\nBuild info: version: \'3.4.0\', revision: \'unknown\', time: \'unknown\'\nSystem info: host: \'box2107\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'3.13.0-119-generic\', java.version: \'1.8.0_102\'\nDriver info: driver.version: ChromeDriver',
     hCode: 60610566,
     class: 'org.openqa.selenium.SessionNotCreatedException',
     buildInformation:
      { buildRevision: 'unknown',
        buildTime: 'unknown',
        releaseLabel: '3.4.0',
        hCode: 163722713,
        class: 'org.openqa.selenium.internal.BuildInfo' },
     screen: null },
  class: 'org.openqa.selenium.remote.Response',
  status: 33 }

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! static_web_site@0.0.0 test: `nightwatch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the static_web_site@0.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2017-06-30T02_34_01_711Z-debug.log

npm run test returned exit code 1
</code>```

package.json

```<code>{
  "name": "static_web_site",
  "version": "0.0.0",
  "description": "",
  "scripts": {
    "build": "rimraf dist && webpack",
    "start": "webpack-dev-server -d --colors --inline --hot --port 4000 --host 0.0.0.0",
    "test": "nightwatch",
    "lint": "sass-lint -v -q && pug-lint app/**/*.pug"
  },
  "keywords": [],
  "author": "Allajah",
  "license": "MIT",
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^7.0.0",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-register": "^6.24.1",
    "chromedriver": "^2.30.1",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^2.1.1",
    "file-loader": "^0.10.1",
    "html-webpack-plugin": "^2.28.0",
    "nightwatch": "^0.9.16",
    "node-sass": "^4.5.0",
    "normalize.css": "^6.0.0",
    "postcss-loader": "^2.0.6",
    "pug": "^2.0.0-beta.12",
    "pug-lint": "^2.4.0",
    "pug-loader": "^2.3.0",
    "rimraf": "^2.6.1",
    "sass-lint": "^1.10.2",
    "sass-loader": "^6.0.2",
    "selenium-server-standalone-jar": "=3.4.0",
    "style-loader": "^0.13.2",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.1"
  }
}
</code>```

nightwatch.json

```<code>{
  "src_folders": ["test/e2e/"],
  "output_folder": "test/reports/",
  "custom_commands_path": "",
  "custom_assertions_path": "",
  "page_objects_path": "",
  "globals_path": "node_modules/babel-register",
  "selenium": {
    "start_process": true,
    "server_path": "node_modules/selenium-server-standalone-jar/jar/selenium-server-standalone-3.4.0.jar",
    "log_path": "test/logs",
    "host": "127.0.0.1",
    "port": 4444,
    "cli_args": {
      "webdriver.chrome.driver": "node_modules/.bin/chromedriver"
    }
  },
  "test_settings": {
    "default": {
      "launch_url": "http://localhost",
      "selenium_port": 4444,
      "selenium_host": "localhost",
      "silent": true,
      "screenshots": {
        "enabled": true,
        "on_failure": true,
        "on_error": false,
        "path": "test/screenshots"
      },
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      },
      "globals": {
        "baseUrl": "http://localhost:4000",
        "waitTime": 10000
      },
      "use_xpath": false
    }
  }
}
</code>```

test/e2e/test.js

```<code>module.exports = {
    tag: 'nightwatch test',
    'test': (client) => {
        client.url('http://www.google.com').waitForElementVisible('body', 1000).assert.title('Google').assert.visible('input[type=text]').end()
    }
}
</code>```

circle.yml

```<code>machine:
  node:
    version: 7.4.0
environment:
  PATH: "${PATH}:${HOME}/${CIRCLE_PROJECT_REPONAME}/node_modules/.bin"
dependencies:
  pre:
    - npm i -g npm
test:
  override:
    - npm run build
    - npm run start:
        background: true
    - sleep 10
    - npm run test
</code>```

I wrote these scripts referring to https://github.com/beatfactor/nightwatch-circleci .
And I forked it and tried to run test on CircleCI but it din't work.

Someone can help me to run E2E test with Nightwatch.js on CircleCI?

Thank you :)

答:
You just need to update Chrome on CircleCI.

The error from Selenium states that it is expecting Chrome to be at least version 58. The default Ubuntu images are using older (or much older) versions of Chrome.

To fix this, add these steps to your circle.yml when you install your dependencies:

```<code>wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
sudo apt-get update
sudo apt-get --fix-broken --only-upgrade install google-chrome-stable
</code>```

Body:
I'm developing web sites and want to run test automatically on CircleCI.

I wrote config files and a js file for test, and run E2E test on my machine local. It works.

And then, I wrote circleci.yml and build project on CircleCI. It doesn't work.

Error log

$ npm run test

> static_web_site@0.0.0 test /home/ubuntu/static_web_site
> nightwatch

Starting selenium server... started - PID:  17970

[Test] Test Suite
=====================

Running:  Demo test Google

Error retrieving a new session from the selenium server

Connection refused! Is selenium server started?
{ state: 'session not created',
  sessionId: null,
  hCode: 537979030,
  value:
   { additionalInformation: '\nDriver info: driver.version: ChromeDriver',
     localizedMessage: 'session not created exception: Chrome version must be >= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 3.13.0-119-generic x86_64) (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 746 milliseconds\nBuild info: version: \'3.4.0\', revision: \'unknown\', time: \'unknown\'\nSystem info: host: \'box2107\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'3.13.0-119-generic\', java.version: \'1.8.0_102\'\nDriver info: driver.version: ChromeDriver',
     systemInformation: 'System info: host: \'box2107\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'3.13.0-119-generic\', java.version: \'1.8.0_102\'',
     supportUrl: null,
     cause: null,
     suppressed: [],
     message: 'session not created exception: Chrome version must be >= 58.0.3029.0\n  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 3.13.0-119-generic x86_64) (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 746 milliseconds\nBuild info: version: \'3.4.0\', revision: \'unknown\', time: \'unknown\'\nSystem info: host: \'box2107\', ip: \'127.0.0.1\', os.name: \'Linux\', os.arch: \'amd64\', os.version: \'3.13.0-119-generic\', java.version: \'1.8.0_102\'\nDriver info: driver.version: ChromeDriver',
     hCode: 60610566,
     class: 'org.openqa.selenium.SessionNotCreatedException',
     buildInformation:
      { buildRevision: 'unknown',
        buildTime: 'unknown',
        releaseLabel: '3.4.0',
        hCode: 163722713,
        class: 'org.openqa.selenium.internal.BuildInfo' },
     screen: null },
  class: 'org.openqa.selenium.remote.Response',
  status: 33 }

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! static_web_site@0.0.0 test: `nightwatch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the static_web_site@0.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2017-06-30T02_34_01_711Z-debug.log

npm run test returned exit code 1

package.json

{
  "name": "static_web_site",
  "version": "0.0.0",
  "description": "",
  "scripts": {
    "build": "rimraf dist && webpack",
    "start": "webpack-dev-server -d --colors --inline --hot --port 4000 --host 0.0.0.0",
    "test": "nightwatch",
    "lint": "sass-lint -v -q && pug-lint app/**/*.pug"
  },
  "keywords": [],
  "author": "Allajah",
  "license": "MIT",
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^7.0.0",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-register": "^6.24.1",
    "chromedriver": "^2.30.1",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^2.1.1",
    "file-loader": "^0.10.1",
    "html-webpack-plugin": "^2.28.0",
    "nightwatch": "^0.9.16",
    "node-sass": "^4.5.0",
    "normalize.css": "^6.0.0",
    "postcss-loader": "^2.0.6",
    "pug": "^2.0.0-beta.12",
    "pug-lint": "^2.4.0",
    "pug-loader": "^2.3.0",
    "rimraf": "^2.6.1",
    "sass-lint": "^1.10.2",
    "sass-loader": "^6.0.2",
    "selenium-server-standalone-jar": "=3.4.0",
    "style-loader": "^0.13.2",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.1"
  }
}

nightwatch.json

{
  "src_folders": ["test/e2e/"],
  "output_folder": "test/reports/",
  "custom_commands_path": "",
  "custom_assertions_path": "",
  "page_objects_path": "",
  "globals_path": "node_modules/babel-register",
  "selenium": {
    "start_process": true,
    "server_path": "node_modules/selenium-server-standalone-jar/jar/selenium-server-standalone-3.4.0.jar",
    "log_path": "test/logs",
    "host": "127.0.0.1",
    "port": 4444,
    "cli_args": {
      "webdriver.chrome.driver": "node_modules/.bin/chromedriver"
    }
  },
  "test_settings": {
    "default": {
      "launch_url": "http://localhost",
      "selenium_port": 4444,
      "selenium_host": "localhost",
      "silent": true,
      "screenshots": {
        "enabled": true,
        "on_failure": true,
        "on_error": false,
        "path": "test/screenshots"
      },
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      },
      "globals": {
        "baseUrl": "http://localhost:4000",
        "waitTime": 10000
      },
      "use_xpath": false
    }
  }
}

test/e2e/test.js

module.exports = {
    tag: 'nightwatch test',
    'test': (client) => {
        client.url('http://www.google.com').waitForElementVisible('body', 1000).assert.title('Google').assert.visible('input[type=text]').end()
    }
}

circle.yml

machine:
  node:
    version: 7.4.0
environment:
  PATH: "${PATH}:${HOME}/${CIRCLE_PROJECT_REPONAME}/node_modules/.bin"
dependencies:
  pre:
    - npm i -g npm
test:
  override:
    - npm run build
    - npm run start:
        background: true
    - sleep 10
    - npm run test

I wrote these scripts referring to https://github.com/beatfactor/nightwatch-circleci .
And I forked it and tried to run test on CircleCI but it din't work.

Someone can help me to run E2E test with Nightwatch.js on CircleCI?

Thank you :)

Body:
You just need to update Chrome on CircleCI.

The error from Selenium states that it is expecting Chrome to be at least version 58. The default Ubuntu images are using older (or much older) versions of Chrome.

To fix this, add these steps to your circle.yml when you install your dependencies:

wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
sudo apt-get update
sudo apt-get --fix-broken --only-upgrade install google-chrome-stable


问:
Null variables are not generated properly
PHP 5.6.30 on Apache 2.2.32

I am trying to make a call with SoapClient. One of the classes in the structure of the request has a lot of attributes and most of them must be sent as xsi:nil="true". Here is a simpler class for an example

```<code>class myClass {
  public $attribute1;
  public $attribute2;
  public $attribute3;
}
</code>```

When I send the request the XML without assigning anything (or null to all attributes) is generated as follow (skipping the soap-env and such):

```<code><ns1:class>
  <ns1:attribute1 xsi:nil="true">
    <ns1:attribute2 xsi:nil="true">
      <ns1:attribute3 xsi:nil="true"></ns1:attribute3>
    </ns1:attribute2>
  </ns1:attribute1>
</ns1:class>
</code>```

What I expect is

```<code><ns1:class>
  <ns1:attribute1 xsi:nil="true" />
  <ns1:attribute2 xsi:nil="true" />
  <ns1:attribute3 xsi:nil="true" />
</ns1:class>
</code>```

If I assign a value to lets say attribute2 then the XML will be generated this way:

```<code><ns1:class>
  <ns1:attribute1 xsi:nil="true">
    <ns1:attribute2>my_value</ns1:attribute2>
    <ns1:attribute3 xsi:nil="true"></ns1:attribute3>
  </ns1:attribute1>
</ns1:class>
</code>```

Obviously the remote server is not accepting my request!

Any thoughts on this problem?

BTW I am not providing the WSDL as I would first have to ask for permission.

Thank you

答: Seems like this was a non-issue, at one point while catching my response it was interpreted by the browser (tried Safari and FireFox) which was, I don't know why, producing the wrong display. Using the raw data (ie by writing it to a log file or something similar) got me the right output without this weird behaviour.</p>

Body:
PHP 5.6.30 on Apache 2.2.32

I am trying to make a call with SoapClient. One of the classes in the structure of the request has a lot of attributes and most of them must be sent as xsi:nil="true". Here is a simpler class for an example

class myClass {
  public $attribute1;
  public $attribute2;
  public $attribute3;
}

When I send the request the XML without assigning anything (or null to all attributes) is generated as follow (skipping the soap-env and such):

<ns1:class>
  <ns1:attribute1 xsi:nil="true">
    <ns1:attribute2 xsi:nil="true">
      <ns1:attribute3 xsi:nil="true"></ns1:attribute3>
    </ns1:attribute2>
  </ns1:attribute1>
</ns1:class>

What I expect is

<ns1:class>
  <ns1:attribute1 xsi:nil="true" />
  <ns1:attribute2 xsi:nil="true" />
  <ns1:attribute3 xsi:nil="true" />
</ns1:class>

If I assign a value to lets say attribute2 then the XML will be generated this way:

<ns1:class>
  <ns1:attribute1 xsi:nil="true">
    <ns1:attribute2>my_value</ns1:attribute2>
    <ns1:attribute3 xsi:nil="true"></ns1:attribute3>
  </ns1:attribute1>
</ns1:class>

Obviously the remote server is not accepting my request!

Any thoughts on this problem?

BTW I am not providing the WSDL as I would first have to ask for permission.

Thank you


问:
Open other applications with their Deeplinks in Swift
I am learning to have deep links in my application.

I would like to have my users link their social media, blog, or other site in my application.

But, it should attempt to open a link by detecting the site and attempt to open that site's application (at least for mainstream social media etc).

I was attempting to use https://github.com/BranchMetrics/Roots-iOS but their own demo does not even work it seems and I could not get my application to work(I am also using swift so I am not used to reading Obj-C too much).

Does anyone know how to do this?

答:
Although it is not quite what i needed, the library https://github.com/SwiftKitz/Appz is pretty close.

It launches to an external application, with a web fall back.  It is also pretty easy to add code to pass a url and detect the base application and parse it out into that applications deeplinking scheme (which was info I didn't have before.)

Sorry for the trouble on this.


问:
Passing C++ double array to Python Results in a Crash
I'm running into an issue while trying to pass a double array from C++ to Python.  I run a script to create a binary file with data, then read that data back into an array and am trying to pass the array to Python.  I've followed advice here: how to return array from c function to python using ctypes among other pages I have found through google.  I can write a generic example that works fine (like a similar array to the link above), but when I try to pass the array read from a binary file (code below), the program crashes with "Unhandled exception at ADDR (ucrtbase.dll) in python.exe: An invalid parameter was passed to a function that considers invalid parameters fatal."  So, I'm wondering if anyone has any insight.

A word on methodology:

Right now, I'm just trying to learn - that's why  I'm going through the convoluted process of saving to disk, loading, and passing to Python.  Eventaully, I will use this in scientific simulations where the data read from disk needs to be generated by distributed computing/a super computer.  I would like to use Python for its ease of plotting (matplotlib) and C++ for its speed (iterative calculations, etc).

So, on to my code.  This generates the binary file:

```<code>for (int zzz = 0; zzz < arraysize; ++zzz)
{
    for (int yyy = 0; yyy < arraysize; ++yyy)
    {
        for (int xxx = 0; xxx < arraysize; ++xxx)
        {//totalBatP returns a 3 element std::vector<double> - dblArray3_t is basically that with a few overloaded operators (+,-,etc)
            dblArray3_t BatP = B.totalBatP({ -5 + xxx * stepsize, -5 + yyy * stepsize, -5 + zzz * stepsize }, 37);
            for (int bbb = 0; bbb < 3; ++bbb)
            {
                dataarray[loopind] = BatP[bbb];
                ++loopind;
                ...(end braces here)
FILE* binfile;
binfile = fopen("MBdata.bin", "wb");
fwrite(dataarray, 8, 3 * arraysize * arraysize * arraysize, binfile);
</code>```

The code that reads the file:

```<code>DLLEXPORT double* readDblBin(const std::string filename, unsigned int numOfDblsToRead)
{
    char* buffer = new char[numOfDblsToRead];
    std::ifstream binFile;
    binFile.open(filename, std::ios::in | std::ios::binary);
    binFile.read(buffer, numOfDblsToRead);
    double* dataArray = (double*)buffer;
    binFile.close();

    return dataArray;
}
</code>```

And the Python Code that receives the array:

```<code>def readBDataWrapper(filename, numDblsToRead):
    fileIO = ctypes.CDLL('./fileIO.dll')
    fileIO.readDblBin.argtypes = (ctypes.c_char_p, ctypes.c_uint)
    fileIO.readDblBin.restype = ctypes.POINTER(ctypes.c_double)

    return fileIO.readDblBin(filename, numDblsToRead)
</code>```

答:
One possible problem is here

```<code>char* buffer = new char[numOfDblsToRead];
</code>```

Here you allocate numOfDblsToRead bytes. You probably want numOfDblsToRead * sizeof(double).

Same with the reading from the file, you only read numOfDblsToRead bytes.

Body:
I'm running into an issue while trying to pass a double array from C++ to Python.  I run a script to create a binary file with data, then read that data back into an array and am trying to pass the array to Python.  I've followed advice here: how to return array from c function to python using ctypes among other pages I have found through google.  I can write a generic example that works fine (like a similar array to the link above), but when I try to pass the array read from a binary file (code below), the program crashes with "Unhandled exception at ADDR (ucrtbase.dll) in python.exe: An invalid parameter was passed to a function that considers invalid parameters fatal."  So, I'm wondering if anyone has any insight.

A word on methodology:

Right now, I'm just trying to learn - that's why  I'm going through the convoluted process of saving to disk, loading, and passing to Python.  Eventaully, I will use this in scientific simulations where the data read from disk needs to be generated by distributed computing/a super computer.  I would like to use Python for its ease of plotting (matplotlib) and C++ for its speed (iterative calculations, etc).

So, on to my code.  This generates the binary file:

for (int zzz = 0; zzz < arraysize; ++zzz)
{
    for (int yyy = 0; yyy < arraysize; ++yyy)
    {
        for (int xxx = 0; xxx < arraysize; ++xxx)
        {//totalBatP returns a 3 element std::vector<double> - dblArray3_t is basically that with a few overloaded operators (+,-,etc)
            dblArray3_t BatP = B.totalBatP({ -5 + xxx * stepsize, -5 + yyy * stepsize, -5 + zzz * stepsize }, 37);
            for (int bbb = 0; bbb < 3; ++bbb)
            {
                dataarray[loopind] = BatP[bbb];
                ++loopind;
                ...(end braces here)
FILE* binfile;
binfile = fopen("MBdata.bin", "wb");
fwrite(dataarray, 8, 3 * arraysize * arraysize * arraysize, binfile);

The code that reads the file:

DLLEXPORT double* readDblBin(const std::string filename, unsigned int numOfDblsToRead)
{
    char* buffer = new char[numOfDblsToRead];
    std::ifstream binFile;
    binFile.open(filename, std::ios::in | std::ios::binary);
    binFile.read(buffer, numOfDblsToRead);
    double* dataArray = (double*)buffer;
    binFile.close();

    return dataArray;
}

And the Python Code that receives the array:

def readBDataWrapper(filename, numDblsToRead):
    fileIO = ctypes.CDLL('./fileIO.dll')
    fileIO.readDblBin.argtypes = (ctypes.c_char_p, ctypes.c_uint)
    fileIO.readDblBin.restype = ctypes.POINTER(ctypes.c_double)

    return fileIO.readDblBin(filename, numDblsToRead)

Body:
One possible problem is here

char* buffer = new char[numOfDblsToRead];

Here you allocate numOfDblsToRead bytes. You probably want numOfDblsToRead * sizeof(double).

Same with the reading from the file, you only read numOfDblsToRead bytes.


问:
Object to database with PDO, is it possible?
I'm using PDO's fetch_class feature to retrieve data from my database row into object, It's pretty convenient, but how can I do to do the opposite (object to database row) ? without using serialization of course.</p>

答:
Haven't used PDO before, I assume the fetch's contents are stored as $object->Key?

You'd have to write an update method/function

$sql = "UPDATE `table` SET `fieldone` = '$object->fieldone',`fieldtwo` = '$object->fieldtwo' WHERE `id` = $object->id"

mysql_query($sql);

etc.


问:
Use match from file in string
I have a list of user ids in a file and I'm trying to generate some sql from the file.

```<code>cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'
</code>```

But it's not doing what I expected it to do:

```<code>);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"
</code>```

The query I am trying for is:

```<code>INSERT IGNORE INTO potential_problem_users VALUES ([userID]);
</code>```

example json if it helps:

```<code>{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}
</code>```

Am I using the right tool? If I am, what am I doing wrong?

答:
Your JSON input has a couple of issues which makes it impossible to parse them using parser like jq which on OS X you can install by brew install jq

The error free JSON from your question would be

```<code>{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}
</code>```

To parse this JSON and produce two statements as queries containing the UID values, just do

```<code>jq --raw-output '"INSERT IGNORE INTO potential_problem_users VALUES (" + (.results[] | .UID) + ")"' users.json
</code>```

would produce an output as

```<code>INSERT IGNORE INTO potential_problem_users VALUES (abc)
INSERT IGNORE INTO potential_problem_users VALUES (124)
</code>```

The addition operator + in jq allows you to concatenate strings to form the final string.

jq snippet from jqplay.

Title: Use match from file in string

Body:
I have a list of user ids in a file and I'm trying to generate some sql from the file.

cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'

But it's not doing what I expected it to do:

);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"

The query I am trying for is:

INSERT IGNORE INTO potential_problem_users VALUES ([userID]);

example json if it helps:

{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}

Am I using the right tool? If I am, what am I doing wrong?

Body:
Your JSON input has a couple of issues which makes it impossible to parse them using parser like jq which on OS X you can install by brew install jq

The error free JSON from your question would be

{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}

To parse this JSON and produce two statements as queries containing the UID values, just do

jq --raw-output '"INSERT IGNORE INTO potential_problem_users VALUES (" + (.results[] | .UID) + ")"' users.json

would produce an output as

INSERT IGNORE INTO potential_problem_users VALUES (abc)
INSERT IGNORE INTO potential_problem_users VALUES (124)

The addition operator + in jq allows you to concatenate strings to form the final string.

jq snippet from jqplay.


问:
Get the rows from previous month
I am trying this query

```<code>SELECT *
FROM flexible_products
WHERE YEAR(updated_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
AND MONTH(updated_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
</code>```

for my current work. What I want to do is to get all rows from the previous month,

Like for example, we have today July 04, 2017, I would like to get rows from January to June, which is not the outcome of the above query.

What is the best way to this in MySQL?

答:
a bit shorter. Not sure if also faster</p>

```<code>SELECT *
FROM flexible_products
WHERE
  YEAR(updated_at) = YEAR(CURRENT_DATE) AND
  MONTH(updated_at) < MONTH(CURRENT_DATE())
</code>```

Title: Get the rows from previous month

Body:
I am trying this query

SELECT *
FROM flexible_products
WHERE YEAR(updated_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
AND MONTH(updated_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))

for my current work. What I want to do is to get all rows from the previous month,

Like for example, we have today July 04, 2017, I would like to get rows from January to June, which is not the outcome of the above query.

What is the best way to this in MySQL?

Body:
a bit shorter. Not sure if also faster

SELECT *
FROM flexible_products
WHERE
  YEAR(updated_at) = YEAR(CURRENT_DATE) AND
  MONTH(updated_at) < MONTH(CURRENT_DATE())


问:
webpack2 code splitting and CommonsChunkPlugin
I ran into a problem using code splitting and the CommonsChunkPlugin. I'm used to require.js where the files are cached automatically. I'm also using the libraryTarget: 'amd' for my webpack configuration.

Considering these two simple files, this is the output I get:

```<code>// fileA.js
import $ from 'jquery'

// fileB.js
import $ from 'jquery'

   Asset    Size  Chunks                    Chunk Names
fileB.js  271 kB       0  [emitted]  [big]  fileB
fileA.js  271 kB       1  [emitted]  [big]  fileA
</code>```

So both files, fileA and fileB have jquery included. Also, I'm able to use these files like this in my html file.

```<code>require(['./dist/fileA.js', './dist/fileB.js'], function () {
})
</code>```

As per the docs I can use the CommonsChunkPlugin to basically extract jquery into its own file, so my config looks like this:

```<code>new webpack.optimize.CommonsChunkPlugin({
  name: 'common'
}),
</code>```

resulting in this output:

```<code>    Asset       Size  Chunks                    Chunk Names
 fileB.js  635 bytes       0  [emitted]         fileB
 fileA.js  617 bytes       1  [emitted]         fileA
common.js     274 kB       2  [emitted]  [big]  common
</code>```

BUT now I'm unable to use the above require block, because the common.js also includes the webpack runtime. All I now get is an Uncaught ReferenceError: webpackJsonp is not defined error.

So what I would need is:

fileA.js (only contains "fileA" code, requiring jquery)

fileB.js (only contains "fileB" code, requiring jquery)

jquery.js (all of the jquery stuff)

common.js (only contains the runtime for webpack)

I already tried something like this for fileA and fileB, but it's basically the same output:

```<code>define(['jquery'], function ($) {

})
</code>```

A (Vendor) library should only be loaded, if a script (like fileA) is loaded and has it as a dependency (as it is with requirejs).

Can this be accomplished? I skimmed through the webpack2 docs numerous times, but couldn't find anything that could help me...

edit: Ok, with the help of some github issues, I managed to get the correct asset generation with the following configuration:

```<code>module.exports = {
  entry: {
    jquery: ['jquery'],
    vue: ['vue'],
    fileA: ['./src/fileA.js'],
    fileB: ['./src/fileB.js'],
    fileC: ['./src/fileC.js']
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist',
    filename: '[name].js',
    libraryTarget: 'amd'
  }
}

module.exports.plugins = (module.exports.plugins || []).concat([
  new webpack.optimize.CommonsChunkPlugin({
    name: ['vue', 'jquery']
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    chunks: ['vue', 'jquery'],
    minChunks: Infinity
  }),
  new webpack.optimize.OccurrenceOrderPlugin()
])
</code>```

I changed the source files to:

```<code>// fileA.js
import $ from 'jquery'
import Vue from 'vue'
// fileB.js
import $ from 'jquery'
// fileC.js
import Vue from 'vue'
</code>```

And this is the output:

```<code>   vue.js     193 kB       0  [emitted]         vue
 fileC.js  447 bytes       1  [emitted]         fileC
 fileB.js  579 bytes       2  [emitted]         fileB
 fileA.js  666 bytes       3  [emitted]         fileA
jquery.js     269 kB       4  [emitted]  [big]  jquery
common.js    5.78 kB       5  [emitted]         common
</code>```

However, using it in an .html file like so results in the following error:

```<code><body>
  <script src="./dist/common.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.3/require.js"></script>
  <script>
    require(['./dist/fileA.js', './dist/fileB.js', './dist/fileC.js'], function (a, b, c) {
    })
  </script>
</body>
</code>```

The following error occurs both for fileA and for fileC...

```<code>common.js:55 Uncaught TypeError: Cannot read property 'call' of undefined
    at __webpack_require__ (common.js:55)
    at Object.7 (fileA.js:16)
    at __webpack_require__ (common.js:55)
    at Object.6 (fileA.js:6)
    at __webpack_require__ (common.js:55)
    at webpackJsonpCallback (common.js:26)
    at fileA.js:1
    at Object.execCb (require.js:1696)
    at Module.check (require.js:883)
    at Module.enable (require.js:1176)
</code>```

edit:

I've create a repo on github showing the problem I ran into. As per the answer of Rafael De Leon, I'm now using System.import('<module>') to asynchronously import other files. main.ts imports fileA.ts via this syntax, resulting in an error when output.js (the compiled main.ts file) is required. The error seems to happen when fileA is being loaded from withing output.js... I've also created a github issue, because I think it's a bug.

答:
A (Vendor) library should only be loaded, if a script (like fileA) is loaded and has it as a dependency (as it is with requirejs).

If you want this result, CommonsChunkPlugin isn't what you are looking for. That plugin is to aggregate files that are used by different entries or other CommonChunkPlugin into one file.

I think what you are looking for import() or require.ensure to load "vendor" files on demand

otherwise How to bundle vendor scripts separately and require them as needed with Webpack? will work

Body:
I ran into a problem using code splitting and the CommonsChunkPlugin. I'm used to require.js where the files are cached automatically. I'm also using the libraryTarget: 'amd' for my webpack configuration.

Considering these two simple files, this is the output I get:

// fileA.js
import $ from 'jquery'

// fileB.js
import $ from 'jquery'

   Asset    Size  Chunks                    Chunk Names
fileB.js  271 kB       0  [emitted]  [big]  fileB
fileA.js  271 kB       1  [emitted]  [big]  fileA

So both files, fileA and fileB have jquery included. Also, I'm able to use these files like this in my html file.

require(['./dist/fileA.js', './dist/fileB.js'], function () {
})

As per the docs I can use the CommonsChunkPlugin to basically extract jquery into its own file, so my config looks like this:

new webpack.optimize.CommonsChunkPlugin({
  name: 'common'
}),

resulting in this output:

    Asset       Size  Chunks                    Chunk Names
 fileB.js  635 bytes       0  [emitted]         fileB
 fileA.js  617 bytes       1  [emitted]         fileA
common.js     274 kB       2  [emitted]  [big]  common

BUT now I'm unable to use the above require block, because the common.js also includes the webpack runtime. All I now get is an Uncaught ReferenceError: webpackJsonp is not defined error.

So what I would need is:

fileA.js (only contains "fileA" code, requiring jquery)

fileB.js (only contains "fileB" code, requiring jquery)

jquery.js (all of the jquery stuff)

common.js (only contains the runtime for webpack)

I already tried something like this for fileA and fileB, but it's basically the same output:

define(['jquery'], function ($) {

})

A (Vendor) library should only be loaded, if a script (like fileA) is loaded and has it as a dependency (as it is with requirejs).

Can this be accomplished? I skimmed through the webpack2 docs numerous times, but couldn't find anything that could help me...

edit: Ok, with the help of some github issues, I managed to get the correct asset generation with the following configuration:

module.exports = {
  entry: {
    jquery: ['jquery'],
    vue: ['vue'],
    fileA: ['./src/fileA.js'],
    fileB: ['./src/fileB.js'],
    fileC: ['./src/fileC.js']
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist',
    filename: '[name].js',
    libraryTarget: 'amd'
  }
}

module.exports.plugins = (module.exports.plugins || []).concat([
  new webpack.optimize.CommonsChunkPlugin({
    name: ['vue', 'jquery']
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    chunks: ['vue', 'jquery'],
    minChunks: Infinity
  }),
  new webpack.optimize.OccurrenceOrderPlugin()
])

I changed the source files to:

// fileA.js
import $ from 'jquery'
import Vue from 'vue'
// fileB.js
import $ from 'jquery'
// fileC.js
import Vue from 'vue'

And this is the output:

   vue.js     193 kB       0  [emitted]         vue
 fileC.js  447 bytes       1  [emitted]         fileC
 fileB.js  579 bytes       2  [emitted]         fileB
 fileA.js  666 bytes       3  [emitted]         fileA
jquery.js     269 kB       4  [emitted]  [big]  jquery
common.js    5.78 kB       5  [emitted]         common

However, using it in an .html file like so results in the following error:

The following error occurs both for fileA and for fileC...

common.js:55 Uncaught TypeError: Cannot read property 'call' of undefined
    at __webpack_require__ (common.js:55)
    at Object.7 (fileA.js:16)
    at __webpack_require__ (common.js:55)
    at Object.6 (fileA.js:6)
    at __webpack_require__ (common.js:55)
    at webpackJsonpCallback (common.js:26)
    at fileA.js:1
    at Object.execCb (require.js:1696)
    at Module.check (require.js:883)
    at Module.enable (require.js:1176)

edit:

I've create a repo on github showing the problem I ran into. As per the answer of Rafael De Leon, I'm now using System.import('<module>') to asynchronously import other files. main.ts imports fileA.ts via this syntax, resulting in an error when output.js (the compiled main.ts file) is required. The error seems to happen when fileA is being loaded from withing output.js... I've also created a github issue, because I think it's a bug.


问:
Aggregate rows of Spark DataFrame to String after groupby
I'm quite new both Spark and Scale and could really need a hint to solve my problem. So I have two DataFrames A (columns id and name) and B (columns id and text) would like to join them, group by id and combine all rows of text into a single String:

A

```<code>+--------+--------+
|      id|    name|
+--------+--------+
|       0|       A|
|       1|       B|
+--------+--------+
</code>```

B

```<code>+--------+ -------+
|      id|    text|
+--------+--------+
|       0|     one|
|       0|     two|
|       1|   three|
|       1|    four|
+--------+--------+
</code>```

desired result:

```<code>+--------+--------+----------+
|      id|    name|     texts|
+--------+--------+----------+
|       0|       A|   one two|
|       1|       B|three four|
+--------+--------+----------+
</code>```

So far I'm trying the following:

```<code>var C = A.join(B, "id")
var D = C.groupBy("id", "name").agg(collect_list("text") as "texts")
</code>```

This works quite well besides that my texts column is an Array of Strings instead of a String. I would appreciate some help very much.

答:
It's quite simple:

```<code>val bCollected = b.groupBy('id).agg(collect_list('text).as("texts")
val ab = a.join(bCollected, a("id") == bCollected("id"), "left")
</code>```

First DataFrame is immediate result, b DataFrame that has texts collected for every id. Then you are joining it with a. bCollected should be smaller that b itself, so it will probably get better shuffle time

Body:
I'm quite new both Spark and Scale and could really need a hint to solve my problem. So I have two DataFrames A (columns id and name) and B (columns id and text) would like to join them, group by id and combine all rows of text into a single String:

A

+--------+--------+
|      id|    name|
+--------+--------+
|       0|       A|
|       1|       B|
+--------+--------+

B

+--------+ -------+
|      id|    text|
+--------+--------+
|       0|     one|
|       0|     two|
|       1|   three|
|       1|    four|
+--------+--------+

desired result:

+--------+--------+----------+
|      id|    name|     texts|
+--------+--------+----------+
|       0|       A|   one two|
|       1|       B|three four|
+--------+--------+----------+

So far I'm trying the following:

var C = A.join(B, "id")
var D = C.groupBy("id", "name").agg(collect_list("text") as "texts")

This works quite well besides that my texts column is an Array of Strings instead of a String. I would appreciate some help very much.

Body:
It's quite simple:

val bCollected = b.groupBy('id).agg(collect_list('text).as("texts")
val ab = a.join(bCollected, a("id") == bCollected("id"), "left")

First DataFrame is immediate result, b DataFrame that has texts collected for every id. Then you are joining it with a. bCollected should be smaller that b itself, so it will probably get better shuffle time


答:
use display:flex

```<code>.welcomeAreaContent .welcomeName{
  font-weight: bold;
  font-size: 1.7em;
  display: flex;
  align-items: center;
}
</code>```

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
  display: flex;
    align-items: center;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="welcomeArea">
 <div class="welcomeAreaContent">
  <div class="welcomeName">
   TEXT TEXT
   <span class ="circle twittericon"></span>
  </div>
  <div class="verticalLine">
  </div>
 </div>
</div></code>```

Here is the working Fiddle

Title: Align elements vertically inside a div

Body:
I'm trying to align elements vertically inside a div, but I'm stuck with circles.
The red div is 100% width, with my code, but the vertical line does not show, and the circles (that are divs or spans with background images) are not in the middle.

My code:

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}

         TEXT TEXT

The result looks like the following which is not good at all:

Body:
use display:flex

.welcomeAreaContent .welcomeName{
  font-weight: bold;
  font-size: 1.7em;
  display: flex;
  align-items: center;
}

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
  display: flex;
    align-items: center;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}

<div class="welcomeArea">
 <div class="welcomeAreaContent">
  <div class="welcomeName">
   TEXT TEXT
   <span class ="circle twittericon"></span>
  </div>
  <div class="verticalLine">
  </div>
 </div>
</div>

Here is the working Fiddle


问:
Weird Footer Behavior
I'm relatively new to CSS, so please pardon me for the odd gaffe. I defined a footer to have absolute position, and it stays at the bottom for all all but one pages on my website.

...>The footer here behaves perfectly, i.e., it's position is glued to the bottom of the screen regardless of the content.

...>Whereas, the footer below behaves abnormally, it's position isn't glued to the bottom of the page.

I am using the same footer class on both the pages, so I'm not sure what's wrong here, mentioned below -

```<code>.shell3-Footer {
box-sizing: border-box;
padding: 0.9375rem;
border-top: 0.0625rem solid #dcdcdc;
overflow: hidden;
max-height:40px;
width:100%;
background-color:#f5f5f5;
position:absolute; }
</code>```

Note that if I change the position to fixed, then the problem is only partially solved, as I need the footer to be seen only when we scroll to the bottom of the page. Also, when the position:fixed is used, I'm not able to view the down-arrow of the scroll bar - which is not desired behavior.

Additionally, there is a slight whitespace beneath the faulty footer which I corrected by adding bottom:0pxto it.

Can someone help why the same footer class would behave differently on two pages? Thoughts?

答:
Try this:</p>

```<code>body {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* Put this class on everything that is not the footer */
.content {
  flex: 1 0 auto;
}

.shell3-Footer {
  flex-shrink: 0; /* new stuff */
  width:100%;
  background-color:#f5f5f5;
  box-sizing: border-box;
  padding: 0.9375rem;
  border-top: 0.0625rem solid #dcdcdc;
  overflow: hidden;
}
</code>```

Title: Weird Footer Behavior

Body:
I'm relatively new to CSS, so please pardon me for the odd gaffe. I defined a footer to have absolute position, and it stays at the bottom for all all but one pages on my website.

...>The footer here behaves perfectly, i.e., it's position is glued to the bottom of the screen regardless of the content.

...>Whereas, the footer below behaves abnormally, it's position isn't glued to the bottom of the page.

I am using the same footer class on both the pages, so I'm not sure what's wrong here, mentioned below -

.shell3-Footer {
box-sizing: border-box;
padding: 0.9375rem;
border-top: 0.0625rem solid #dcdcdc;
overflow: hidden;
max-height:40px;
width:100%;
background-color:#f5f5f5;
position:absolute; }

Note that if I change the position to fixed, then the problem is only partially solved, as I need the footer to be seen only when we scroll to the bottom of the page. Also, when the position:fixed is used, I'm not able to view the down-arrow of the scroll bar - which is not desired behavior.

Additionally, there is a slight whitespace beneath the faulty footer which I corrected by adding bottom:0pxto it.

Can someone help why the same footer class would behave differently on two pages? Thoughts?

Body:
Try this:

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* Put this class on everything that is not the footer */
.content {
  flex: 1 0 auto;
}

.shell3-Footer {
  flex-shrink: 0; /* new stuff */
  width:100%;
  background-color:#f5f5f5;
  box-sizing: border-box;
  padding: 0.9375rem;
  border-top: 0.0625rem solid #dcdcdc;
  overflow: hidden;
}


问:
android studio 3, how to configure sdk version
I'm trying to set the sdk installed version on my pc: sdk 19. I've got an error:

```<code>Error:Failed to find target with hash string 'android-25' in: /Users/myuser/Library/Android/sdk
<a href="install.android.platform">Install missing platform(s) and sync project</a>
</code>```

Where is the file where I have to set the sdk version, min or max  ? Not the folder of sdk

the project come from an Ionic 3 project.

I've changed the file ./AndroidManifest.xml :

```<code><uses-sdk android:minSdkVersion="16" android:targetSdkVersion="19" />
</code>```

./project properties:

target=android-19

And finally I change on Android Studio   menu "File" - "Project Structure" , Tab "Properties" ,

Fields:

```<code>"Compile sdk version"  = "API 19 Android 4.42"
"Build Tools version" = 26.0.0
</code>```

but the errors keeps....

答:
Where is the file where I have to set the sdk ?
Anyplace you prefer too

What SDK version should I use?
Depends in your audiences

Make sure your SDK location is referred to where you downloaded it.

Body:
I'm trying to set the sdk installed version on my pc: sdk 19. I've got an error:

Error:Failed to find target with hash string 'android-25' in: /Users/myuser/Library/Android/sdk
Install missing platform(s) and sync project

Where is the file where I have to set the sdk version, min or max  ? Not the folder of sdk

the project come from an Ionic 3 project.

I've changed the file ./AndroidManifest.xml :

<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="19" />

./project properties:

target=android-19

And finally I change on Android Studio   menu "File" - "Project Structure" , Tab "Properties" ,

Fields:

"Compile sdk version"  = "API 19 Android 4.42"
"Build Tools version" = 26.0.0

but the errors keeps....


问:
Cannot read property 'password' of undefined at Query._callback Node.js
While implementing passport and working the backend for it i got this error. Could anyone help me figure out how to fix it?

TypeError: Cannot read property 'password' of undefined
      at Query._callback (/Users/oscarstein/Documents/Programering/express-cc/app.js:76:32)

Using the following code:

```<code>passport.use(new LocalStrategy(
  function(username, password, done) {
      console.log(username);
      console.log(password);
      const db = require('./db');

      db.query('SELECT id, password FROM users WHERE username = ?', [username], function(err, results, fields){
        if (err) {done(err)};

        if (results.length == 0) {
          done(null, false);
        }

        const hash = results[0].password.toString();

        bcrypt.compare(password, hash, function(err, response){
            if (response == true) {
              return done(null, {user_id: results[0].id});
            } else {
              return done(null, false);
            }

          });
      })

    }
));
</code>```

答:
Consider these lines of code

```<code>if (err) {done(err)};

if (results.length == 0) {
    done(null, false);
}
</code>```

It checks for error existence, then executes function done(err) and the function flow goes on.

Then it checks if there are results, calls function done(null, false) and the flow goes on again.

Correct way of doing this is

```<code>if (err) {
    return done(err)
}

if (results.length == 0) {
    return done(null, false);
}
</code>```

Notice return statement above. It breaks further code execution inside of this callback function.

Body:
While implementing passport and working the backend for it i got this error. Could anyone help me figure out how to fix it?

TypeError: Cannot read property 'password' of undefined
      at Query._callback (/Users/oscarstein/Documents/Programering/express-cc/app.js:76:32)

Using the following code:

passport.use(new LocalStrategy(
  function(username, password, done) {
      console.log(username);
      console.log(password);
      const db = require('./db');

      db.query('SELECT id, password FROM users WHERE username = ?', [username], function(err, results, fields){
        if (err) {done(err)};

        if (results.length == 0) {
          done(null, false);
        }

        const hash = results[0].password.toString();

        bcrypt.compare(password, hash, function(err, response){
            if (response == true) {
              return done(null, {user_id: results[0].id});
            } else {
              return done(null, false);
            }

          });
      })

    }
));

Body:
Consider these lines of code

if (err) {done(err)};

if (results.length == 0) {
    done(null, false);
}

It checks for error existence, then executes function done(err) and the function flow goes on.

Then it checks if there are results, calls function done(null, false) and the flow goes on again.

Correct way of doing this is

if (err) {
    return done(err)
}

if (results.length == 0) {
    return done(null, false);
}

Notice return statement above. It breaks further code execution inside of this callback function.


问:
Object is identified only if it is visible with eye on browser window - UFT
We are automating a web application using UFT/QTP. The issue is that UFT works only on those web objects which are seen in browser window part. If any object/element is at the bottom of the page and require scroll down in window to be seen. UFT is not able to work on those objects. We have written code to  page down to work on those objects. It works fine. But sometimes when page is very lengthy and we don't know at what position that object will be like in middle of the page, or far bottom of the page etc. In that case, only page down does not work. Is there any way that we can make the object visible on the basis of object properties? That means we can bring object in front of the window.</p>

答:
UFT doesn't depend on whether the object is in view or not. If an object is scrolled out of view UFT will automatically scroll it into view before performing any action upon it (e.g. Click).

The behaviour you're describing may be caused by the fact that the web site dynamically adds objects to the DOM when the page is scrolled. If this is the case then UFT has no way to know what will cause the object to be added to the DOM and you have to scroll for it they you've been doing.

Sorry I couldn't bring better news :(