问:
AddGesture different in Swift 3?
I have no idea why my code isn't working :

```<code>let profileImageView: UIImageView = {
    let image = UIImageView()
    image.image = UIImage(named: "gameofthrones_splash")
    image.translatesAutoresizingMaskIntoConstraints = false
    image.contentMode = .scaleAspectFill
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
    image.addGestureRecognizer(tapGesture)
    image.isUserInteractionEnabled = true

    return image
}()
</code>```

This imageView is loaded in the ViewDidLoad (I can see it)

```<code>func handleSelectProfileImageView() {
    print("123")
}
</code>```

But nothing get returned in the console when I'm tapping on it ! WTF?

答:
I fixed this issue using an UIButton -></p>

```<code>let profileImageView: UIButton = {
    let iv = UIButton()
    let image = UIImage(named: "r2d2")
    iv.setImage(image, for: .normal)
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.addTarget(self, action: #selector(selectProfileImage), for: .touchUpInside)
    iv.isUserInteractionEnabled = true
    return iv
}()

@objc func selectProfileImage(){
    print("Hello")
}
</code>```

Title: AddGesture different in Swift 3?

Body:
I have no idea why my code isn't working :

let profileImageView: UIImageView = {
    let image = UIImageView()
    image.image = UIImage(named: "gameofthrones_splash")
    image.translatesAutoresizingMaskIntoConstraints = false
    image.contentMode = .scaleAspectFill
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
    image.addGestureRecognizer(tapGesture)
    image.isUserInteractionEnabled = true

    return image
}()

This imageView is loaded in the ViewDidLoad (I can see it)

func handleSelectProfileImageView() {
    print("123")
}

But nothing get returned in the console when I'm tapping on it ! WTF?

Body:
I fixed this issue using an UIButton ->

let profileImageView: UIButton = {
    let iv = UIButton()
    let image = UIImage(named: "r2d2")
    iv.setImage(image, for: .normal)
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.addTarget(self, action: #selector(selectProfileImage), for: .touchUpInside)
    iv.isUserInteractionEnabled = true
    return iv
}()

@objc func selectProfileImage(){
    print("Hello")
}


来源: stackexchange

问:
JS: Why are variables allowed to be declared both with and without the `var` keyword...?
It is possible to declare a javascript variable both with and without the var keyword.

```<code>var a = 100; // this works!
    b = 200; // and this does too!
</code>```

It is also possible to declare a variable without initialisation.

```<code>var c;       // this is just as acceptable!
</code>```

But then why is the same NOT true for a variable without var, to be declared without initialisation.

```<code>var c;
    d;       // causes a reference error to occur!
</code>```

Why?

答:
First, what you're seeing is legacy behavior. Assignment to an undeclared symbol traditionally meant, implicitly, that a global symbol should be created (declared) and set to the given value. Thus

```<code>x = 1;
</code>```

when x has not been declared was taken to be an implicit instantiation of a global symbol.

The mention of an undeclared symbol, as in:

```<code>x;
</code>```

is an error because the symbol is undeclared.

In modern JavaScript, and when "strict" mode is in force because of a

```<code>"use strict";
</code>```

statement (or because of other influences, as may be the case with Node.js code), the implicit creation of global symbols is also erroneous.

Generally, implicit global symbol instantiation is considered a bad idea. Global symbols in browser JavaScript are quite problematic because the global namespace is so horribly polluted. Thankfully, it's easy to wrap code in a function scope to create a "safe space" for symbols without fear of the browser imposing weird global names.

ContentLicense: CC BY-SA 3.0

Body:
It is possible to declare a javascript variable both with and without the var keyword.

var a = 100; // this works!
    b = 200; // and this does too!

It is also possible to declare a variable without initialisation.

var c;       // this is just as acceptable!

But then why is the same NOT true for a variable without var, to be declared without initialisation.

var c;
    d;       // causes a reference error to occur!

Why?

Body:
First, what you're seeing is legacy behavior. Assignment to an undeclared symbol traditionally meant, implicitly, that a global symbol should be created (declared) and set to the given value. Thus

x = 1;

when x has not been declared was taken to be an implicit instantiation of a global symbol.

The mention of an undeclared symbol, as in:

x;

is an error because the symbol is undeclared.

In modern JavaScript, and when "strict" mode is in force because of a

"use strict";

statement (or because of other influences, as may be the case with Node.js code), the implicit creation of global symbols is also erroneous.

Generally, implicit global symbol instantiation is considered a bad idea. Global symbols in browser JavaScript are quite problematic because the global namespace is so horribly polluted. Thankfully, it's easy to wrap code in a function scope to create a "safe space" for symbols without fear of the browser imposing weird global names.


问:
Compile error C2027 in VS2017 but not Clang with small object optimization
So I'm trying to implement small object optimization in a project of mine, but I'm running into a strange compiler error. Here's some simplified code that reproduces the issue:

```<code>#include <type_traits>

template<typename T>
class Wrapper {
    T thing;
public:
    Wrapper(T&& thing) {
        // ...
    }
};

class Test {
    static const size_t PADDING_SIZE = 64;
public:
    template<
        typename T,
        std::enable_if_t<sizeof(Wrapper<std::decay_t<T>>) <= PADDING_SIZE, int> = 0
        // Error on this line ^
    >
    Test(T&& thing) {
        new (padding) Wrapper<std::decay_t<T>>(std::forward<T>(thing));
    }

    char padding[PADDING_SIZE];
};

int main() {
    auto t = Test(0.0f);
}
</code>```

Basically, I need to take an arbitrary object, put it in a wrapper, and instantiate an instance of the wrapper in the padding, but I need to use one wrapper for types that can fit in the padding and a different one for types that are too large (one of the wrappers stores the object in place while the other allocates external space for it). And obviously I'd like to support perfect forwarding.

Unfortunately, VS2017 gives me the following compiler error: error C2027: use of undefined type 'Wrapper<decay<_Ty>::type>'. I can compile it just fine with Wrapper<T> rather than Wrapper<std::decay_t<T>>, but I think I need to use the decayed type. Clang compiles it fine as is.

So what's the problem here? I'm a bit stuck.

答:
Possibly a bug in the VS compiler.

I can get it to compile with a slightly different form of the sfinae condition, using a default type instead of a default value:

```<code>#include <type_traits>
#include <new>

template<typename T>
class Wrapper {
    T thing;
public:
    Wrapper(T&& ) {
        // ...
    }
};

class Test {
    static const size_t PADDING_SIZE = 64;
public:
    template<
        typename T,
        class = std::enable_if_t<sizeof(Wrapper<std::decay_t<T>>) <= PADDING_SIZE>
    >
    Test(T&& thing) {
        new (padding) Wrapper<std::decay_t<T>>(std::forward<T>(thing));
    }

    char padding[PADDING_SIZE];
};

int main() {
    auto t = Test(0.0f);
}
</code>```

No real explanation of why this should work better, it's just the form I usually use.

Body:
So I'm trying to implement small object optimization in a project of mine, but I'm running into a strange compiler error. Here's some simplified code that reproduces the issue:

#include <type_traits>

template<typename T>
class Wrapper {
    T thing;
public:
    Wrapper(T&& thing) {
        // ...
    }
};

class Test {
    static const size_t PADDING_SIZE = 64;
public:
    template<
        typename T,
        std::enable_if_t<sizeof(Wrapper<std::decay_t<T>>) <= PADDING_SIZE, int> = 0
        // Error on this line ^
    >
    Test(T&& thing) {
        new (padding) Wrapper<std::decay_t<T>>(std::forward<T>(thing));
    }

    char padding[PADDING_SIZE];
};

int main() {
    auto t = Test(0.0f);
}

Basically, I need to take an arbitrary object, put it in a wrapper, and instantiate an instance of the wrapper in the padding, but I need to use one wrapper for types that can fit in the padding and a different one for types that are too large (one of the wrappers stores the object in place while the other allocates external space for it). And obviously I'd like to support perfect forwarding.

Unfortunately, VS2017 gives me the following compiler error: error C2027: use of undefined type 'Wrapper<decay<_Ty>::type>'. I can compile it just fine with Wrapper<T> rather than Wrapper<std::decay_t<T>>, but I think I need to use the decayed type. Clang compiles it fine as is.

So what's the problem here? I'm a bit stuck.

Body:
Possibly a bug in the VS compiler.

I can get it to compile with a slightly different form of the sfinae condition, using a default type instead of a default value:

#include <type_traits>
#include <new>

template<typename T>
class Wrapper {
    T thing;
public:
    Wrapper(T&& ) {
        // ...
    }
};

class Test {
    static const size_t PADDING_SIZE = 64;
public:
    template<
        typename T,
        class = std::enable_if_t<sizeof(Wrapper<std::decay_t<T>>) <= PADDING_SIZE>
    >
    Test(T&& thing) {
        new (padding) Wrapper<std::decay_t<T>>(std::forward<T>(thing));
    }

    char padding[PADDING_SIZE];
};

int main() {
    auto t = Test(0.0f);
}

No real explanation of why this should work better, it's just the form I usually use.


问:
the main method overlap in the java program
This is the full coding. Once we compile it |it throwing error that main method already defined before.How to settle this error. Guidance needed. Thank you.</p>

```<code>import java.util.Scanner;
import java.lang.*;
import java.math.*;

public class AdditiveCipher {
    public static void main(String[] args){
        String message, encryptedMessage = "", decryptedMessage = "", decryptMessage = "", encryptMessage = "";
        String text;
        int key;
        String keyy = "15";
        char ch;
        char cha;

        System.out.println("");
        System.out.println("-------------------Additive Cipher----------------------");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a message: ");
        message = sc.nextLine();

        System.out.println("Enter key: ");
        key = sc.nextInt();

        for(int i = 0; i < message.length(); ++i){
            ch = message.charAt(i);

            if(ch >= 'a' && ch <= 'z'){
                ch = (char)(ch + key);

                if(ch > 'z'){
                    ch = (char)(ch - 'z' + 'a' - 1);
                }

                encryptedMessage += ch;
            }
            else if(ch >= 'A' && ch <= 'Z'){
                ch = (char)(ch + key);

                if(ch > 'Z'){
                    ch = (char)(ch - 'Z' + 'A' - 1);
                }

                encryptedMessage += ch;
            }
            else {
                encryptedMessage += ch;
            }
        }

        System.out.println("Encrypted Message using additive cipher = " + encryptedMessage);

//Additive decrypted codes

            Scanner sca = new Scanner(System.in);

            System.out.println("Enter a encryted message: ");
            text = sca.nextLine();

            for(int i = 0; i < text.length(); ++i){
                ch = text.charAt(i);

                if(ch >= 'a' && ch <= 'z'){
                    ch = (char)(ch - key);

                    if(ch < 'a'){
                        ch = (char)(ch + 'z' - 'a' + 1);
                    }

                    decryptedMessage += ch;
                }
                else if(ch >= 'A' && ch <= 'Z'){
                    ch = (char)(ch - key);

                    if(ch < 'A'){
                        ch = (char)(ch + 'Z' - 'A' + 1);
                    }

                    decryptedMessage += ch;
                }
                else {
                    decryptedMessage += ch;
                }
            }

            System.out.println("Decrypted Message using additive cipher = " + decryptedMessage);

    }

//Autokey encrypted codes

    private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static void main(String[] args){
        String keyy = "15";  //15 - P
        String textt = "HELLO";

    if(keyy.matches("[-+]?\\d*\\.?\\d+"))
         keyy = ""+alpha.charAt(Integer.parseInt(keyy));

        System.out.println("");
                System.out.println("-------------------Autokey Cipher----------------------");
                System.out.println("");

                String enc = AutoEncryption(textt,keyy);
                System.out.println("Enter a encryted message: " +textt);
                System.out.println("Encrypted Message using additive cipher = " + enc);

    }
        public static String AutoEncryption(String textt,String keyy){
        int len = textt.length();

             String subkey = keyy + textt;
             subkey = subkey.substring(0,subkey.length()-keyy.length());

                String sb = "";
                 for(int x=0;x<len;x++){
                         int get1 = alpha.indexOf(textt.charAt(x));
                         int get2 = alpha.indexOf(subkey.charAt(x));

                         int total = (get1 + get2)%26;

                         sb += alpha.charAt(total);
                }
            return sb;

        }

         public static String AutoDecryption(String text,String key){
              int len = text.length();

              String current = key;
              String sb ="";

              for(int x=0;x<len;x++){
                 int get1 = alpha.indexOf(text.charAt(x));
                 int get2 = alpha.indexOf(current.charAt(x));

                 int total = (get1 - get2)%26;
                 total = (total<0)? total + 26 : total;
                 sb += alpha.charAt(total);

                 current += alpha.charAt(total);
              }
              return sb;
           }

}
</code>```

答: JVM start executing java program from main() you could not defined more than one main() method in java error in 99 line please check code see this</p>

Body:
This is the full coding. Once we compile it |it throwing error that main method already defined before.How to settle this error. Guidance needed. Thank you.

import java.util.Scanner;
import java.lang.*;
import java.math.*;

public class AdditiveCipher {
    public static void main(String[] args){
        String message, encryptedMessage = "", decryptedMessage = "", decryptMessage = "", encryptMessage = "";
        String text;
        int key;
        String keyy = "15";
        char ch;
        char cha;

        System.out.println("");
        System.out.println("-------------------Additive Cipher----------------------");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a message: ");
        message = sc.nextLine();

        System.out.println("Enter key: ");
        key = sc.nextInt();

        for(int i = 0; i < message.length(); ++i){
            ch = message.charAt(i);

            if(ch >= 'a' && ch <= 'z'){
                ch = (char)(ch + key);

                if(ch > 'z'){
                    ch = (char)(ch - 'z' + 'a' - 1);
                }

                encryptedMessage += ch;
            }
            else if(ch >= 'A' && ch <= 'Z'){
                ch = (char)(ch + key);

                if(ch > 'Z'){
                    ch = (char)(ch - 'Z' + 'A' - 1);
                }

                encryptedMessage += ch;
            }
            else {
                encryptedMessage += ch;
            }
        }

        System.out.println("Encrypted Message using additive cipher = " + encryptedMessage);

//Additive decrypted codes

            Scanner sca = new Scanner(System.in);

            System.out.println("Enter a encryted message: ");
            text = sca.nextLine();

            for(int i = 0; i < text.length(); ++i){
                ch = text.charAt(i);

                if(ch >= 'a' && ch <= 'z'){
                    ch = (char)(ch - key);

                    if(ch < 'a'){
                        ch = (char)(ch + 'z' - 'a' + 1);
                    }

                    decryptedMessage += ch;
                }
                else if(ch >= 'A' && ch <= 'Z'){
                    ch = (char)(ch - key);

                    if(ch < 'A'){
                        ch = (char)(ch + 'Z' - 'A' + 1);
                    }

                    decryptedMessage += ch;
                }
                else {
                    decryptedMessage += ch;
                }
            }

            System.out.println("Decrypted Message using additive cipher = " + decryptedMessage);

    }

//Autokey encrypted codes

    private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static void main(String[] args){
        String keyy = "15";  //15 - P
        String textt = "HELLO";

    if(keyy.matches("[-+]?\\d*\\.?\\d+"))
         keyy = ""+alpha.charAt(Integer.parseInt(keyy));

        System.out.println("");
                System.out.println("-------------------Autokey Cipher----------------------");
                System.out.println("");

                String enc = AutoEncryption(textt,keyy);
                System.out.println("Enter a encryted message: " +textt);
                System.out.println("Encrypted Message using additive cipher = " + enc);

    }
        public static String AutoEncryption(String textt,String keyy){
        int len = textt.length();

             String subkey = keyy + textt;
             subkey = subkey.substring(0,subkey.length()-keyy.length());

                String sb = "";
                 for(int x=0;x<len;x++){
                         int get1 = alpha.indexOf(textt.charAt(x));
                         int get2 = alpha.indexOf(subkey.charAt(x));

                         int total = (get1 + get2)%26;

                         sb += alpha.charAt(total);
                }
            return sb;

        }

         public static String AutoDecryption(String text,String key){
              int len = text.length();

              String current = key;
              String sb ="";

              for(int x=0;x<len;x++){
                 int get1 = alpha.indexOf(text.charAt(x));
                 int get2 = alpha.indexOf(current.charAt(x));

                 int total = (get1 - get2)%26;
                 total = (total<0)? total + 26 : total;
                 sb += alpha.charAt(total);

                 current += alpha.charAt(total);
              }
              return sb;
           }

}


问:
Interpolate validation-specific parameters in bean validation message
I have a custom bean validator which checks if a given field on an entity is unique for some conditions. If the validation fails, the message should include a field (e.g. the ID) of the already existing entity. So for example the message should be:

```<code>"Product 42 already has such a value defined, choose a unique value."
</code>```

Is this possible using bean validation?

AFAICS, the message format may include parameters, such as:

```<code>"Length must be between {min} and {max}."
</code>```

But this can only reference the "static" attributes of the validation annotation, in this case:

```<code>@Size(min=1, max=16)
private String name;
</code>```

In my case, the value is only known within isValid of my custom validator.

答:
You are right!, And for what you want!, you can build constraint violation message inside the isValid() method. For this the constraints Annotation should be specific for particular class on which it has been applied and it should be a class level validation constraints. Inside isValid before returning false on failure of validation you can create message consisting value of class instance. For example:

```<code>@check class Test{ int id; @validations...on fields}.

public boolean isValid(Test value, ConstraintValidatorContext context)
{
// your check logic
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("It should be different for(custom message) .."+ value.id).addConstraintViolation();
return false; // based on constraint filure.

}
</code>```

But i think you want to do this with Field level annotations! I don't have idea about that looking forward to your results.

ContentLicense: CC BY-SA 2.5

Body:
I have a custom bean validator which checks if a given field on an entity is unique for some conditions. If the validation fails, the message should include a field (e.g. the ID) of the already existing entity. So for example the message should be:

"Product 42 already has such a value defined, choose a unique value."

Is this possible using bean validation?

AFAICS, the message format may include parameters, such as:

"Length must be between {min} and {max}."

But this can only reference the "static" attributes of the validation annotation, in this case:

@Size(min=1, max=16)
private String name;

In my case, the value is only known within isValid of my custom validator.

Body:
You are right!, And for what you want!, you can build constraint violation message inside the isValid() method. For this the constraints Annotation should be specific for particular class on which it has been applied and it should be a class level validation constraints. Inside isValid before returning false on failure of validation you can create message consisting value of class instance. For example:

@check class Test{ int id; @validations...on fields}.

public boolean isValid(Test value, ConstraintValidatorContext context)
{
// your check logic
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("It should be different for(custom message) .."+ value.id).addConstraintViolation();
return false; // based on constraint filure.

}

But i think you want to do this with Field level annotations! I don't have idea about that looking forward to your results.


问:
Make a button visible after a PHP script has been executed
Hi all I have a requirement to make an add items button visible once the user has logged in im trying to test this with the below test code but am not sure of the best way to make a button visible after a php call any help would be appreciated.

passwordchecker.php

```<code><?php
        $message = "access granted, you can now add items";
        $message1 = "access denied";
    $user = $_POST['username'];
        $pass = $_POST['password'];
        if ($user == "admin" && $pass == "admin")
        {
        echo "<script type='text/javascript'>
          alert('$message');
          </script>";
        die();
        }
        else
        {
         echo "<script type='text/javascript'>
          alert('$message1');
          </script>";
              die();
        }
?>
</code>```

button we are trying to display

```<code><a href="#AddItems" class="btn btn-default btn-lg history" style="visibility:hidden" id="additems">Add item</a>
</code>```

Any help would be appreciated usually I would use Jquery to show and hide buttons but i'm not sure if this is possible in the current situation or if it is the best way to handle it.

thanks in advance!

答:
Just add it in your PHP like this (if the user exists echo the button else dont.)</p>

```<code><?php
    $message = "access granted, you can now add items";
    $message1 = "access denied";
    $user = $_POST['username'];
    $pass = $_POST['password'];
    if ($user == "admin" && $pass == "admin")
    {
    echo "<script type='text/javascript'>
      alert('$message');
      </script>'
      <a href=\"#AddItems\" class=\"btn btn-default btn-lg history\" style=\"visibility:hidden\" id=\"additems\">Add item</a>";
    die();
    }
    else
    {
     echo "<script type='text/javascript'>
      alert('$message1');
      </script>";
          die();
    }
?>
</code>```

Body:
Hi all I have a requirement to make an add items button visible once the user has logged in im trying to test this with the below test code but am not sure of the best way to make a button visible after a php call any help would be appreciated.

passwordchecker.php

<?php
        $message = "access granted, you can now add items";
        $message1 = "access denied";
    $user = $_POST['username'];
        $pass = $_POST['password'];
        if ($user == "admin" && $pass == "admin")
        {
        echo "";
        die();
        }
        else
        {
         echo "";
              die();
        }
?>

button we are trying to display

Add item

Any help would be appreciated usually I would use Jquery to show and hide buttons but i'm not sure if this is possible in the current situation or if it is the best way to handle it.

thanks in advance!

Body:
Just add it in your PHP like this (if the user exists echo the button else dont.)

<?php
    $message = "access granted, you can now add items";
    $message1 = "access denied";
    $user = $_POST['username'];
    $pass = $_POST['password'];
    if ($user == "admin" && $pass == "admin")
    {
    echo "<script type='text/javascript'>
      alert('$message');
      </script>'
      <a href=\"#AddItems\" class=\"btn btn-default btn-lg history\" style=\"visibility:hidden\" id=\"additems\">Add item</a>";
    die();
    }
    else
    {
     echo "<script type='text/javascript'>
      alert('$message1');
      </script>";
          die();
    }
?>


问:
text to decimal C
Manual conversion.

For example, input = axe, why the dec of 'a' (97) always in endless loop?

Can't move to 'x' dec and 'e'?

```<code>//project text to ASCII Dec
#include <stdio.h>

main(){
    char i=0, data, a;

    printf("Enter data : ");
    scanf("%s", &data); //or %c

    while(data != i){ /* can't out from this loop I mean to the next letter of word */
      a = data;
      printf("%d", data); // or printf("%d", a);
      if(data != 0){
        printf("-");
      }
    }
}
</code>```

答:
You've declared data as type char, meaning it can only hold a single character value ('A'', '1', '0', '\n', etc. ).

If you want to be able to store a string to data (such as "axe" or "foo" or "Supercalifragilisticexpialidocious"), then you will need to declare data as an array of char, and the array size must be at least one longer than the length of the longest string you intend to store:

```<code>#define STRING_LENGTH 20 // store strings *up to* 20 characters long
...
char data[STRING_LENGTH + 1]; // +1 for the 0 terminator that marks
                              // the end of the string
</code>```

As for the endless loop, 'a' (97) is never equal to i (0), and you never update the value of either entity in the loop.  You have to update one or the other each time through the loop.  Here's what I think you're going for:

```<code>if ( fgets( data, sizeof data, stdin ) ) // safer than using scanf
{
  for ( size_t i = 0; data[i] != 0; i++ )
  {
    printf( "%d ", data[i] ); // print out character encoding value
  }
}
</code>```

This code takes a string input by the user and prints the encoding value of each character (ASCII, EBCDIC, UTF-8, whatever) as an integer.

Title: text to decimal C

Body:
Manual conversion.

For example, input = axe, why the dec of 'a' (97) always in endless loop?

Can't move to 'x' dec and 'e'?

//project text to ASCII Dec
#include <stdio.h>

main(){
    char i=0, data, a;

    printf("Enter data : ");
    scanf("%s", &data); //or %c

    while(data != i){ /* can't out from this loop I mean to the next letter of word */
      a = data;
      printf("%d", data); // or printf("%d", a);
      if(data != 0){
        printf("-");
      }
    }
}

Body:
You've declared data as type char, meaning it can only hold a single character value ('A'', '1', '0', '\n', etc. ).

If you want to be able to store a string to data (such as "axe" or "foo" or "Supercalifragilisticexpialidocious"), then you will need to declare data as an array of char, and the array size must be at least one longer than the length of the longest string you intend to store:

#define STRING_LENGTH 20 // store strings *up to* 20 characters long
...
char data[STRING_LENGTH + 1]; // +1 for the 0 terminator that marks
                              // the end of the string

As for the endless loop, 'a' (97) is never equal to i (0), and you never update the value of either entity in the loop.  You have to update one or the other each time through the loop.  Here's what I think you're going for:

if ( fgets( data, sizeof data, stdin ) ) // safer than using scanf
{
  for ( size_t i = 0; data[i] != 0; i++ )
  {
    printf( "%d ", data[i] ); // print out character encoding value
  }
}

This code takes a string input by the user and prints the encoding value of each character (ASCII, EBCDIC, UTF-8, whatever) as an integer.


问:
PhotoEditor SDK: java.lang.OutOfMemoryError
6 hours invested at this point into this SDK. Followed the ionic guide carefully at: https://github.com/imgly/pesdk-ionic-demo

after everything is in place I enter cordova build android. It then hangs for a while at :mergeDebugResources leading to an error soon after

```<code>java.lang.OutOfMemoryError: Java heap space
:mergeDebugResources FAILED
</code>```

I've tried setting my environment settings (windows 10) to -Xmx512m and even -Xmx2048m without any difference.

Uninstall Java 32bit and reinstall 64 bit

The moment I remove the pesdk-cordova-demo plugin, its business as usual. Add it back and it hangs at the same point again.

I have 12GB of ram on my computer. java version "1.8.0_152". Cordova 7.1.0. Ionic 3.19.0

running Cordova android 5.1.1

Any ideas?

答:
Finally found a solution! Environment variable did the trick

```<code>GRADLE_OPTS=-Xmx2048m
</code>```

Only after a restart did it take effect.

Body:
6 hours invested at this point into this SDK. Followed the ionic guide carefully at: https://github.com/imgly/pesdk-ionic-demo

after everything is in place I enter cordova build android. It then hangs for a while at :mergeDebugResources leading to an error soon after

java.lang.OutOfMemoryError: Java heap space
:mergeDebugResources FAILED

I've tried setting my environment settings (windows 10) to -Xmx512m and even -Xmx2048m without any difference.

Uninstall Java 32bit and reinstall 64 bit

The moment I remove the pesdk-cordova-demo plugin, its business as usual. Add it back and it hangs at the same point again.

I have 12GB of ram on my computer. java version "1.8.0_152". Cordova 7.1.0. Ionic 3.19.0

running Cordova android 5.1.1

Any ideas?

Body:
Finally found a solution! Environment variable did the trick

GRADLE_OPTS=-Xmx2048m

Only after a restart did it take effect.


问:
Do internal artifacts belong in a repository?
Our team is struggling with issues around the idea of a library repository. I have used Maven, and I am familiar with Ivy.  We have little doubt that for third-party jars, a common repository that is integrated into the build system has tremendous advantage.

The struggle is around how to handle artifacts that are strictly internal.  We have many artifacts that use a handful of different build tools, including Maven, but essentially they are all part of one one product (one team responsible for all of it).  Unfortunately, we are not currently producing a single artifact per project, but we're headed in that direction.  Developers do and will check out all the projects.

We see two options:

1) Treat all artifacts even internal ones as any third-party jar.  Each jar gets built and published to the repository, and other artifact projects refer to the repository for all projects.

2) Each project refers to other "sibling" projects directly.  There is a "master project" that triggers the builds for all other projects with an appropriate dependency order.  In the IDE (eclipse), each projects refers to it's dependent project (source) directly. The build tools look into the sibling project referencing a .jar.

It's very clear that the open-source world is moving towards the repository model.  But it seems to us that their needs may be different.  Most such projects are very independent and we strongly suspect users are seldom making changes across projects.  There are frequent upgrades that are now easier for clients to track and be aware of.

However, it does add a burden in that you have to separately publish changes.  In our case, we just want to commit to source control (something we do 20-50 times a day).

I'm aware that Maven might solve all these problems, but the team is NOT going to convert everything to Maven.  Other than maven, what do you recommend (and why)?

答:
If a project produces multiple jar files (and many do) I would carefully consider (case by case) whether or not each jar will ever be reused by other projects.

If yes, that jar should go into the repository as a library, because it facilitates reuse by allowing you to specify it as a dependency.

If no, it would be a so-called "multi-project" in which the whole project is built of the parts. The individual jars probably do not need to be stored individually in the repo. Just the final completed artifact.

Gradle is definitely a candidate for you: It can use Ant tasks and call Ant scripts, understands Maven pom files, and handles multi-projects well. Maven can do much of this as well, and if you have lots of patience, Ant+Ivy can.


问:
Fast element access for multi-dimensional representation of contiguous array
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

```<code>template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};
</code>```

So if I initialize this class and attempted to access an element, it would look something like this:

```<code>my_array = MultiArray<4>();
element = my_array(2,5,4,1);
</code>```

How might I go about doing this using templates? Is this even possible?

答:
I've used this pattern several times when creating a class templates of a matrix class with variable dimensions.

Matrix.h

```<code>#ifndef MATRIX_H

template<typename Type, size_t... Dims>
class Matrix {
public:
    static const size_t numDims_ = sizeof...(Dims);

private:
    size_t numElements_;

    std::vector<Type> elements_;
    std::vector<size_t> strides_; // Technically this vector contains the size of each dimension... (its shape)
    // actual strides would be the width in memory of each element to that dimension of the container.
    // A better name for this container would be dimensionSizes_ or shape_

public:
    Matrix() noexcept;

    template<typename... Arg>
    Matrix( Arg&&... as  ) noexcept;

    const Type& operator[]( size_t idx ) const;

    size_t numElements() const {
        return elements_.size();
    }

    const std::vector<size_t>& strides() const {
        return strides_;
    }

    const std::vector<Type>& elements() const {
        return elements_;
    }

}; // matrix

#include "Matrix.inl"

#endif // MATRIX_H
</code>```

Matrix.inl

```<code>template<typename Type, size_t... Dims>
Matrix<Type, Dims...>::Matrix() noexcept :
strides_( { Dims... } ) {
    using std::begin;
    using std::end;
    auto mult = std::accumulate( begin( strides_ ), end( strides_ ), 1, std::multiplies<>() );
    numElements_ = mult;
    elements_.resize( numElements_ );
} // Matrix

template<typename Type, size_t... Dims>
template<typename... Arg>
Matrix<Type, Dims...>::Matrix( Arg&&... as ) noexcept   :
elements_( { as... } ),
strides_( { Dims... } ){
    numElements_ = elements_.size();
} // Matrix

template<typename T, size_t... d>
const T& Matrix<T,d...>::operator[]( size_t idx ) const {
    return elements_[idx];
} // Operator[]
</code>```

Matrix.cpp

```<code>#include "Matrix.h"
#include <vector>
#include <numeric>
#include <functional>
#include <algorithm>
</code>```

main.cpp

```<code>#include <vector>
#include <iostream>
#include "matrix.h"

int main() {

    Matrix<int, 3, 3> mat3x3( 1, 2, 3, 4, 5, 6, 7, 8, 9 );

    for ( size_t idx = 0; idx < mat3x3.numElements(); idx++ ) {
        std::cout << mat3x3.elements()[idx] << " ";
    }

    std::cout << "\n\nnow using array index operator\n\n";

    for ( size_t idx = 0; idx < mat3x3.numElements(); idx++ ) {
        std::cout << mat3x3[idx] << " ";
    }

    std::cout << "\n\ncheck the strides\n\n";
    for ( size_t idx = 0; idx < mat3x3.numDims_; idx++ ) {
        std::cout << mat3x3.strides()[idx] << " ";
    }
    std::cout << "\n\n";

    std::cout << "=================================\n\n";

    Matrix<float, 5, 2, 9, 7> mf5x2x9x7;
    // Check Strides
    // Num Elements
    // Total Size
    std::cout << "The total number of dimensions are: " << mf5x2x9x7.numDims_ << "\n";
    std::cout << "The total number of elements are: " << mf5x2x9x7.numElements() << "\n";
    std::cout << "These are the strides: \n";
    for ( size_t n = 0; n < mf5x2x9x7.numDims_; n++ ) {
        std::cout << mf5x2x9x7.strides()[n] << " ";
    }
    std::cout << "\n";

    std::cout << "The elements are: ";
    for ( size_t n = 0; n < mf5x2x9x7.numElements(); n++ ) {
        std::cout << mf5x2x9x7[n] << " ";
    }
    std::cout << "\n";

    std::cout << "\nPress any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;

} // main
</code>```

This is a simple variable multidimensional matrix class of the Same Type <T>

You can create a matrix of floats, ints, chars etc of varying sizes such as a 2x2, 2x3, 5x3x7, 4x9x8x12x2x19. This is a very simple but versatile class.

It is using std::vector<> so the search time is linear. The larger the multi - dimensional matrix grows in dimensions the larger the internal container will grow depending on the size of each dimension; this can "explode" fairly quick if each individual dimensions are of a large dimensional size for example: a 9x9x9 is only a 3 dimensional volumetric matrix that has many more elements than a 2x2x2x2x2 which is a 5 dimensional volumetric matrix. The first matrix has 729 elements where the second matrix has only 32 elements.

I did not include a default constructor, copy constructor, move constructor, nor any overloaded constructors that would accept either a std::container<T> or another Matrix<T,...>. This can be done as an exercise for the OP.

I also did not include any simple functions that would give the size of total elements from the main container, nor the number of total dimensions which would be the size of the strides container size. The OP should be able to implement these very simply.

As for the strides and for indexing with multiple dimensional coordinates the OP would need to use the stride values to compute the appropriate indexes again I leave this as the main exercise.

EDIT - I went ahead and added a default constructor, moved some members to private section of the class, and added a few access functions. I did this because I just wanted to demonstrate in the main function the power of this class even when creating an empty container of its type.

Even more you can take user Yakk's answer with his "stride & slice" algorithm and should easily be able to plug it right into this class giving you the full functionality of what you are looking for.

Body:
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};

So if I initialize this class and attempted to access an element, it would look something like this:

my_array = MultiArray<4>();
element = my_array(2,5,4,1);

How might I go about doing this using templates? Is this even possible?

Body:
I've used this pattern several times when creating a class templates of a matrix class with variable dimensions.

Matrix.h

#ifndef MATRIX_H

template<typename Type, size_t... Dims>
class Matrix {
public:
    static const size_t numDims_ = sizeof...(Dims);

private:
    size_t numElements_;

    std::vector<Type> elements_;
    std::vector<size_t> strides_; // Technically this vector contains the size of each dimension... (its shape)
    // actual strides would be the width in memory of each element to that dimension of the container.
    // A better name for this container would be dimensionSizes_ or shape_

public:
    Matrix() noexcept;

    template<typename... Arg>
    Matrix( Arg&&... as  ) noexcept;

    const Type& operator[]( size_t idx ) const;

    size_t numElements() const {
        return elements_.size();
    }

    const std::vector<size_t>& strides() const {
        return strides_;
    }

    const std::vector<Type>& elements() const {
        return elements_;
    }

}; // matrix

#include "Matrix.inl"

#endif // MATRIX_H

Matrix.inl

template<typename Type, size_t... Dims>
Matrix<Type, Dims...>::Matrix() noexcept :
strides_( { Dims... } ) {
    using std::begin;
    using std::end;
    auto mult = std::accumulate( begin( strides_ ), end( strides_ ), 1, std::multiplies<>() );
    numElements_ = mult;
    elements_.resize( numElements_ );
} // Matrix

template<typename Type, size_t... Dims>
template<typename... Arg>
Matrix<Type, Dims...>::Matrix( Arg&&... as ) noexcept   :
elements_( { as... } ),
strides_( { Dims... } ){
    numElements_ = elements_.size();
} // Matrix

template<typename T, size_t... d>
const T& Matrix<T,d...>::operator[]( size_t idx ) const {
    return elements_[idx];
} // Operator[]

Matrix.cpp

#include "Matrix.h"
#include <vector>
#include <numeric>
#include <functional>
#include <algorithm>

main.cpp

#include <vector>
#include <iostream>
#include "matrix.h"

int main() {

    Matrix<int, 3, 3> mat3x3( 1, 2, 3, 4, 5, 6, 7, 8, 9 );

    for ( size_t idx = 0; idx < mat3x3.numElements(); idx++ ) {
        std::cout << mat3x3.elements()[idx] << " ";
    }

    std::cout << "\n\nnow using array index operator\n\n";

    for ( size_t idx = 0; idx < mat3x3.numElements(); idx++ ) {
        std::cout << mat3x3[idx] << " ";
    }

    std::cout << "\n\ncheck the strides\n\n";
    for ( size_t idx = 0; idx < mat3x3.numDims_; idx++ ) {
        std::cout << mat3x3.strides()[idx] << " ";
    }
    std::cout << "\n\n";

    std::cout << "=================================\n\n";

    Matrix<float, 5, 2, 9, 7> mf5x2x9x7;
    // Check Strides
    // Num Elements
    // Total Size
    std::cout << "The total number of dimensions are: " << mf5x2x9x7.numDims_ << "\n";
    std::cout << "The total number of elements are: " << mf5x2x9x7.numElements() << "\n";
    std::cout << "These are the strides: \n";
    for ( size_t n = 0; n < mf5x2x9x7.numDims_; n++ ) {
        std::cout << mf5x2x9x7.strides()[n] << " ";
    }
    std::cout << "\n";

    std::cout << "The elements are: ";
    for ( size_t n = 0; n < mf5x2x9x7.numElements(); n++ ) {
        std::cout << mf5x2x9x7[n] << " ";
    }
    std::cout << "\n";

    std::cout << "\nPress any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;

} // main

This is a simple variable multidimensional matrix class of the Same Type <T>

You can create a matrix of floats, ints, chars etc of varying sizes such as a 2x2, 2x3, 5x3x7, 4x9x8x12x2x19. This is a very simple but versatile class.

It is using std::vector<> so the search time is linear. The larger the multi - dimensional matrix grows in dimensions the larger the internal container will grow depending on the size of each dimension; this can "explode" fairly quick if each individual dimensions are of a large dimensional size for example: a 9x9x9 is only a 3 dimensional volumetric matrix that has many more elements than a 2x2x2x2x2 which is a 5 dimensional volumetric matrix. The first matrix has 729 elements where the second matrix has only 32 elements.

I did not include a default constructor, copy constructor, move constructor, nor any overloaded constructors that would accept either a std::container<T> or another Matrix<T,...>. This can be done as an exercise for the OP.

I also did not include any simple functions that would give the size of total elements from the main container, nor the number of total dimensions which would be the size of the strides container size. The OP should be able to implement these very simply.

As for the strides and for indexing with multiple dimensional coordinates the OP would need to use the stride values to compute the appropriate indexes again I leave this as the main exercise.

EDIT - I went ahead and added a default constructor, moved some members to private section of the class, and added a few access functions. I did this because I just wanted to demonstrate in the main function the power of this class even when creating an empty container of its type.

Even more you can take user Yakk's answer with his "stride & slice" algorithm and should easily be able to plug it right into this class giving you the full functionality of what you are looking for.


问:
Node - console.log + return values
I'm just getting started in programming and am using VSC and installed Node and am using it to run my files. My console.logs works, but I can't get return values when I invoke functions. What am I doing wrong?

答:
Node.js is asynchronous.  99% of all functions you write are going to be "non-blocking".  If you don't quite understand what that is, I highly suggest you google up on the node.js event loop, and what it means to be "asynchronous".

Once you figure that out, start using the async/await syntax, or "promise" syntax.

Edit:
I see you posted more information.  Based on what you're doing, it actually has nothing to do with being asynchronous.

The problem is that you're just returning a string value of hihihihihi... and that's it.  You don't print it out anywhere.  You need to wrap your call to function a() inside console.log().  So like: console.log(a());

Title: Node - console.log + return values


问:
dask performance apply along axis
I am trying to compute the linear trend over time on a large high resolution ocean model dataset using dask.

I have followed this example (Applying a function along an axis of a dask array) and found the syntax of apply_along_axis easier.

I am currently using dask.array.apply_along_axis to wrap a numpy function on 1 dimensional arrays and then package the resulting dask array into an xarray Dataarray. Using top -u <username> suggest that the computation is not executed in parallel (~100% cpu use).

Should I expect a better performance from map_blocks? Or are there any suggestions on how to improve the performance of apply_along_axis?
Any tips are highly appreciated.

```<code>import numpy as np
from scipy import optimize
import xarray as xr
import dask.array as dsa

def _lin_trend(y):
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)

def linear_trend(da, dim, name='parameter'):
    da = da.copy()
    axis_num = da.get_axis_num(dim)

    dims = list(da.dims)
    dims[axis_num] = name
    coords = da.rename({dim:name}).coords
    coords[name] = ['slope', 'intercept']

    dsk = da.data
    dsk_trend = dsa.apply_along_axis(_lin_trend,0,dsk)
    out = xr.DataArray(dsk_trend, dims=dims, coords=coords)
    return out
</code>```

答:
I think that ultimately the performance is limited by the filesystem I am working on. To answer your question though, my dataset has the following shape:

```<code><xarray.Dataset>
Dimensions:         (st_edges_ocean: 51, st_ocean: 50, time: 101, xt_ocean: 3600, yt_ocean: 2700)
Coordinates:
  * xt_ocean        (xt_ocean) float64 -279.9 -279.8 -279.7 -279.6 -279.5 ...
  * yt_ocean        (yt_ocean) float64 -81.11 -81.07 -81.02 -80.98 -80.94 ...
  * st_ocean        (st_ocean) float64 5.034 15.1 25.22 35.36 45.58 55.85 ...
  * st_edges_ocean  (st_edges_ocean) float64 0.0 10.07 20.16 30.29 40.47 ...
  * time            (time) float64 3.634e+04 3.671e+04 3.707e+04 3.744e+04 ...
</code>```

So it is rather big and needs a long time to read from disk. I have rechunked it so that the time dimension is a single chunk

```<code>dask.array<concatenate, shape=(101, 50, 2700, 3600), dtype=float64,
chunksize=(101, 1, 270, 3600)>
</code>```

That did not make a big difference for the performance (it still takes about 20 hrs for the function to finish (that is including reading and writing to disk). I am currently only chunking in time, e.g.

```<code>dask.array<concatenate, shape=(101, 50, 2700, 3600), dtype=float64,
chunksize=(1, 1, 2700, 3600)>
</code>```

I was interested in the relative performance of both methods and ran a test on my laptop.

```<code>import xarray as xr
import numpy as np
from scipy import stats
import dask.array as dsa

slope = 10
intercept = 5
t = np.arange(250)
x = np.arange(10)
y = np.arange(500)
z = np.arange(200)
chunks = {'x':10, 'y':10}

noise = np.random.random([len(x), len(y), len(z), len(t)])
ones = np.ones_like(noise)
time = ones*t
data = (time*slope+intercept)+noise
da = xr.DataArray(data, dims=['x', 'y', 'z', 't'],
                 coords={'x':('x', x),
                        'y':('y', y),
                        'z':('z', z),
                        't':('t', t)})
da = da.chunk(chunks)
da
</code>```

I now defined a set of private functions (using both linregress and polyfit to calculate the slope of a timeseries), as well as different implementations using dask.apply_along and xarray.apply_ufunc.

```<code>def _calc_slope_poly(y):
    """ufunc to be used by linear_trend"""
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)[0]

def _calc_slope(y):
    '''returns the slop from a linear regression fit of x and y'''
    x = np.arange(len(y))
    return stats.linregress(x, y)[0]

def linear_trend_along(da, dim):
    """computes linear trend over 'dim' from the da.
       Slope and intercept of the least square fit are added to a new
       DataArray which has the dimension 'name' instead of 'dim', containing
       slope and intercept for each gridpoint
    """
    da = da.copy()
    axis_num = da.get_axis_num(dim)
    trend = dsa.apply_along_axis(_calc_slope, axis_num, da.data)
    return trend

def linear_trend_ufunc(obj, dim):
    trend = xr.apply_ufunc(_calc_slope, obj,
                           vectorize=True,
                           input_core_dims=[[dim]],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

def linear_trend_ufunc_poly(obj, dim):
    trend = xr.apply_ufunc(_calc_slope_poly, obj,
                           vectorize=True,
                           input_core_dims=[[dim]],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

def linear_trend_along_poly(da, dim):
    """computes linear trend over 'dim' from the da.
       Slope and intercept of the least square fit are added to a new
       DataArray which has the dimension 'name' instead of 'dim', containing
       slope and intercept for each gridpoint
    """
    da = da.copy()
    axis_num = da.get_axis_num(dim)
    trend = dsa.apply_along_axis(_calc_slope_poly, axis_num, da.data)
    return trend

trend_ufunc = linear_trend_ufunc(da, 't')
trend_ufunc_poly = linear_trend_ufunc_poly(da, 't')
trend_along = linear_trend_along(da, 't')
trend_along_poly = linear_trend_along_poly(da, 't')
</code>```

Timing the computation seems to indicate that the apply_along method might be marginally faster. Using polyfit instead of linregress seems to have quite a big influences though. I am not sure why this is much faster but perhaps this is of interest to you.

```<code>%%timeit
print(trend_ufunc[1,1,1].data.compute())
</code>```

4.89 s ± 180 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

```<code>%%timeit
trend_ufunc_poly[1,1,1].compute()
</code>```

2.74 s ± 182 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

```<code>%%timeit
trend_along[1,1,1].compute()
</code>```

4.58 s ± 193 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

```<code>%%timeit
trend_along_poly[1,1,1].compute()
</code>```

2.64 s ± 65 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Title: dask performance apply along axis

Body:
I am trying to compute the linear trend over time on a large high resolution ocean model dataset using dask.

I have followed this example (Applying a function along an axis of a dask array) and found the syntax of apply_along_axis easier.

I am currently using dask.array.apply_along_axis to wrap a numpy function on 1 dimensional arrays and then package the resulting dask array into an xarray Dataarray. Using top -u <username> suggest that the computation is not executed in parallel (~100% cpu use).

Should I expect a better performance from map_blocks? Or are there any suggestions on how to improve the performance of apply_along_axis?
Any tips are highly appreciated.

import numpy as np
from scipy import optimize
import xarray as xr
import dask.array as dsa

def _lin_trend(y):
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)

def linear_trend(da, dim, name='parameter'):
    da = da.copy()
    axis_num = da.get_axis_num(dim)

    dims = list(da.dims)
    dims[axis_num] = name
    coords = da.rename({dim:name}).coords
    coords[name] = ['slope', 'intercept']

    dsk = da.data
    dsk_trend = dsa.apply_along_axis(_lin_trend,0,dsk)
    out = xr.DataArray(dsk_trend, dims=dims, coords=coords)
    return out

Body:
I think that ultimately the performance is limited by the filesystem I am working on. To answer your question though, my dataset has the following shape:

<xarray.Dataset>
Dimensions:         (st_edges_ocean: 51, st_ocean: 50, time: 101, xt_ocean: 3600, yt_ocean: 2700)
Coordinates:
  * xt_ocean        (xt_ocean) float64 -279.9 -279.8 -279.7 -279.6 -279.5 ...
  * yt_ocean        (yt_ocean) float64 -81.11 -81.07 -81.02 -80.98 -80.94 ...
  * st_ocean        (st_ocean) float64 5.034 15.1 25.22 35.36 45.58 55.85 ...
  * st_edges_ocean  (st_edges_ocean) float64 0.0 10.07 20.16 30.29 40.47 ...
  * time            (time) float64 3.634e+04 3.671e+04 3.707e+04 3.744e+04 ...

So it is rather big and needs a long time to read from disk. I have rechunked it so that the time dimension is a single chunk

dask.array<concatenate, shape=(101, 50, 2700, 3600), dtype=float64,
chunksize=(101, 1, 270, 3600)>

That did not make a big difference for the performance (it still takes about 20 hrs for the function to finish (that is including reading and writing to disk). I am currently only chunking in time, e.g.

dask.array<concatenate, shape=(101, 50, 2700, 3600), dtype=float64,
chunksize=(1, 1, 2700, 3600)>

I was interested in the relative performance of both methods and ran a test on my laptop.

import xarray as xr
import numpy as np
from scipy import stats
import dask.array as dsa

slope = 10
intercept = 5
t = np.arange(250)
x = np.arange(10)
y = np.arange(500)
z = np.arange(200)
chunks = {'x':10, 'y':10}

noise = np.random.random([len(x), len(y), len(z), len(t)])
ones = np.ones_like(noise)
time = ones*t
data = (time*slope+intercept)+noise
da = xr.DataArray(data, dims=['x', 'y', 'z', 't'],
                 coords={'x':('x', x),
                        'y':('y', y),
                        'z':('z', z),
                        't':('t', t)})
da = da.chunk(chunks)
da

I now defined a set of private functions (using both linregress and polyfit to calculate the slope of a timeseries), as well as different implementations using dask.apply_along and xarray.apply_ufunc.

def _calc_slope_poly(y):
    """ufunc to be used by linear_trend"""
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)[0]

def _calc_slope(y):
    '''returns the slop from a linear regression fit of x and y'''
    x = np.arange(len(y))
    return stats.linregress(x, y)[0]

def linear_trend_along(da, dim):
    """computes linear trend over 'dim' from the da.
       Slope and intercept of the least square fit are added to a new
       DataArray which has the dimension 'name' instead of 'dim', containing
       slope and intercept for each gridpoint
    """
    da = da.copy()
    axis_num = da.get_axis_num(dim)
    trend = dsa.apply_along_axis(_calc_slope, axis_num, da.data)
    return trend

def linear_trend_ufunc(obj, dim):
    trend = xr.apply_ufunc(_calc_slope, obj,
                           vectorize=True,
                           input_core_dims=[[dim]],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

def linear_trend_ufunc_poly(obj, dim):
    trend = xr.apply_ufunc(_calc_slope_poly, obj,
                           vectorize=True,
                           input_core_dims=[[dim]],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

def linear_trend_along_poly(da, dim):
    """computes linear trend over 'dim' from the da.
       Slope and intercept of the least square fit are added to a new
       DataArray which has the dimension 'name' instead of 'dim', containing
       slope and intercept for each gridpoint
    """
    da = da.copy()
    axis_num = da.get_axis_num(dim)
    trend = dsa.apply_along_axis(_calc_slope_poly, axis_num, da.data)
    return trend

trend_ufunc = linear_trend_ufunc(da, 't')
trend_ufunc_poly = linear_trend_ufunc_poly(da, 't')
trend_along = linear_trend_along(da, 't')
trend_along_poly = linear_trend_along_poly(da, 't')

Timing the computation seems to indicate that the apply_along method might be marginally faster. Using polyfit instead of linregress seems to have quite a big influences though. I am not sure why this is much faster but perhaps this is of interest to you.

%%timeit
print(trend_ufunc[1,1,1].data.compute())

4.89 s ± 180 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
trend_ufunc_poly[1,1,1].compute()

2.74 s ± 182 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
trend_along[1,1,1].compute()

4.58 s ± 193 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
trend_along_poly[1,1,1].compute()

2.64 s ± 65 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Why do "inline-block" elements in a "nowrap" div overflow?
The following code causes #headline to overflow #wrapper and I do not understand why this is happening.

HTML:

```<code><div id="wrapper">
    <div id="logo">
        <img src="/test.png">
    </div>
    <div id="headline">
        <h1>This headline overflows its wrapping div. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #</h1>
    </div>
</div>
</code>```

CSS:

```<code>#wrapper {
    background: #fea;
    white-space: nowrap;
    width: 50%;
}

#logo {
    display: inline-block;
    vertical-align: middle;
}

#logo img {
       width: 6em;
}

#headline {
     display: inline-block;
     vertical-align: middle;
     white-space: normal;
}
</code>```

Example code: http://jsfiddle.net/XjstZ/21/ or http://tinkerbin.com/XvSAEfrK

答:
This content wrap because of white-space: normal;.

The white-space CSS property determines how whitespace inside an element is handled. To make words break within themselves, use overflow-wrap, word-break, or hyphens instead.
Now there if you want to limit this with #wrapper than you can limit the overflow property for the div.If you using white-space: nowrap; for div this clear the overflow text and show the div in a single line (ROW).

```<code>#wrapper {
    background: #fea;
    width: 50%;
    overflow: hidden;
}

#logo {
    display: inline-block;
    vertical-align: middle;
}

#logo img {
       width: 6em;
}

#headline {
     display: inline-block;
     vertical-align: middle;

}
</code>```

Body:
The following code causes #headline to overflow #wrapper and I do not understand why this is happening.

HTML:

This headline overflows its wrapping div. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

CSS:

#wrapper {
    background: #fea;
    white-space: nowrap;
    width: 50%;
}

#logo {
    display: inline-block;
    vertical-align: middle;
}

#logo img {
       width: 6em;
}

#headline {
     display: inline-block;
     vertical-align: middle;
     white-space: normal;
}

Example code: http://jsfiddle.net/XjstZ/21/ or http://tinkerbin.com/XvSAEfrK

Body:
This content wrap because of white-space: normal;.

The white-space CSS property determines how whitespace inside an element is handled. To make words break within themselves, use overflow-wrap, word-break, or hyphens instead.
Now there if you want to limit this with #wrapper than you can limit the overflow property for the div.If you using white-space: nowrap; for div this clear the overflow text and show the div in a single line (ROW).

#wrapper {
    background: #fea;
    width: 50%;
    overflow: hidden;
}

#logo {
    display: inline-block;
    vertical-align: middle;
}

#logo img {
       width: 6em;
}

#headline {
     display: inline-block;
     vertical-align: middle;

}


问:
Validation failed for object='statutProduits'. Error count: 2
When i'm trying to submit my form i get this errors, well i need to create  an object "status_product"

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing
  this as a fallback.

Thu Dec 07 04:07:23 GMT+01:00 2017 There was an unexpected error
  (type=Bad Request, status=400). Validation failed for
  object='statutProduits'. Error count: 2

I am having trouble finding the two validation errors show on the error page. I am pretty lost at this point. Hopefully someone can help me out, its preventing me from making progress at the moment.

StatutProduits class:

```<code>package com.example.demo.entities;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 *
 * @author G557437
 */
@Entity
@Table(name = "STATUT_PRODUITS", catalog = "", schema = "PACKOUT")

public class StatutProduits implements Serializable {
    private static final long serialVersionUID = 1L;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "ID_STATUT_PRODUIT")
    private BigDecimal idStatutProduit;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "CODE")
    private String code;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "LIBELLE")
    private String libelle;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 10)
    @Column(name = "CREE_PAR")
    private String creePar;
    @Column(name = "DATE_CREATION")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreation;
    @Size(max = 10)
    @Column(name = "MAJ_PAR")
    private String majPar;
    @Column(name = "DATE_MAJ")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateMaj;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idStatutProduit")
    private List<Produits> produitsList;

    public StatutProduits() {
    }

    public StatutProduits(BigDecimal idStatutProduit) {
        this.idStatutProduit = idStatutProduit;
    }

    public StatutProduits(BigDecimal idStatutProduit, String code, String libelle, String creePar) {
        this.idStatutProduit = idStatutProduit;
        this.code = code;
        this.libelle = libelle;
        this.creePar = creePar;
    }

    public BigDecimal getIdStatutProduit() {
        return idStatutProduit;
    }

    public void setIdStatutProduit(BigDecimal idStatutProduit) {
        this.idStatutProduit = idStatutProduit;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getLibelle() {
        return libelle;
    }

    public void setLibelle(String libelle) {
        this.libelle = libelle;
    }

    public String getCreePar() {
        return creePar;
    }

    public void setCreePar(String creePar) {
        this.creePar = creePar;
    }

    public Date getDateCreation() {
        return dateCreation;
    }

    public void setDateCreation(Date dateCreation) {
        this.dateCreation = dateCreation;
    }

    public String getMajPar() {
        return majPar;
    }

    public void setMajPar(String majPar) {
        this.majPar = majPar;
    }

    public Date getDateMaj() {
        return dateMaj;
    }

    public void setDateMaj(Date dateMaj) {
        this.dateMaj = dateMaj;
    }

    public List<Produits> getProduitsList() {
        return produitsList;
    }

    public void setProduitsList(List<Produits> produitsList) {
        this.produitsList = produitsList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idStatutProduit != null ? idStatutProduit.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof StatutProduits)) {
            return false;
        }
        StatutProduits other = (StatutProduits) object;
        if ((this.idStatutProduit == null && other.idStatutProduit != null) || (this.idStatutProduit != null && !this.idStatutProduit.equals(other.idStatutProduit))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.sagemcom.tn.entities.StatutProduits[ idStatutProduit=" + idStatutProduit + " ]";
    }

}
</code>```

Controller Class:

```<code>package com.example.demo.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.demo.dao.StatutProduitsRepository;
import com.example.demo.entities.StatutProduits;

@Controller
public class StatutProduitsController {

    @Autowired
    StatutProduitsRepository statutproduitsrepository ;

    @RequestMapping(value="/form", method=RequestMethod.GET)
    public String formStatProduit( Model model) {
        model.addAttribute("statproduit",new StatutProduits());
        return "FormStatutProduit";
    }

    @RequestMapping(value="/save", method=RequestMethod.POST)
    public String save( Model model, StatutProduits statproduit) {
        statutproduitsrepository.save(statproduit);
        return "Confirmation";
    }
}
</code>```

thymleaf:

```<code><body>
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">Statut d'un produit</div>
            <div class="panel-body">
            <form th:action="@{save}"  method="post">
                <div class="form-group">

                    <label class="control-label">ID</label>
                    <input class="form-control" type="number" name="idStatutProduit"
                            th:value="${statproduit.idStatutProduit}"/>
                </div>
                <div class="form-group">

                    <label class="control-label">Code</label>
                    <input class="form-control" type="text" name="code"
                    th:value="${statproduit.code}"/>
                </div>
                <div class="form-group">

                    <label class="control-label">Cree par</label>
                    <input class="form-control" type="text" name="creePar"
                          th:value="${statproduit.creePar}"/>
                </div>
                <div class="form-group">

                    <label class="control-label">Date creation</label>
                    <input class="form-control" type="date"  name="dateCreation"
                    th:value="${statproduit.dateCreation}"/>
                </div>
                <div class="form-group">

                    <label class="control-label">Date maj</label>
                    <input class="form-control" type="date" name="dateMaj"
                    th:value="${statproduit.dateMaj}"/>
                </div>
                <div class="form-group">

                    <label class="control-label">Libelle</label>
                    <input class="form-control" type="text" name="libelle"
                    th:value="${statproduit.libelle}"/>
                </div>
                <div class="form-group">

                    <label class="control-label">Maj par</label>
                    <input class="form-control" type="text"  name="majPar"
                     th:value="${statproduit.majPar}"/>
                </div>
                <div>
                <button type="submit" class="btn btn-primary">Save</button>

                </div>
             </form>
            </div>
     </div>
</div>
</body>
</code>```

答:
In your case, you have added server-side validation but in your controller, you didn't check that conditions and blindly saving that object into your database. instead of doing like that check the conditions in the controller by using BindingResult

```<code> @RequestMapping(value="/save", method=RequestMethod.POST)
 public String save( Model model, @Validated StatutProduits statproduit BindingResult bindingResult) {
     if(bindingResult.hasErrors()){
         return "to same page to shows error fields";
     }
    statutproduitsrepository.save(statproduit);
    return "Confirmation";
 }
</code>```

Body:
When i'm trying to submit my form i get this errors, well i need to create  an object "status_product"

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing
  this as a fallback.

Thu Dec 07 04:07:23 GMT+01:00 2017 There was an unexpected error
  (type=Bad Request, status=400). Validation failed for
  object='statutProduits'. Error count: 2

I am having trouble finding the two validation errors show on the error page. I am pretty lost at this point. Hopefully someone can help me out, its preventing me from making progress at the moment.

StatutProduits class:

package com.example.demo.entities;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 *
 * @author G557437
 */
@Entity
@Table(name = "STATUT_PRODUITS", catalog = "", schema = "PACKOUT")

public class StatutProduits implements Serializable {
    private static final long serialVersionUID = 1L;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "ID_STATUT_PRODUIT")
    private BigDecimal idStatutProduit;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "CODE")
    private String code;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "LIBELLE")
    private String libelle;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 10)
    @Column(name = "CREE_PAR")
    private String creePar;
    @Column(name = "DATE_CREATION")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreation;
    @Size(max = 10)
    @Column(name = "MAJ_PAR")
    private String majPar;
    @Column(name = "DATE_MAJ")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateMaj;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idStatutProduit")
    private List<Produits> produitsList;

    public StatutProduits() {
    }

    public StatutProduits(BigDecimal idStatutProduit) {
        this.idStatutProduit = idStatutProduit;
    }

    public StatutProduits(BigDecimal idStatutProduit, String code, String libelle, String creePar) {
        this.idStatutProduit = idStatutProduit;
        this.code = code;
        this.libelle = libelle;
        this.creePar = creePar;
    }

    public BigDecimal getIdStatutProduit() {
        return idStatutProduit;
    }

    public void setIdStatutProduit(BigDecimal idStatutProduit) {
        this.idStatutProduit = idStatutProduit;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getLibelle() {
        return libelle;
    }

    public void setLibelle(String libelle) {
        this.libelle = libelle;
    }

    public String getCreePar() {
        return creePar;
    }

    public void setCreePar(String creePar) {
        this.creePar = creePar;
    }

    public Date getDateCreation() {
        return dateCreation;
    }

    public void setDateCreation(Date dateCreation) {
        this.dateCreation = dateCreation;
    }

    public String getMajPar() {
        return majPar;
    }

    public void setMajPar(String majPar) {
        this.majPar = majPar;
    }

    public Date getDateMaj() {
        return dateMaj;
    }

    public void setDateMaj(Date dateMaj) {
        this.dateMaj = dateMaj;
    }

    public List<Produits> getProduitsList() {
        return produitsList;
    }

    public void setProduitsList(List<Produits> produitsList) {
        this.produitsList = produitsList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idStatutProduit != null ? idStatutProduit.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof StatutProduits)) {
            return false;
        }
        StatutProduits other = (StatutProduits) object;
        if ((this.idStatutProduit == null && other.idStatutProduit != null) || (this.idStatutProduit != null && !this.idStatutProduit.equals(other.idStatutProduit))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.sagemcom.tn.entities.StatutProduits[ idStatutProduit=" + idStatutProduit + " ]";
    }

}

Controller Class:

package com.example.demo.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.demo.dao.StatutProduitsRepository;
import com.example.demo.entities.StatutProduits;

@Controller
public class StatutProduitsController {

    @Autowired
    StatutProduitsRepository statutproduitsrepository ;

    @RequestMapping(value="/form", method=RequestMethod.GET)
    public String formStatProduit( Model model) {
        model.addAttribute("statproduit",new StatutProduits());
        return "FormStatutProduit";
    }

    @RequestMapping(value="/save", method=RequestMethod.POST)
    public String save( Model model, StatutProduits statproduit) {
        statutproduitsrepository.save(statproduit);
        return "Confirmation";
    }
}

thymleaf:

Statut d'un produit

            <form th:action="@{save}"  method="post">

                    ID
                    <input class="form-control" type="number" name="idStatutProduit"
                            th:value="${statproduit.idStatutProduit}"/>

                    Code
                    <input class="form-control" type="text" name="code"
                    th:value="${statproduit.code}"/>

                    Cree par
                    <input class="form-control" type="text" name="creePar"
                          th:value="${statproduit.creePar}"/>

                    Date creation
                    <input class="form-control" type="date"  name="dateCreation"
                    th:value="${statproduit.dateCreation}"/>

                    Date maj
                    <input class="form-control" type="date" name="dateMaj"
                    th:value="${statproduit.dateMaj}"/>

                    Libelle
                    <input class="form-control" type="text" name="libelle"
                    th:value="${statproduit.libelle}"/>

                    Maj par
                    <input class="form-control" type="text"  name="majPar"
                     th:value="${statproduit.majPar}"/>

                <button type="submit" class="btn btn-primary">Save</button>

             </form>

Body:
In your case, you have added server-side validation but in your controller, you didn't check that conditions and blindly saving that object into your database. instead of doing like that check the conditions in the controller by using BindingResult

 @RequestMapping(value="/save", method=RequestMethod.POST)
 public String save( Model model, @Validated StatutProduits statproduit BindingResult bindingResult) {
     if(bindingResult.hasErrors()){
         return "to same page to shows error fields";
     }
    statutproduitsrepository.save(statproduit);
    return "Confirmation";
 }


问:
What's the best way to manage a classic asp front-end using Visual Studio 2008?
I support a third party system that uses COM, classic ASP, and SQL Server.  Our company has gone to using TFS as our source control provider - which pushes things through Visual Studio.  So, what's the best way to get a classic asp front-end into Visual Studio?</p>

答:
Did any of you heard of Visual Web developer 2008 Express edition?
Work wonders for me.
Most important as soon as you ask to open website in it- it opens each folder of intended website and when you save project it does what you need to do to later open this website in regular visual studio.

It have some limited capability even to convert simple Classic ASP pages into NET  code!

OwnerDisplayName: The Imir of GrooFunkistan

LastEditorDisplayName: splattne


问:
CSS calc not working for  width
I'd like Cell A to leave exactly 100px for the remain two cells.  I would think calc(100% - 100px) would be sufficient as this works just fine in many other situations.  Why isn't it working here?

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

td:first-child {
  width: calc(100% - 100px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table></code>```

答:
At least in Chrome, it seems to work when defining the width on a colgroup element:

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

colgroup:first-child {
  width: calc(100% - 100px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <colgroup/>
  <colgroup span="2" />
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table></code>```

Update April 1st, 2020

This no longer seems to work in the current version of Chrome. I'll leave the answer to serve as a test case should the behavior change in the future.

Title: CSS calc not working for <td> width

Body:
I'd like Cell A to leave exactly 100px for the remain two cells.  I would think calc(100% - 100px) would be sufficient as this works just fine in many other situations.  Why isn't it working here?

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

td:first-child {
  width: calc(100% - 100px);
}

      Cell A
      Cell B
      Cell C

Body:
At least in Chrome, it seems to work when defining the width on a colgroup element:

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

colgroup:first-child {
  width: calc(100% - 100px);
}

<table>
  <colgroup/>
  <colgroup span="2" />
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table>

Update April 1st, 2020

This no longer seems to work in the current version of Chrome. I'll leave the answer to serve as a test case should the behavior change in the future.

ContentLicense: CC BY-SA 4.0


问:
Not reading lesser or greater than input properly
So this is the problem section in a simple "Is your amount greater than or less than 50?" program. This section is entirely independent, but it doesn't work. If my input is 50 or anything less, it says "Sorry, not enough money." But strangely, from 100 and on, it also registers those amounts as "Sorry, that is not enough money." I've tried a bunch of things with it and I can't get it to work! What am I missing? Thank you!</p>

```<code>money_amount = input("Type your amount with no quotations.")

if money_amount <= "50":
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")
</code>```

答:
You can't compare an string and an integer and expect good results. You should transform the input in an integer using int().

```<code>money_amount = int(input("Type your amount with no quotations."))

if money_amount <= 50:
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")
</code>```

By that way you can convert a string into a number to make the comparison. "50" from input would be transform into 50.

Also, you can't make an math operation (<=) with strings. So if money_amount <= "50": should be changed to if money_amount <= 50: (from string to integer), by that way you would be able to compare both numbers.

Body:
So this is the problem section in a simple "Is your amount greater than or less than 50?" program. This section is entirely independent, but it doesn't work. If my input is 50 or anything less, it says "Sorry, not enough money." But strangely, from 100 and on, it also registers those amounts as "Sorry, that is not enough money." I've tried a bunch of things with it and I can't get it to work! What am I missing? Thank you!

money_amount = input("Type your amount with no quotations.")

if money_amount <= "50":
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")

Body:
You can't compare an string and an integer and expect good results. You should transform the input in an integer using int().

money_amount = int(input("Type your amount with no quotations."))

if money_amount <= 50:
    print ("Sorry, that is not enough money.")
    quit()

else:
    print ("Yay!")

By that way you can convert a string into a number to make the comparison. "50" from input would be transform into 50.

Also, you can't make an math operation (<=) with strings. So if money_amount <= "50": should be changed to if money_amount <= 50: (from string to integer), by that way you would be able to compare both numbers.


问:
How to give a docker container its own routable IP (different from the host's)?
I am trying to give containers a routable IP. My local network is 192.168.1.0/24 and I'd like to use 192.168.1.17/29 to give containers.

The goal is to have each container have their own IP. This way if two containers run a webserver on port 80, I can reach them directly from any other host on the local network via their unique IP on port 80 instead of mapping them to different ports on the shared host's IP.

Similar to how a physical machine with its own network card would each have distinct 192.168.1.xxx IPs on the network.

I tried this:

```<code>docker network create --subnet 192.168.1.0/24 --ip-range 192.168.1.17/29 --gateway 192.168.1.1 test_nw
</code>```

which yields the following:

```<code>$ docker network inspect test_nw
[
    {
        "Name": "test_nw",
        "Id": "96bd574300059ef3710527a9bd0b3010d3b3c22d8de321ff459697eda96ab5e6",
        "Created": "2017-12-06T21:50:08.591070587-05:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.1.0/24",
                    "IPRange": "192.168.1.17/29",
                    "Gateway": "192.168.1.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]
</code>```

In this case from within a container, I can ping 192.168.1.1 but I can't ping anything on the internet (either by IP or by hostname.), and I can't even ping other devices on the local network (192.168.1.2 exists but is unreachable)

The host (my laptop) is also unable to reach anything on the internet or on my local network anymore until I remove this network with docker network rm.

I'm obviously missing something, but I can't understand what. Is there any way to achieve what I'm trying to do?

答:
This way if two containers run a webserver on port 80, I can reach them directly from any other host on the local network via their unique IP on port 80 instead of mapping them to different ports on the shared host's IP.

I think maybe you are thinking about this problem wrong. You don't have to map them to different ports on the shared host's IP.  The most common way of solving this problem is to assign multiple ip addresses to the host.  For example, if my host is 192.168.1.100, I might add some additional addresses:

```<code>ip addr add 192.168.1.200/24 dev eth0
ip addr add 192.168.1.201/24 dev eth0
</code>```

Now I can start up one webserver and bind it to the first ip address:

```<code>docker run -p 192.168.1.200:80:80 mywebserver1
</code>```

And I can start another webserver and map that to port 80 on the other address:

```<code>docker run -p 192.168.1.201:80:80 mywebserver2
</code>```

This seems to meet your goal.

Body:
I am trying to give containers a routable IP. My local network is 192.168.1.0/24 and I'd like to use 192.168.1.17/29 to give containers.

The goal is to have each container have their own IP. This way if two containers run a webserver on port 80, I can reach them directly from any other host on the local network via their unique IP on port 80 instead of mapping them to different ports on the shared host's IP.

Similar to how a physical machine with its own network card would each have distinct 192.168.1.xxx IPs on the network.

I tried this:

docker network create --subnet 192.168.1.0/24 --ip-range 192.168.1.17/29 --gateway 192.168.1.1 test_nw

which yields the following:

$ docker network inspect test_nw
[
    {
        "Name": "test_nw",
        "Id": "96bd574300059ef3710527a9bd0b3010d3b3c22d8de321ff459697eda96ab5e6",
        "Created": "2017-12-06T21:50:08.591070587-05:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.1.0/24",
                    "IPRange": "192.168.1.17/29",
                    "Gateway": "192.168.1.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]

In this case from within a container, I can ping 192.168.1.1 but I can't ping anything on the internet (either by IP or by hostname.), and I can't even ping other devices on the local network (192.168.1.2 exists but is unreachable)

The host (my laptop) is also unable to reach anything on the internet or on my local network anymore until I remove this network with docker network rm.

I'm obviously missing something, but I can't understand what. Is there any way to achieve what I'm trying to do?

Body:
This way if two containers run a webserver on port 80, I can reach them directly from any other host on the local network via their unique IP on port 80 instead of mapping them to different ports on the shared host's IP.

I think maybe you are thinking about this problem wrong. You don't have to map them to different ports on the shared host's IP.  The most common way of solving this problem is to assign multiple ip addresses to the host.  For example, if my host is 192.168.1.100, I might add some additional addresses:

ip addr add 192.168.1.200/24 dev eth0
ip addr add 192.168.1.201/24 dev eth0

Now I can start up one webserver and bind it to the first ip address:

docker run -p 192.168.1.200:80:80 mywebserver1

And I can start another webserver and map that to port 80 on the other address:

docker run -p 192.168.1.201:80:80 mywebserver2

This seems to meet your goal.


问:
Lodash _.set only if object exists
I am looking to set inner properties of an object only if they already exist. Lodash _.set will create the whole hierarchy if it does not exist.

Is there an easy way to do this ? (Without and if statement ?)

Snippet below:

const obj = {a: {b: 1}};

_.set(obj, 'a.b', 2);

console.log(obj); // Great !

_.set(obj, 'a.c', 1);

console.log(obj); // Great but not what I want. I would like c not to be set because it does not exist in the first place```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

答:
The answer from Kalaiselvan A below put me on the way but this is not quite what I was looking for.

Using the same idea but improving the ternary gives me the following solution which I am happy with.

const obj = {a: {b: 1}};

_.has(obj, 'a.b') && _.set(obj, 'a.b', 2);

console.log(obj);

_.has(obj, 'a.c') && _.set(obj, 'a.c', 2);

console.log(obj);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script></code>```

Title: Lodash _.set only if object exists

Body:
The answer from Kalaiselvan A below put me on the way but this is not quite what I was looking for.

Using the same idea but improving the ternary gives me the following solution which I am happy with.

const obj = {a: {b: 1}};

_.has(obj, 'a.b') && _.set(obj, 'a.b', 2);

console.log(obj);

_.has(obj, 'a.c') && _.set(obj, 'a.c', 2);

console.log(obj);

<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>


问:
Cache Object Script How to MakeDirectory FTP Class
In Cache Object Script how can I make a remote directory on an FTP Server. I do see the class MakeDirectory but that is returning 0 when I call it?</p>

```<code>set ftp=##class(%Net.FtpSession).%New()
d ftp.Connect(COMServer,c.Username,c.Password)
d ftp.SetDirectory("/Test")
w ftp.MakeDirectory("6666")
0
</code>```

答:
This should create directory 6666 under /Test, are you sure /Test exists and you have enough privileges to create directory there?

You can check ftp.ReturnCode and ftp.ReturnMessage to check for server response.

Body:
In Cache Object Script how can I make a remote directory on an FTP Server. I do see the class MakeDirectory but that is returning 0 when I call it?

set ftp=##class(%Net.FtpSession).%New()
d ftp.Connect(COMServer,c.Username,c.Password)
d ftp.SetDirectory("/Test")
w ftp.MakeDirectory("6666")
0


问:
Is it possible to use a variable as part of an image URL?
I am making a quiz on a basic website using PHP and HTML/CSS and have answers stored in a PHP array.

I would like to display the quiz answers and the corresponding images (which I have named to match) using the simplest method.
For example if $ANSWER="cat", I want to display "cat.jpg"

If it were possible to use a variable in the image URL it would be wonderful, but I haven't been able to find an example of this.

Should this syntax work?

```<code>echo '<img src=/pictures/"$ANSWER".jpg >';
</code>```

So far I'm getting no output but not sure if it's due to a bug somewhere else.

答:
Simply

```<code>echo "<img src='/pictures/".$ANSWER.".jpg' >";
</code>```

or

```<code><img src="/pictures/<?php edho $ANSWER;?>.jpg">
</code>```

Body:
I am making a quiz on a basic website using PHP and HTML/CSS and have answers stored in a PHP array.

I would like to display the quiz answers and the corresponding images (which I have named to match) using the simplest method.
For example if $ANSWER="cat", I want to display "cat.jpg"

If it were possible to use a variable in the image URL it would be wonderful, but I haven't been able to find an example of this.

Should this syntax work?

echo '';

So far I'm getting no output but not sure if it's due to a bug somewhere else.

Body:
Simply

echo "<img src='/pictures/".$ANSWER.".jpg' >";

or

<img src="/pictures/<?php edho $ANSWER;?>.jpg">