问:
Weird behaviour of direction property in CSS
I was just playing around with CSS on Codepen with auto-save mode enabled when I encountered this weird behaviour,

Here's my code-

var inner_div = document.querySelector('.inner-div');
var width = inner_div.offsetWidth;
if(width > 200)
  {
    inner_div.style.fontSize = '20px';
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outer-div {
    display: flex;
    height: 3.5em;
    width: 10%;
    border: 2px solid #000000a3;
    margin-left: 200px;
    align-items: center;
    border: 1px solid green;
    direction: rtl;
    white-space: nowrap;
    overflow-x: auto;
}
.inner-div {
    font-size: 40px;
}</code>```

       Hello World

```

As my auto-save mode was enabled, I was checking with each key press whether the text is being appended from right to left or not, but when I press slash(/), or any of the arithmetic operators(+, -, *), then these are first appended on the left first and then if the next keypress is alphanumeric then it appends it automatically to the right of the expression.
For e.g., if I type c, then b, then a, then it gets displayed as 'abc'(as desired from direction: rtl property), but if I then type slash(/), then the display is /abc, and then if I type any alphanumeric character, say d, then it displays abc/d .
Could someone explain me the reason for this. Thanks.

答: Slash has BiDi (bi-directional) class on I think. The same thing with ! and other special character. It applies the direction in context of surrounding text</p>

Body:
I was just playing around with CSS on Codepen with auto-save mode enabled when I encountered this weird behaviour,

Here's my code-

var inner_div = document.querySelector('.inner-div');
var width = inner_div.offsetWidth;
if(width > 200)
  {
    inner_div.style.fontSize = '20px';
  }

.outer-div {
    display: flex;
    height: 3.5em;
    width: 10%;
    border: 2px solid #000000a3;
    margin-left: 200px;
    align-items: center;
    border: 1px solid green;
    direction: rtl;
    white-space: nowrap;
    overflow-x: auto;
}
.inner-div {
    font-size: 40px;
}

       Hello World

As my auto-save mode was enabled, I was checking with each key press whether the text is being appended from right to left or not, but when I press slash(/), or any of the arithmetic operators(+, -, *), then these are first appended on the left first and then if the next keypress is alphanumeric then it appends it automatically to the right of the expression.
For e.g., if I type c, then b, then a, then it gets displayed as 'abc'(as desired from direction: rtl property), but if I then type slash(/), then the display is /abc, and then if I type any alphanumeric character, say d, then it displays abc/d .
Could someone explain me the reason for this. Thanks.


来源: stackexchange

问:
NO 'Access-control-allow-origin' header is present on the requested resource.Origin http://localhost:4200 is therefore not allowed access
I am trying to send request through angular.js 4 to java rest api.I am getting the following error : NO 'Access-control-allow-origin' header is present on the requested  resource.Origin http://localhost:4200 is therefore not allowed access
My code looks like :

```<code>    signupUser() {
    // if (this.signupForm.dirty && this.signupForm.valid) {
    // let headers = new Headers({ 'Content-Type': 'application/json' });
    let data = {
      "email": this.signupForm.value.email,
      "password": this.signupForm.value.password,
      'phone': this.signupForm.value.mobile,

      // 'first_name': 'dd1',
      // 'email': 'xyz@gmail.com',
      // 'password': 'manju',
      // 'phone': '123456',
      'signup_type': 'Custom',
      // social_media:
      // "email": this.loginForm.value.name,
      // "password": this.loginForm.value.password
    };
    console.log(data)

    let options = {
      type: "GET",
      url: "http://localhost:8085/dashboard/signUp",
      body: JSON.stringify(data)
    };

    this.http.post(options.url, options.body, {
      headers: this.headers
    }).subscribe((data) => {
      console.log(data);
      this.otpScreen = true;
    }, (err) => {
      console.log(err);
    });
    // alert(`Name: ${this.userForm.value.name} Email:         ${this.userForm.value.password}`);
    // }
}
</code>```

@CrossOrigin(origins="http://localhost:4200")
Adding this line in java code has to resolve this issue but still same error I'm getting can anyone let me know how to solve this issue? My Controller looks like:

```<code>@CrossOrigin
@RequestMapping("/signUp")
public void getOTP(HttpServletRequest request, HttpServletResponse response){
    System.out.println("In Signup");
}
</code>```

答:
or add a global config to your spring application allowing the localhost:4200

e.g.

```<code>package nl.ivonet.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Adds a CORS filter on http://localhost:4200 allowing it cross origin access.
 * It is the url where ng serve works when developing.
 * <p>
 * you could also add @CrossOrigin(origins = "*") to the rest method but this is global.
 *
 * @author Ivo Woltring
 */
@Configuration
public class CorsConfig {
    @Bean
    public FilterRegistrationBean corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:4200");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send request through angular.js 4 to java rest api.I am getting the following error : NO 'Access-control-allow-origin' header is present on the requested  resource.Origin http://localhost:4200 is therefore not allowed access
My code looks like :

    signupUser() {
    // if (this.signupForm.dirty && this.signupForm.valid) {
    // let headers = new Headers({ 'Content-Type': 'application/json' });
    let data = {
      "email": this.signupForm.value.email,
      "password": this.signupForm.value.password,
      'phone': this.signupForm.value.mobile,

      // 'first_name': 'dd1',
      // 'email': 'xyz@gmail.com',
      // 'password': 'manju',
      // 'phone': '123456',
      'signup_type': 'Custom',
      // social_media:
      // "email": this.loginForm.value.name,
      // "password": this.loginForm.value.password
    };
    console.log(data)

    let options = {
      type: "GET",
      url: "http://localhost:8085/dashboard/signUp",
      body: JSON.stringify(data)
    };

    this.http.post(options.url, options.body, {
      headers: this.headers
    }).subscribe((data) => {
      console.log(data);
      this.otpScreen = true;
    }, (err) => {
      console.log(err);
    });
    // alert(`Name: ${this.userForm.value.name} Email:         ${this.userForm.value.password}`);
    // }
}

@CrossOrigin(origins="http://localhost:4200")
Adding this line in java code has to resolve this issue but still same error I'm getting can anyone let me know how to solve this issue? My Controller looks like:

@CrossOrigin
@RequestMapping("/signUp")
public void getOTP(HttpServletRequest request, HttpServletResponse response){
    System.out.println("In Signup");
}

Body:
or add a global config to your spring application allowing the localhost:4200

e.g.

package nl.ivonet.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Adds a CORS filter on http://localhost:4200 allowing it cross origin access.
 * It is the url where ng serve works when developing.
 * <p>
 * you could also add @CrossOrigin(origins = "*") to the rest method but this is global.
 *
 * @author Ivo Woltring
 */
@Configuration
public class CorsConfig {
    @Bean
    public FilterRegistrationBean corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:4200");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}


问:
What are the predefined single-character variables in python called?
My point is that python has some predefined variables that you may have not even set, but still was given a value when you start off the shell. Say you ran the following code:

```<code>print (a)
</code>```

Without even having defined variable "a" beforehand, it returned 0. Wherease, if you tried printing:

```<code>print(var1)
</code>```

Would return an error because var1 was not defined. I did a bit of testing and found out the same goes for every other single character in python, print any of them out on the console and you will get the same result of 0.

The question I'd like to ask is that why are these characters given their own value beforehand? And are there special names for these predefined variables such as these? If I could know the name of these special variables, I could read upon some documentations about them.

答:
There are no predefined variables in python.

```<code>print(a)
</code>```

will return NameError: name 'a' is not defined as long as a has not been defined earlier.

Body:
My point is that python has some predefined variables that you may have not even set, but still was given a value when you start off the shell. Say you ran the following code:

print (a)

Without even having defined variable "a" beforehand, it returned 0. Wherease, if you tried printing:

print(var1)

Would return an error because var1 was not defined. I did a bit of testing and found out the same goes for every other single character in python, print any of them out on the console and you will get the same result of 0.

The question I'd like to ask is that why are these characters given their own value beforehand? And are there special names for these predefined variables such as these? If I could know the name of these special variables, I could read upon some documentations about them.

Body:
There are no predefined variables in python.

print(a)

will return NameError: name 'a' is not defined as long as a has not been defined earlier.


问:
Programming by contracts in PHP
Programming by contracts is a modern trend in .NET, but what about libraries/frameworks for code contracts in PHP? What do you think about applicability of this paradigm for PHP?

Googling for "code contracts php" gave nothing to me.

Note: by "code by contract", I mean Design by contract, so it has nothing to do with .NET or PHP interfaces.

答:
I was searching for the same thing by curiosity, and found this question, so will try to give an answer.

First, PHP, by design, is not really code-contracty. You cannot even enforce, when need, the core types¹ of parameters inside the methods, so I hardly believe that code contracts will exist in PHP one day.

Let's see what happens if we do a custom, third party library/framework implementation.

1. Preconditions

The freedom of passing everything we want to a method makes code contracts (or something more or less similar to code contracts) very valuable, at least on preconditions, since protecting methods against bad values in arguments is more difficult to do, comparing to normal programming languages, where types can be enforced through the language itself.

It would be more convenient to write:

```<code>public function AddProduct($productId, $name, $price, $isCurrentlyInStock)
{
    Contracts::Require(__FILE__, __LINE__, is_int($productId), 'The product ID must be an integer.');
    Contracts::Require(__FILE__, __LINE__, is_string($name), 'The product name must be a string.');
    Contracts::Require(__FILE__, __LINE__, is_int($price), 'The price must be an integer.');
    Contracts::Require(__FILE__, __LINE__, is_bool($isCurrentlyInStock), 'The product availability must be an boolean.');

    Contracts::Require(__FILE__, __LINE__, $productId > 0 && $productId <= 5873, 'The product ID is out of range.');
    Contracts::Require(__FILE__, __LINE__, $price > 0, 'The product price cannot be negative.');

    // Business code goes here.
}
</code>```

instead of:

```<code>public function AddProduct($productId, $name, $price, $isCurrentlyInStock)
{
    if (!is_int($productId))
    {
        throw new ArgumentException(__FILE__, __LINE__, 'The product ID must be an integer.');
    }

    if (!is_int($name))
    {
        throw new ArgumentException(__FILE__, __LINE__, 'The product name must be a string.');
    }

    // Continue with four other checks.

    // Business code goes here.
}
</code>```

2. Postconditions: big problems

What is easy to do with preconditions remains impossible for postconditions. Of course, you can imagine something like:

```<code>public function FindLastProduct()
{
    $lastProduct = ...

    // Business code goes here.

    Contracts::Ensure($lastProduct instanceof Product, 'The method was about to return a non-product, when an instance of a Product class was expected.');
    return $lastProduct;
}
</code>```

The only problem is that this approach has nothing to do with code contracts, neither at the implementation level (just like a preconditions example), nor on code level (since postconditions go before actual business code, not between code and method return).

It also means that if there are multiple returns in a method or a throw, postcondition will never be checked, unless you include the $this->Ensure() before every return or throw (maintenance nightmare!).

3. Invariants: possible?

With setters, it is possible to emulate some sort of code contracts on properties. But setters are so badly implemented in PHP, that this will cause too many problems, and auto-completion will not work if setters are used instead of fields.

4. Implementation

To finish, PHP is not a best candidate for code contracts, and since its design is so poor, it will probably never have code contracts, unless there will be substantial changes in future in the language design.

Currently, pseudo-code contracts² are pretty worthless when it comes to postconditions or invariants. On the other hand, some pseudo-preconditions can be easily written in PHP, making checks on arguments much more elegant and shorter.

Here's a short example of such implementation:

```<code>class ArgumentException extends Exception
{
    // Code here.
}

class CodeContracts
{
    public static function Require($file, $line, $precondition, $failureMessage)
    {
        Contracts::Require(__FILE__, __LINE__, is_string($file), 'The source file name must be a string.');
        Contracts::Require(__FILE__, __LINE__, is_int($line), 'The source file line must be an integer.');
        Contracts::Require(__FILE__, __LINE__, is_string($precondition), 'The precondition must evaluate to a boolean.');
        Contracts::Require(__FILE__, __LINE__, is_int($failureMessage), 'The failure message must be a string.');

        Contracts::Require(__FILE__, __LINE__, $file != '', 'The source file name cannot be an empty string.');
        Contracts::Require(__FILE__, __LINE__, $line >= 0, 'The source file line cannot be negative.');

        if (!$precondition)
        {
            throw new ContractException('The code contract was violated in ' . $file . ':' . $line . ': ' . $failureMessage);
        }
    }
}
</code>```

Of course, an exception may be replaced by log-and-continue/log-and-stop approach, a error page, etc.

5. Conclusion

Looking at the implementation of precontracts, the whole idea seems worthless. Why are we bothering with those pseudo-code contracts, which are actually very different from code contracts in normal programming languages? What does it brings to us? Pretty nothing, except the fact that we can write the checks in the same way as if we were using real code contracts. And there is no reason to do this just because we can.

Why code contracts exist in normal languages? For two reasons:

Because they provide a simple way to enforce conditions which must be matched when a block of code starts or finishes,

Because when I use a .NET Framework library which uses code contracts, I can easily know within the IDE what is required by the method, and what is expected from the method, and this, without having an access to the source code³.

From what I see, in an implementation of pseudo-code contracts in PHP, the first reason is very limited, and the second one does not exist and will probably never exist.

It means that actually, a simple check of arguments is a good alternative, especially since PHP works well with arrays. Here's a copy-paste from an old personal project:

```<code>class ArgumentException extends Exception
{
    private $argumentName = null;

    public function __construct($message = '', $code = 0, $argumentName = '')
    {
        if (!is_string($message)) throw new ArgumentException('Wrong parameter for ArgumentException constructor. String value expected.', 0, 'message');
        if (!is_long($code)) throw new ArgumentException('Wrong parameter for ArgumentException constructor. Integer value expected.', 0, 'code');
        if (!is_string($argumentName)) throw new ArgumentException('Wrong parameter for ArgumentException constructor. String value expected.', 0, 'argumentName');
        parent::__construct($message, $code);
        $this->argumentName = $argumentName;
    }

    public function __toString()
    {
        return 'exception \'' . get_class($this) . '\' ' . ((!$this->argumentName) ? '' : 'on argument \'' . $this->argumentName . '\' ') . 'with message \'' . parent::getMessage() . '\' in ' . parent::getFile() . ':' . parent::getLine() . '
Stack trace:
' . parent::getTraceAsString();
    }
}

class Component
{
    public static function CheckArguments($file, $line, $args)
    {
        foreach ($args as $argName => $argAttributes)
        {
            if (isset($argAttributes['type']) && (!VarTypes::MatchType($argAttributes['value'], $argAttributes['type'])))
            {
                throw new ArgumentException(String::Format('Invalid type for argument \'{0}\' in {1}:{2}. Expected type: {3}.', $argName, $file, $line, $argAttributes['type']), 0, $argName);
            }
            if (isset($argAttributes['length']))
            {
                settype($argAttributes['length'], 'integer');
                if (is_string($argAttributes['value']))
                {
                    if (strlen($argAttributes['value']) != $argAttributes['length'])
                    {
                        throw new ArgumentException(String::Format('Invalid length for argument \'{0}\' in {1}:{2}. Expected length: {3}. Current length: {4}.', $argName, $file, $line, $argAttributes['length'], strlen($argAttributes['value'])), 0, $argName);
                    }
                }
                else
                {
                    throw new ArgumentException(String::Format('Invalid attributes for argument \'{0}\' in {1}:{2}. Either remove length attribute or pass a string.', $argName, $file, $line), 0, $argName);
                }
            }
        }
    }
}
</code>```

Usage example:

```<code>/// <summary>
/// Determines whether the ending of the string matches the specified string.
/// </summary>
public static function EndsWith($string, $end, $case = true)
{
    Component::CheckArguments(__FILE__, __LINE__, array(
        'string' => array('value' => $string, 'type' => VTYPE_STRING),
        'end' => array('value' => $end, 'type' => VTYPE_STRING),
        'case' => array('value' => $case, 'type' => VTYPE_BOOL)
    ));

    $stringLength = strlen($string);
    $endLength = strlen($end);
    if ($endLength > $stringLength) return false;
    if ($endLength == $stringLength && $string != $end) return false;

    return (($case) ? substr_compare($string, $end, $stringLength - $endLength) : substr_compare($string, $end, $stringLength - $endLength, $stringLength, true)) == 0;
}
</code>```

It will not be enough if we want to check preconditions which are not just dependent of arguments (for example checking a value of a property in a precondition). But in most cases, all we need is to check arguments, and pseudo-code contracts in PHP are not the best way to do it.

In other words, if your only purpose is to check the arguments, pseudo-code contracts are an overkill. They may be possible when you need something more, like a precondition which depends on an object property. But in this last case, there are probably more PHPy ways to do things⁴, so the only reason to use code contracts stays: because we can.

¹ We can specify that an argument must be an instance of a class. Curiously, there is no way to specify that an argument must be an integer or a string.

² By pseudo-code contracts, I mean that the implementation presented above is very different from the implementation of code contracts in .NET Framework. The real implementation would be possible only by changing the language itself.

³ If Contract Reference Assembly is built, or, even better, if contracts are specified in an XML file.

⁴ A simple if - throw can do the trick.

Title: Programming by contracts in PHP

Body:
I was searching for the same thing by curiosity, and found this question, so will try to give an answer.

First, PHP, by design, is not really code-contracty. You cannot even enforce, when need, the core types¹ of parameters inside the methods, so I hardly believe that code contracts will exist in PHP one day.

Let's see what happens if we do a custom, third party library/framework implementation.

1. Preconditions

The freedom of passing everything we want to a method makes code contracts (or something more or less similar to code contracts) very valuable, at least on preconditions, since protecting methods against bad values in arguments is more difficult to do, comparing to normal programming languages, where types can be enforced through the language itself.

It would be more convenient to write:

public function AddProduct($productId, $name, $price, $isCurrentlyInStock)
{
    Contracts::Require(__FILE__, __LINE__, is_int($productId), 'The product ID must be an integer.');
    Contracts::Require(__FILE__, __LINE__, is_string($name), 'The product name must be a string.');
    Contracts::Require(__FILE__, __LINE__, is_int($price), 'The price must be an integer.');
    Contracts::Require(__FILE__, __LINE__, is_bool($isCurrentlyInStock), 'The product availability must be an boolean.');

    Contracts::Require(__FILE__, __LINE__, $productId > 0 && $productId <= 5873, 'The product ID is out of range.');
    Contracts::Require(__FILE__, __LINE__, $price > 0, 'The product price cannot be negative.');

    // Business code goes here.
}

instead of:

public function AddProduct($productId, $name, $price, $isCurrentlyInStock)
{
    if (!is_int($productId))
    {
        throw new ArgumentException(__FILE__, __LINE__, 'The product ID must be an integer.');
    }

    if (!is_int($name))
    {
        throw new ArgumentException(__FILE__, __LINE__, 'The product name must be a string.');
    }

    // Continue with four other checks.

    // Business code goes here.
}

2. Postconditions: big problems

What is easy to do with preconditions remains impossible for postconditions. Of course, you can imagine something like:

public function FindLastProduct()
{
    $lastProduct = ...

    // Business code goes here.

    Contracts::Ensure($lastProduct instanceof Product, 'The method was about to return a non-product, when an instance of a Product class was expected.');
    return $lastProduct;
}

The only problem is that this approach has nothing to do with code contracts, neither at the implementation level (just like a preconditions example), nor on code level (since postconditions go before actual business code, not between code and method return).

It also means that if there are multiple returns in a method or a throw, postcondition will never be checked, unless you include the $this->Ensure() before every return or throw (maintenance nightmare!).

3. Invariants: possible?

With setters, it is possible to emulate some sort of code contracts on properties. But setters are so badly implemented in PHP, that this will cause too many problems, and auto-completion will not work if setters are used instead of fields.

4. Implementation

To finish, PHP is not a best candidate for code contracts, and since its design is so poor, it will probably never have code contracts, unless there will be substantial changes in future in the language design.

Currently, pseudo-code contracts² are pretty worthless when it comes to postconditions or invariants. On the other hand, some pseudo-preconditions can be easily written in PHP, making checks on arguments much more elegant and shorter.

Here's a short example of such implementation:

class ArgumentException extends Exception
{
    // Code here.
}

class CodeContracts
{
    public static function Require($file, $line, $precondition, $failureMessage)
    {
        Contracts::Require(__FILE__, __LINE__, is_string($file), 'The source file name must be a string.');
        Contracts::Require(__FILE__, __LINE__, is_int($line), 'The source file line must be an integer.');
        Contracts::Require(__FILE__, __LINE__, is_string($precondition), 'The precondition must evaluate to a boolean.');
        Contracts::Require(__FILE__, __LINE__, is_int($failureMessage), 'The failure message must be a string.');

        Contracts::Require(__FILE__, __LINE__, $file != '', 'The source file name cannot be an empty string.');
        Contracts::Require(__FILE__, __LINE__, $line >= 0, 'The source file line cannot be negative.');

        if (!$precondition)
        {
            throw new ContractException('The code contract was violated in ' . $file . ':' . $line . ': ' . $failureMessage);
        }
    }
}

Of course, an exception may be replaced by log-and-continue/log-and-stop approach, a error page, etc.

5. Conclusion

Looking at the implementation of precontracts, the whole idea seems worthless. Why are we bothering with those pseudo-code contracts, which are actually very different from code contracts in normal programming languages? What does it brings to us? Pretty nothing, except the fact that we can write the checks in the same way as if we were using real code contracts. And there is no reason to do this just because we can.

Why code contracts exist in normal languages? For two reasons:

Because they provide a simple way to enforce conditions which must be matched when a block of code starts or finishes,

Because when I use a .NET Framework library which uses code contracts, I can easily know within the IDE what is required by the method, and what is expected from the method, and this, without having an access to the source code³.

From what I see, in an implementation of pseudo-code contracts in PHP, the first reason is very limited, and the second one does not exist and will probably never exist.

It means that actually, a simple check of arguments is a good alternative, especially since PHP works well with arrays. Here's a copy-paste from an old personal project:

class ArgumentException extends Exception
{
    private $argumentName = null;

    public function __construct($message = '', $code = 0, $argumentName = '')
    {
        if (!is_string($message)) throw new ArgumentException('Wrong parameter for ArgumentException constructor. String value expected.', 0, 'message');
        if (!is_long($code)) throw new ArgumentException('Wrong parameter for ArgumentException constructor. Integer value expected.', 0, 'code');
        if (!is_string($argumentName)) throw new ArgumentException('Wrong parameter for ArgumentException constructor. String value expected.', 0, 'argumentName');
        parent::__construct($message, $code);
        $this->argumentName = $argumentName;
    }

    public function __toString()
    {
        return 'exception \'' . get_class($this) . '\' ' . ((!$this->argumentName) ? '' : 'on argument \'' . $this->argumentName . '\' ') . 'with message \'' . parent::getMessage() . '\' in ' . parent::getFile() . ':' . parent::getLine() . '
Stack trace:
' . parent::getTraceAsString();
    }
}

class Component
{
    public static function CheckArguments($file, $line, $args)
    {
        foreach ($args as $argName => $argAttributes)
        {
            if (isset($argAttributes['type']) && (!VarTypes::MatchType($argAttributes['value'], $argAttributes['type'])))
            {
                throw new ArgumentException(String::Format('Invalid type for argument \'{0}\' in {1}:{2}. Expected type: {3}.', $argName, $file, $line, $argAttributes['type']), 0, $argName);
            }
            if (isset($argAttributes['length']))
            {
                settype($argAttributes['length'], 'integer');
                if (is_string($argAttributes['value']))
                {
                    if (strlen($argAttributes['value']) != $argAttributes['length'])
                    {
                        throw new ArgumentException(String::Format('Invalid length for argument \'{0}\' in {1}:{2}. Expected length: {3}. Current length: {4}.', $argName, $file, $line, $argAttributes['length'], strlen($argAttributes['value'])), 0, $argName);
                    }
                }
                else
                {
                    throw new ArgumentException(String::Format('Invalid attributes for argument \'{0}\' in {1}:{2}. Either remove length attribute or pass a string.', $argName, $file, $line), 0, $argName);
                }
            }
        }
    }
}

Usage example:

/// <summary>
/// Determines whether the ending of the string matches the specified string.
/// </summary>
public static function EndsWith($string, $end, $case = true)
{
    Component::CheckArguments(__FILE__, __LINE__, array(
        'string' => array('value' => $string, 'type' => VTYPE_STRING),
        'end' => array('value' => $end, 'type' => VTYPE_STRING),
        'case' => array('value' => $case, 'type' => VTYPE_BOOL)
    ));

    $stringLength = strlen($string);
    $endLength = strlen($end);
    if ($endLength > $stringLength) return false;
    if ($endLength == $stringLength && $string != $end) return false;

    return (($case) ? substr_compare($string, $end, $stringLength - $endLength) : substr_compare($string, $end, $stringLength - $endLength, $stringLength, true)) == 0;
}

It will not be enough if we want to check preconditions which are not just dependent of arguments (for example checking a value of a property in a precondition). But in most cases, all we need is to check arguments, and pseudo-code contracts in PHP are not the best way to do it.

In other words, if your only purpose is to check the arguments, pseudo-code contracts are an overkill. They may be possible when you need something more, like a precondition which depends on an object property. But in this last case, there are probably more PHPy ways to do things⁴, so the only reason to use code contracts stays: because we can.

¹ We can specify that an argument must be an instance of a class. Curiously, there is no way to specify that an argument must be an integer or a string.

² By pseudo-code contracts, I mean that the implementation presented above is very different from the implementation of code contracts in .NET Framework. The real implementation would be possible only by changing the language itself.

³ If Contract Reference Assembly is built, or, even better, if contracts are specified in an XML file.

⁴ A simple if - throw can do the trick.


问:
Generate OpenAPI spec for vertx project
I want to generate an OpenAPI spec for my vertx project. So I have a simple vertx server as follows which just returns me a json object:

```<code>package server;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

public class Server extends AbstractVerticle {

  @Override
  public void start() throws Exception {
    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);
    router.route("/v0.2.2/*").handler(this::responseSetUp);
    router.get("/v0.2.2/location").handler(this::getLocation);
    server.requestHandler(router::accept).listen(8004);
  }

  public void responseSetUp(RoutingContext context) {
    HttpServerResponse response = context.response();
    response.putHeader("Access-Control-Allow-Origin", "*")
        .putHeader("Access-Control-Allow-Methods", "GET, POST, PUT , DELETE, OPTIONS")
        .putHeader("Access-Control-Allow-Headers", "Content-Type,cache-control, x-requested-with")
        .putHeader("Access-Control-Max-Age", "86400");
    context.next();
  }

  public void getLocation(RoutingContext context) {
    JsonObject location = new JsonObject();
    location.put("city", "Bangalore");
    location.put("country", "India");
    location.put("pin", 560095);
    HttpServerResponse response = context.response();
    response.putHeader("content-type", "application/json");
    response.setChunked(true);
    response.write(location.toString());
    response.end();
  }
}
</code>```

I just want to generate an OpenAPI spec for this route. I am new to Swagger and so far while googling, I could see tutorials for RestEasy, Mule, Jersey1,Jersey2, Spring but not for vertx.

Can anyone please help me out or any pointers?

Sorry, if the question is naive.

答: With Vert.x 3.5.0 there's a new package called Vert.x Web API Contract that helps you generate the Router and the Validation handlers for your request. You can also generate a skeleton of your project with slush-vertx, a command line tool that helps you scaffolding your project</p>

Title: Generate OpenAPI spec for vertx project

Body:
I want to generate an OpenAPI spec for my vertx project. So I have a simple vertx server as follows which just returns me a json object:

package server;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

public class Server extends AbstractVerticle {

  @Override
  public void start() throws Exception {
    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);
    router.route("/v0.2.2/*").handler(this::responseSetUp);
    router.get("/v0.2.2/location").handler(this::getLocation);
    server.requestHandler(router::accept).listen(8004);
  }

  public void responseSetUp(RoutingContext context) {
    HttpServerResponse response = context.response();
    response.putHeader("Access-Control-Allow-Origin", "*")
        .putHeader("Access-Control-Allow-Methods", "GET, POST, PUT , DELETE, OPTIONS")
        .putHeader("Access-Control-Allow-Headers", "Content-Type,cache-control, x-requested-with")
        .putHeader("Access-Control-Max-Age", "86400");
    context.next();
  }

  public void getLocation(RoutingContext context) {
    JsonObject location = new JsonObject();
    location.put("city", "Bangalore");
    location.put("country", "India");
    location.put("pin", 560095);
    HttpServerResponse response = context.response();
    response.putHeader("content-type", "application/json");
    response.setChunked(true);
    response.write(location.toString());
    response.end();
  }
}

I just want to generate an OpenAPI spec for this route. I am new to Swagger and so far while googling, I could see tutorials for RestEasy, Mule, Jersey1,Jersey2, Spring but not for vertx.

Can anyone please help me out or any pointers?

Sorry, if the question is naive.


问:
Jira: Query all stories that belong to a different project than the Epic itself
In Jira I want to query all stories that belong to a different project than the Epic itself.

For example:
My Epic is in project Y. The Epic contains 5 stories in project Y but one story in project Z.

Now I want to show on a board only the stories that belong to different projects than the epic they belong to.

The goal is to create a board that gives me an overview of dependencies on other projects than my own.

Can anyone please advise how I can accomplish this?

答:
Try This JQL query

```<code>Project!="YourProject" and issuetype=Story and "Epic Link" in (XXX-###, YYY-###)
</code>```

Advanced scearching

Body:
Try This JQL query

Project!="YourProject" and issuetype=Story and "Epic Link" in (XXX-###, YYY-###)

Advanced scearching


问:
Python File Reading into another text in diff format
my text file look like
name1\n
name2\n
name3\n

I want read this file and store in another text file like this('name1','name2','name3') in Python, Could you please help anyone.

答:
```<code>YourTextFile = 'name1\n name2\n name3\n'
ListOFNames = YourTextFile.split('\n ')
AllNamesList = [x.replace('\n', '') for x in ListOFNames]
</code>```


问:
create-react-app node-less compilation

I'm using node-less compiler with my create-react-app webpack config in order to compile my less files. The compilation is EXTREMELY slow and takes nearly 5-8 secs for every file change.

Here's a part of my webpack config that specifies less compilation:

```<code>{
  exclude: [
    /\.html$/,
    /\.(js|jsx)$/,
    /\.css$/,
    /\.json$/,
    /\.svg$/,
    /\.less$/
  ],
  loader: 'url',
  query: {
    limit: 10000,
    name: 'static/media/[name].[hash:8].[ext]'
  }
},

{
  test: /\.less$/,
  loaders: [
    'style-loader',
    'css-loader?modules&importLoaders=1&localIdentName="[name]__[local]___[hash:base64:5]"',
    'postcss-loader',
    'less-loader'
  ]
},
</code>```

I want the compilation to be as fast (or nearly as fast) as before (when I didn't user the less loader)

Thanks in advance!

答:
I also started with the less loader but then read Dan Abramov's comment on adding css pre-prossesor and switched to his solution. Works really great - below is a link to the comment, but in short - you don't need to eject and change create-react-app default configuration - just add a file watcher that monitors and compiles your less files into css files and let webpack use these compiled css files. No changes to config required!

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-a-css-preprocessor-sass-less-etc.

Title: create-react-app node-less compilation

Body:
I'm using node-less compiler with my create-react-app webpack config in order to compile my less files. The compilation is EXTREMELY slow and takes nearly 5-8 secs for every file change.

Here's a part of my webpack config that specifies less compilation:

{
  exclude: [
    /\.html$/,
    /\.(js|jsx)$/,
    /\.css$/,
    /\.json$/,
    /\.svg$/,
    /\.less$/
  ],
  loader: 'url',
  query: {
    limit: 10000,
    name: 'static/media/[name].[hash:8].[ext]'
  }
},

{
  test: /\.less$/,
  loaders: [
    'style-loader',
    'css-loader?modules&importLoaders=1&localIdentName="[name]__[local]___[hash:base64:5]"',
    'postcss-loader',
    'less-loader'
  ]
},

I want the compilation to be as fast (or nearly as fast) as before (when I didn't user the less loader)

Thanks in advance!


问:
How to debug project with makefile
I'm a newbie both in makefiles and in projects using multiple files. What I'm working on now has one main.c and two user libraries. Here's the makefile:

```<code>CC = gcc
OBJECTS = main.o path.o util.o

9_1 : $(OBJECTS)
    $(CC) -g $(OBJECTS) -o 9_1

main.o : main.c path.h util.h
    $(CC) -g -c main.c path.h util.h
path.o : path.c path.h util.h
    $(CC) -g -c path.c path.h util.h
util.o : util.c util.h
    $(CC) -g -c util.c util.h

.PHONY : clean
clean :
    rm $(OBJECTS)
</code>```

I'd like to be able to debug this project in Emacs (using the multiple-windows variable) however when I run gdb -i=mi 9_1 (the default option) and try to add breakpoints in main.c it doesn't let me. Specifically: I run b main.c:25 and I get

```<code>No symbol table is loaded. Use the "file" command.
Breakpoint 1 (main.c:25) pending
</code>```

What should I do?

答:
It happened because

you already built your objects/executable without the -g flag

you added the -g flag afterwards

Adding an option in the makefile doesn't automatically trigger a recompilation. Since you have a clean target, just do

```<code>make clean
make
</code>```

and the objects are rebuilt with the -g option: executable is produced with symbols now. Happy debugging.

Aside: don't pass header files to the gcc command. They're useful so make knows the dependencies (in the line above) but not when building the object from the .c file. Doing so creates useless .o files.

Title: How to debug project with makefile

Body:
I'm a newbie both in makefiles and in projects using multiple files. What I'm working on now has one main.c and two user libraries. Here's the makefile:

CC = gcc
OBJECTS = main.o path.o util.o

9_1 : $(OBJECTS)
    $(CC) -g $(OBJECTS) -o 9_1

main.o : main.c path.h util.h
    $(CC) -g -c main.c path.h util.h
path.o : path.c path.h util.h
    $(CC) -g -c path.c path.h util.h
util.o : util.c util.h
    $(CC) -g -c util.c util.h

.PHONY : clean
clean :
    rm $(OBJECTS)

I'd like to be able to debug this project in Emacs (using the multiple-windows variable) however when I run gdb -i=mi 9_1 (the default option) and try to add breakpoints in main.c it doesn't let me. Specifically: I run b main.c:25 and I get

No symbol table is loaded. Use the "file" command.
Breakpoint 1 (main.c:25) pending

What should I do?

Body:
It happened because

you already built your objects/executable without the -g flag

you added the -g flag afterwards

Adding an option in the makefile doesn't automatically trigger a recompilation. Since you have a clean target, just do

make clean
make

and the objects are rebuilt with the -g option: executable is produced with symbols now. Happy debugging.

Aside: don't pass header files to the gcc command. They're useful so make knows the dependencies (in the line above) but not when building the object from the .c file. Doing so creates useless .o files.


问:
Calculated measure which returns average number of site key per day
I am trying to create a calculated measure which  returns average number of site keys per day.

Fact table looks like below.

Formula for measure is sum of number of distinct keys of each day divided by number of days for that month..

Calculated Measure = SUM(Distinct Keys of Day1, Distinct Keys of Day2,....Distinct Keys of last day of month)/ Number of days of month.

Any suggestion is appreciated and Thanks in Advance.

答:
From my point of view your calculated member will be something like:</p>

```<code>SET [Used Keys] AS
  NONEMPTY([Key].[Key].[Key], [Measures].[Count])
MEMBER [AVG Keys] AS
  AVG(
    [Date].[Month].&[2017-01].Children,
    DistinctCount([Used Keys])
)
</code>```

Body:
From my point of view your calculated member will be something like:

SET [Used Keys] AS
  NONEMPTY([Key].[Key].[Key], [Measures].[Count])
MEMBER [AVG Keys] AS
  AVG(
    [Date].[Month].&[2017-01].Children,
    DistinctCount([Used Keys])
)


问:
how to fetch a variable outside of the observable in Angular
I have an Observable which has an array. I want to fetch that array outside of the Observable so that I can merge it with another array.

```<code>    this.builderService.getCommercialData()
     .subscribe(
       data=>{
        this.commercialDetails = data;
        this.commercialDetailsArray.push(this.commercialDetails);

       console.log(this.commercialDetailsArray);
       this.newcommercialDetailsArray =
                             this.commercialDetailsArray[0];
       const arrayLength = this.commercialDetailsArray.length;
         if (arrayLength < 1) {
          this.loaderStatus = false;
          this.dataLoaded = false;
          this.noData = true;
          } else {
            this.loaderStatus = false;
            this.dataLoaded = true;
            this.noData = false;
          }
        },
      error=>{},
     );
</code>```

I want to fetch newcommercialDetailsArray

答:
I have done it using Angular 2

ts file

```<code> ngOnInit() {

       this._basicService.getBasic().subscribe(
       data => {

           this.basicResponse = data;

           console.log(this.basicResponse);

           return this.basicResponse;

    }
  )
  }
</code>```

I have get the data from service and put into basicResponse and just return the data from subscribe function console it to another onclick function to check that basicResponse if coming or not.

```<code> save()
     {
       console.log(this.basicResponse)
    }
</code>```

Just return the values.It worked for me

Body:
I have an Observable which has an array. I want to fetch that array outside of the Observable so that I can merge it with another array.

    this.builderService.getCommercialData()
     .subscribe(
       data=>{
        this.commercialDetails = data;
        this.commercialDetailsArray.push(this.commercialDetails);

       console.log(this.commercialDetailsArray);
       this.newcommercialDetailsArray =
                             this.commercialDetailsArray[0];
       const arrayLength = this.commercialDetailsArray.length;
         if (arrayLength < 1) {
          this.loaderStatus = false;
          this.dataLoaded = false;
          this.noData = true;
          } else {
            this.loaderStatus = false;
            this.dataLoaded = true;
            this.noData = false;
          }
        },
      error=>{},
     );

I want to fetch newcommercialDetailsArray

Body:
I have done it using Angular 2

ts file

 ngOnInit() {

       this._basicService.getBasic().subscribe(
       data => {

           this.basicResponse = data;

           console.log(this.basicResponse);

           return this.basicResponse;

    }
  )
  }

I have get the data from service and put into basicResponse and just return the data from subscribe function console it to another onclick function to check that basicResponse if coming or not.

 save()
     {
       console.log(this.basicResponse)
    }

Just return the values.It worked for me


问:
What is purpose of @ConditionalOnProperty annotation?
I just modified spring boot configuration, and encountered

```<code>@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
</code>```

from org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration

```<code>@Bean(name = { "connect/twitterConnect", "connect/twitterConnected" })
@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
public View twitterConnectView() {
    return new GenericConnectionStatusView("twitter", "Twitter");
}
</code>```

I don't understand purpose of this annotation. I guess this might be enable to use bean only if property  value exist(e.g. "spring.social", "auto-connection-views").

答:
In case you are using this property on TYPE-level, i.e. on one of your @Configuration classes... Keep in mind that in such case the annotation is evaluated/checked against the default properties file, i.e. application.properties

@ConditionalOnProperty on TYPE level w/ @Configuration

Body:
I just modified spring boot configuration, and encountered

@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")

from org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration

@Bean(name = { "connect/twitterConnect", "connect/twitterConnected" })
@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
public View twitterConnectView() {
    return new GenericConnectionStatusView("twitter", "Twitter");
}

I don't understand purpose of this annotation. I guess this might be enable to use bean only if property  value exist(e.g. "spring.social", "auto-connection-views").


问:
How do I return a specific cell value in SlickGrid?
For the life of me I can't seem to return a specific cell value in SlickGrid.  There is an example on SO here. But this did not work either.  I am using the SlickGrid tutorial #7 as my example.  All I am trying to do is add a click event to a cell that returns that cells value.

Note: I am loading my data via JSON request and all works well.  My click event fires but the value is undefined.  For brevity sake I will omit my grid columns and options code.  Here is the code and thanks.  All and all this is a great grid.

```<code>var sortcol = "id";
    var sortdir = -1;
    $(function () {
        $.getJSON(baseURL() + 'programs', function (data) {
            dataView = new Slick.Data.DataView();
            grid = new Slick.Grid($("#program-grid"), data, programColumns, programOptions);

            grid.onSort = function (sortCol, sortAsc) {
                sortdir = sortAsc ? 1 : -1;
                sortcol = sortCol.field;

                if (sortAsc == true) {
                    data.sort(compare);
                }
                else {
                    data.reverse(compare);
                }
                grid.render();
            };
            grid.onClick = function (e, row, cell) {
                if (programColumns[cell].id == "id") {
                    var x = data[row][cell].field;//This is where I am stuck
                    window.location.href = "http://google.com/" + x;
                }
            }

        });
    });
</code>```

答: You are almost there, you should use data[row].fieldname. Do you have a field in your data called "field"?</p>

ContentLicense: CC BY-SA 2.5

Body:
For the life of me I can't seem to return a specific cell value in SlickGrid.  There is an example on SO here. But this did not work either.  I am using the SlickGrid tutorial #7 as my example.  All I am trying to do is add a click event to a cell that returns that cells value.

Note: I am loading my data via JSON request and all works well.  My click event fires but the value is undefined.  For brevity sake I will omit my grid columns and options code.  Here is the code and thanks.  All and all this is a great grid.

var sortcol = "id";
    var sortdir = -1;
    $(function () {
        $.getJSON(baseURL() + 'programs', function (data) {
            dataView = new Slick.Data.DataView();
            grid = new Slick.Grid($("#program-grid"), data, programColumns, programOptions);

            grid.onSort = function (sortCol, sortAsc) {
                sortdir = sortAsc ? 1 : -1;
                sortcol = sortCol.field;

                if (sortAsc == true) {
                    data.sort(compare);
                }
                else {
                    data.reverse(compare);
                }
                grid.render();
            };
            grid.onClick = function (e, row, cell) {
                if (programColumns[cell].id == "id") {
                    var x = data[row][cell].field;//This is where I am stuck
                    window.location.href = "http://google.com/" + x;
                }
            }

        });
    });


问:
Netbeans - Oracle DB - AWS " amazon RDB " - java 8
I want to connect my java file to amazon oracle database.

DataSource.java

```<code>public class DataSource {

private static String dbName = System.getenv("PUBLIC");
private static String userName = System.getenv("root");
private static String password = System.getenv("3deemala7sas");
private static String hostname = System.getenv("oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com");
private static String port = System.getenv("1521");

public static final String JDBC_DRIVER = "oracle.jdbc.OracleDriver";
public static final String DB_URL = "jdbc:oracle:thin://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;

public static boolean checkDomain()
{
    if (System.getenv("oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com") != null) {
        return true;
    }
    return false;
}
</code>```

DbConnection.java

```<code>public static Connection getConnection( )
{

    try {
        Class.forName(DataSource.JDBC_DRIVER);
         connection = DriverManager.getConnection(DataSource.DB_URL);
        //connection = (Connection) DriverManager.getConnection(DataSource.DB_URL);

        System.out.println("Connected ....");

        return connection;
    }
     catch (SQLException ex) {
        System.out.println("Error syntax");
         System.out.println(ex.toString());
         ex.printStackTrace();
    }catch (ClassNotFoundException ex) {
        System.out.println("Class not found error ...");
    }

    return null;
}
</code>```

App01.java

```<code>public class App01 {

public static void main(String[] args) throws SQLException {
    Connection connection = null ;
    System.out.println(DataSource.checkDomain());
   connection =  DbConnection.getConnection();

}}
</code>```

Exception

java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection

Note: I have connected successfully using dbvisualizer, also tried to use neatbeas database services and it is not connecting too

Netbeans error : Cannot establish a connection to jdbc:oracle:thin:@oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com:1521:XE using oracle.jdbc.OracleDriver (Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
 )

答:
Thanks for answering my question.

I have figure it out. The mistake was in the URL to connect to db as u mentioned. So, what found is that the url should be like this :-

```<code>Connection con = DriverManager.getConnection("jdbc:oracle:thin:@"+hostname+":1521:orcl", "username", "password");
</code>```

ORCL is the defualt db name for AWS ( AMAZON cloud )

Thanks

Body:
I want to connect my java file to amazon oracle database.

DataSource.java

public class DataSource {

private static String dbName = System.getenv("PUBLIC");
private static String userName = System.getenv("root");
private static String password = System.getenv("3deemala7sas");
private static String hostname = System.getenv("oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com");
private static String port = System.getenv("1521");

public static final String JDBC_DRIVER = "oracle.jdbc.OracleDriver";
public static final String DB_URL = "jdbc:oracle:thin://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;

public static boolean checkDomain()
{
    if (System.getenv("oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com") != null) {
        return true;
    }
    return false;
}

DbConnection.java

public static Connection getConnection( )
{

    try {
        Class.forName(DataSource.JDBC_DRIVER);
         connection = DriverManager.getConnection(DataSource.DB_URL);
        //connection = (Connection) DriverManager.getConnection(DataSource.DB_URL);

        System.out.println("Connected ....");

        return connection;
    }
     catch (SQLException ex) {
        System.out.println("Error syntax");
         System.out.println(ex.toString());
         ex.printStackTrace();
    }catch (ClassNotFoundException ex) {
        System.out.println("Class not found error ...");
    }

    return null;
}

App01.java

public class App01 {

public static void main(String[] args) throws SQLException {
    Connection connection = null ;
    System.out.println(DataSource.checkDomain());
   connection =  DbConnection.getConnection();

}}

Exception

java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection

Note: I have connected successfully using dbvisualizer, also tried to use neatbeas database services and it is not connecting too

Netbeans error : Cannot establish a connection to jdbc:oracle:thin:@oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com:1521:XE using oracle.jdbc.OracleDriver (Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
 )

Body:
Thanks for answering my question.

I have figure it out. The mistake was in the URL to connect to db as u mentioned. So, what found is that the url should be like this :-

Connection con = DriverManager.getConnection("jdbc:oracle:thin:@"+hostname+":1521:orcl", "username", "password");

ORCL is the defualt db name for AWS ( AMAZON cloud )

Thanks


问:
How to exclude calling class in JGroups RpcDispatcher calls
I want a single class to invoke the same method in multiple other classes, without trying to do so on itself.

For example, RpcDispatcher calling rsp_list = disp.callRemoteMethods(null, "print", new Object[]{10}, new Class[]{int.class}, opts); should not try and invoke print on itself, only the other channel members.

答: You could use an exclusion list in RequestOptions passed to the call, or use TransientFlag.DONT_LOOPBACK (preferred, as more efficient). The transient flag is also set in RequestOptions.


问:
How to get user information from ldap?
I am using apache shiro for ldap authentification:

```<code>Factory<SecurityManager> ldapFactory = new IniSecurityManagerFactory("classpath:active.ini");
SecurityManager sManager = ldapFactory.getInstance();
SecurityUtils.setSecurityManager(sManager);

Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
            try {
                currentUser.login(token);
            } catch (UnknownAccountException ex) {
                logger.info("Unknown user");
            } catch (IncorrectCredentialsException ex) {
                logger.info("Incorrect credentials");
            } catch (LockedAccountException ex) {
                logger.info("Account is Locked");
            } catch (AuthenticationException ex) {
                logger.info("Authentication Exception");
            }
        }

        logger.info("User [" + currentUser.getPrincipal() +"] logged succesfully");
        currentUser.logout();
</code>```

Calling currentUser.getPrincipal(), I've got only email address from the logged user.

How to get more user information, for example lastname, firstname, etc?

答:
You could extend the LDAP Realm. and add more context to Principal/PrincipalCollection (or return a custom object or your Principal)

This is an old thread, but I find myself digging it up every once and a while and covers this topic (It mentions JSecurity which is the original project name for Shiro).

Title: How to get user information from ldap?

Body:
I am using apache shiro for ldap authentification:

Factory<SecurityManager> ldapFactory = new IniSecurityManagerFactory("classpath:active.ini");
SecurityManager sManager = ldapFactory.getInstance();
SecurityUtils.setSecurityManager(sManager);

Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
            try {
                currentUser.login(token);
            } catch (UnknownAccountException ex) {
                logger.info("Unknown user");
            } catch (IncorrectCredentialsException ex) {
                logger.info("Incorrect credentials");
            } catch (LockedAccountException ex) {
                logger.info("Account is Locked");
            } catch (AuthenticationException ex) {
                logger.info("Authentication Exception");
            }
        }

        logger.info("User [" + currentUser.getPrincipal() +"] logged succesfully");
        currentUser.logout();

Calling currentUser.getPrincipal(), I've got only email address from the logged user.

How to get more user information, for example lastname, firstname, etc?


问:
Is there a way to install the package openjdk8 and to prevent perl to update on FreeBSD 9.2 ?
I am currently trying to find a way to install the package openjdk8 on a FreeBSD 9.2.
To do that I used :

sudo pkg install openjdk8

It worked without any problem. However, this has also updated the perl package to the version 5.24. We have many scripts that work only with perl 5.16.3 so I would like to keep this version of perl.

I already tried to uninstall the perl 5.24 package and to reinstall perl 5.16.3 and it worked. So I am convinced openjdk doesn't really need to update this package. I already tried to lock the package perl 5.16.3 but openjdk8 refuse to install himself. I have this message :

perl 5.16.3 is locked and may not be modified

The installation ends and my package is not installed. Also, for specific reasons I don't want to use the port method. I absolutely want to use the pkg method.

So my question is this one : Is there a way to complete my installation of openjdk8 and to prohibit perl to update ?

Thanks for your help.

答:
I finally found an answer to my question. By installing my package offline, it installs the minimum of dependencies. It's not a very popular way to install packages on FreeBSD but it works very well.

Just follow this :

sudo pkg install -F openjdk8

This command allow you to just fetch your packages and its dependencies. Once it's done, you have to find the location of the packages you just fetched.

sudo find / -n *.txz -print

For me the result was

/var/cache/pkg/openjdk8-8.112.16_1-1baeb24a94.txz

Then I go to this directory with :

cd /var/cache/pkg

Now you just have to use :

sudo pkg-static add openjdk8

That's all. It will extract the package and the minimum of dependencies.


问:
How can i send request with SyncHttpClient from fragment?
This is my code to request to server..

```<code>    final SyncHttpClient client = new SyncHttpClient();

    RequestParams params = new RequestParams();
    params.put("product[name]", name);
    params.put("product[price]", price);

    client.post(context,Config.URL_GET_ALL_PRODUCT, params, new AsyncHttpResponseHandler() {
        @Override
        public void onStart() {

            super.onStart();
            setUseSynchronousMode(true);
        }
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            try {
                JSONObject eventResult = new JSONObject(result);

                String id = eventResult.getString("id");
                // Check for error node in json
                if (id != null || id != "" ) {
                    Toast.makeText(context,
                            "New Product Added", Toast.LENGTH_LONG).show();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = eventResult.getString("error_msg");
                    Toast.makeText(context,
                            errorMsg, Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            System.out.println(error.getMessage());
        }
    });
}
</code>```

And this is my code to call the method in Fragment

```<code> ProductController.addProduct(getContext().getApplicationContext(), nameProduct, priceProduct);
</code>```

Error for this code

Unhandled exception origin cause
android.os.NetworkOnMainThreadException
 at com.project.roy.interview.Control.ProductController.addProduct(ProductController.java:102)
at com.project.roy.interview.Fragment.FragmentAddProduct$1.onClick(FragmentAddProduct.java:38

答:
In the documentation of this library its written:

Processes http requests in synchronous mode, so your caller thread
  will be blocked on each request

On Android you may not block the main thread, thats where your Exception comes from.

Either use an AsyncTask, or execute this code inside a separate thread.

Body:
This is my code to request to server..

    final SyncHttpClient client = new SyncHttpClient();

    RequestParams params = new RequestParams();
    params.put("product[name]", name);
    params.put("product[price]", price);

    client.post(context,Config.URL_GET_ALL_PRODUCT, params, new AsyncHttpResponseHandler() {
        @Override
        public void onStart() {

            super.onStart();
            setUseSynchronousMode(true);
        }
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            try {
                JSONObject eventResult = new JSONObject(result);

                String id = eventResult.getString("id");
                // Check for error node in json
                if (id != null || id != "" ) {
                    Toast.makeText(context,
                            "New Product Added", Toast.LENGTH_LONG).show();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = eventResult.getString("error_msg");
                    Toast.makeText(context,
                            errorMsg, Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            System.out.println(error.getMessage());
        }
    });
}

And this is my code to call the method in Fragment

 ProductController.addProduct(getContext().getApplicationContext(), nameProduct, priceProduct);

Error for this code

Unhandled exception origin cause
android.os.NetworkOnMainThreadException
 at com.project.roy.interview.Control.ProductController.addProduct(ProductController.java:102)
at com.project.roy.interview.Fragment.FragmentAddProduct$1.onClick(FragmentAddProduct.java:38


问:
get turkish chars from string
i wish to write a string in reverse order , i  get string with cin and iterating it via for loop from strings length to 0. Problem is when i take turkish char it writes wrongly and also 1 turkish char increases strings length by 2 (i.e. ömür has length 6)

```<code>string text = "ömür";
for ( int i = text.length() ; i >= 0; i--)
{
    if(!isspace(text[i]) && text[i] != '\0')
    {
        cout<<text[i];
    }
}
</code>```

expected output = rümö =>
what i get = r??m??

答:
The problem is that nowdays, non ASCII characters take up more than one byte (C++ char). Your best bet is to use a library such as ICU that will sort out the Unicode stuff for you. You could then do:

```<code>#include <unicode/unistr.h>
#include <unicode/ustream.h>
#include <iostream>

int
main(int argc, char **argv)
{
    icu::UnicodeString text("ömür");
    text.reverse();
    std::cout << text;
}
</code>```

Title: get turkish chars from string

Body:
i wish to write a string in reverse order , i  get string with cin and iterating it via for loop from strings length to 0. Problem is when i take turkish char it writes wrongly and also 1 turkish char increases strings length by 2 (i.e. ömür has length 6)

string text = "ömür";
for ( int i = text.length() ; i >= 0; i--)
{
    if(!isspace(text[i]) && text[i] != '\0')
    {
        cout<<text[i];
    }
}

expected output = rümö =>
what i get = r??m??

Body:
The problem is that nowdays, non ASCII characters take up more than one byte (C++ char). Your best bet is to use a library such as ICU that will sort out the Unicode stuff for you. You could then do:

#include <unicode/unistr.h>
#include <unicode/ustream.h>
#include <iostream>

int
main(int argc, char **argv)
{
    icu::UnicodeString text("ömür");
    text.reverse();
    std::cout << text;
}


问:
Process.Equals() doesn't work
```<code>if (Process.Equals(Process.GetCurrentProcess(), Process.GetCurrentProcess()))
            Console.WriteLine("i am the same as my self");
        else
            Console.WriteLine("i am not the same as my self");
        Console.ReadKey();
</code>```

it prints "i am not the same as my self"

what is the problem ?

and how i can use the Equals(Object a, Object b) Function ?, any examples please ?

答:
Process doesn't override the Equals method, so the one from it's base class System.Object is used which just compares references. It seems Process.GetCurrentProcess() returns always new instances which means they are not the same reference.

The documentation mentions it already:

Gets a new Process component and associates it with the currently
  active process.....
  Use this method to create a new Process instance and associate it with the process resource on the local computer.

if you look at it's source you see new Process(...)(read new-operator):

```<code>public static Process GetCurrentProcess() {
    return new Process(".", false, NativeMethods.GetCurrentProcessId(), null);
}
</code>```

If you want to check if two process instances are equal, you could write a custom comparer:

```<code>public class ProcessIdComparer : IEqualityComparer<System.Diagnostics.Process>
{
    public bool Equals(Process x, Process y)
    {
        if (x == null && y == null) return true;
        if (x == null || y == null) return false;
        return x.Id == y.Id;
    }

    public int GetHashCode(Process obj)
    {
        return obj?.Id.GetHashCode() ?? 0;
    }
}
</code>```

Now you can check if both have the same ID:

```<code>Process p1 = Process.GetCurrentProcess();
Process p2 = Process.GetCurrentProcess();

bool equalProcesses = new ProcessIdComparer().Equals(p1, p2); // true
</code>```

Title: Process.Equals() doesn't work

Body:
if (Process.Equals(Process.GetCurrentProcess(), Process.GetCurrentProcess()))
            Console.WriteLine("i am the same as my self");
        else
            Console.WriteLine("i am not the same as my self");
        Console.ReadKey();

it prints "i am not the same as my self"

what is the problem ?

and how i can use the Equals(Object a, Object b) Function ?, any examples please ?

Body:
Process doesn't override the Equals method, so the one from it's base class System.Object is used which just compares references. It seems Process.GetCurrentProcess() returns always new instances which means they are not the same reference.

The documentation mentions it already:

Gets a new Process component and associates it with the currently
  active process.....
  Use this method to create a new Process instance and associate it with the process resource on the local computer.

if you look at it's source you see new Process(...)(read new-operator):

public static Process GetCurrentProcess() {
    return new Process(".", false, NativeMethods.GetCurrentProcessId(), null);
}

If you want to check if two process instances are equal, you could write a custom comparer:

public class ProcessIdComparer : IEqualityComparer<System.Diagnostics.Process>
{
    public bool Equals(Process x, Process y)
    {
        if (x == null && y == null) return true;
        if (x == null || y == null) return false;
        return x.Id == y.Id;
    }

    public int GetHashCode(Process obj)
    {
        return obj?.Id.GetHashCode() ?? 0;
    }
}

Now you can check if both have the same ID:

Process p1 = Process.GetCurrentProcess();
Process p2 = Process.GetCurrentProcess();

bool equalProcesses = new ProcessIdComparer().Equals(p1, p2); // true


问:
Is that possible to put Template7 code in a separate file rather than in html
I am using a framework called Framework7.

In my index.html, I have some Template7 code, like this format

```<code><script type="text/template7" id="commentsTemplate">
    {{#each this}}
    <div> test this template 7 code </div>
</script>
</code>```

However, I want to have this part of code into an another separated file (Just like I can have many other *.js files in, say, a static folder and refer to the file by "static/*.js).

I have tried to use a typical way to import js

```<code><script type="text/template7" id="storiesTemplate" src="js/template.js"></script>
</code>```

But it doesn't work, there is also no demo/sample code in the documentation.

Any help is appreciated!

答:
How about lazy loading and inserting through the prescriptions?

```<code>    (function (Template7) {
    "use strict";
    window.templater = new function(){
        var cache = {};

        var self = this;

        this.load = function(url)
        {
            return new Promise(function(resolve,reject)
            {
                if(cache[url]){
                    resolve(cache[url]);
                    return true;
                }

                if(url in Template7.templates){
                    resolve(Template7.templates[url]);
                    return true;
                }

                var xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                xhr.onload = function() {
                    if(this.status == 200 && this.response.search('<!DOCTYPE html>') == -1){
                        cache[url] = Template7.compile(this.response);
                        resolve(cache[url]);
                    }else{
                        reject(`Template ${url} not found`);
                    }
                };
                xhr.send();
            })
        }

        this.render = function(url, data)
        {
            return self.load(url)
                .then(function(tpl){
                    return tpl(data) ;
                });
        }

        this.getCache = function()
        {
            return cache;
        }

    }
})(Template7);
</code>```

Using :

```<code>templater.render('tpl.html').then((res)=>{ //res string })
</code>```

Or    :

```<code>templater.load('tpl.html').then( tpl => { Dom7('.selector').html( tpl(data) ) } )
</code>```

Body:
I am using a framework called Framework7.

In my index.html, I have some Template7 code, like this format

However, I want to have this part of code into an another separated file (Just like I can have many other *.js files in, say, a static folder and refer to the file by "static/*.js).

I have tried to use a typical way to import js

But it doesn't work, there is also no demo/sample code in the documentation.

Any help is appreciated!

Body:
How about lazy loading and inserting through the prescriptions?

    (function (Template7) {
    "use strict";
    window.templater = new function(){
        var cache = {};

        var self = this;

        this.load = function(url)
        {
            return new Promise(function(resolve,reject)
            {
                if(cache[url]){
                    resolve(cache[url]);
                    return true;
                }

                if(url in Template7.templates){
                    resolve(Template7.templates[url]);
                    return true;
                }

                var xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                xhr.onload = function() {
                    if(this.status == 200 && this.response.search('<!DOCTYPE html>') == -1){
                        cache[url] = Template7.compile(this.response);
                        resolve(cache[url]);
                    }else{
                        reject(`Template ${url} not found`);
                    }
                };
                xhr.send();
            })
        }

        this.render = function(url, data)
        {
            return self.load(url)
                .then(function(tpl){
                    return tpl(data) ;
                });
        }

        this.getCache = function()
        {
            return cache;
        }

    }
})(Template7);

Using :

templater.render('tpl.html').then((res)=>{ //res string })

Or    :

templater.load('tpl.html').then( tpl => { Dom7('.selector').html( tpl(data) ) } )


答:
Classes are not required to provide an equality definition. The Equals you're looking at here is object.Equals(object,object), and it so happens that Process does not override this. So what you are testing is reference equality.

You have two different object instances - that represent the same OS process. To see if they represent the same OS process: compare the process id (the Id property of the Process instance).

Title: Process.Equals() doesn't work


问:
How can I pass some Data from another activity android
I'm trying to pass some data from one activity to another in my android app, however some errors occur when I try to run the code.
I'm passing data this way:

```<code> Intent pod= new Intent(ACTION_NAME);
 Bundle extras = new Bundle();
 extras.putString("nume", NUME_VAL);
 extras.putString("prenume", PRENUME_VAL);
 startActivity(pod);
</code>```

And recive this:

```<code>public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Bundle data = getIntent().getExtras();
     String nume = data.getStringExtra("nume");
     String prenume = data.getStringExtra("prenume");
}
</code>```

答:
Use this

```<code> Intent pod= new Intent(YourActivity.this,OtherActivity.class);
 Bundle extras = new Bundle();
 extras.putString("nume", NUME_VAL);
 extras.putString("prenume", PRENUME_VAL);
 pod.putExtras(extras);
 startActivity(pod);
</code>```

instead of this

```<code> Intent pod= new Intent(ACTION_NAME);
</code>```

Body:
I'm trying to pass some data from one activity to another in my android app, however some errors occur when I try to run the code.
I'm passing data this way:

 Intent pod= new Intent(ACTION_NAME);
 Bundle extras = new Bundle();
 extras.putString("nume", NUME_VAL);
 extras.putString("prenume", PRENUME_VAL);
 startActivity(pod);

And recive this:

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Bundle data = getIntent().getExtras();
     String nume = data.getStringExtra("nume");
     String prenume = data.getStringExtra("prenume");
}

Body:
Use this

 Intent pod= new Intent(YourActivity.this,OtherActivity.class);
 Bundle extras = new Bundle();
 extras.putString("nume", NUME_VAL);
 extras.putString("prenume", PRENUME_VAL);
 pod.putExtras(extras);
 startActivity(pod);

instead of this

 Intent pod= new Intent(ACTION_NAME);


问:
Change default MSSQL datasource for connection string
When executing integration tests, I'm using a connection string to connect to the database. I know there is a default notation for connecting to the default server instance in a connection string:

data source=.;initial catalog=[database name];integrated security=SSPI;

Unfortunately the database is currently not installed on the default server and due to compatibility issues I am unable to change to the default server. Now for all my tests, I will have to assign the sever name like so:

data source=[My Server name] ;initial catalog=[database name];integrated security=SSPI;

Since the solution is shared, I can't check this configuration in, and I'll have to do a lot of manual maintenance for this.

Is there any way I can change the default SQL Server for my PC, so that I can use the connection string as shown in the first example?

EDIT:

I was able to successfully use the following connection string:

data source=.\SQLEXPRESS;initial catalog=[database name];integrated security=SSPI;

EDIT 2:

I was able to resolve my issue by this awnser

答:
I managed to resolve the issue by following the steps in this post:
https://stackoverflow.com/a/11921896/1829773</p>


问:
org.apache.storm.multilang.NoOutputException: Pipe to subprocess seems to be broken! python: can't open file [Errno 2] No such file or directory
Whenever I try to run my storm topology locally I get the following

error:
java.lang.RuntimeException: org.apache.storm.multilang.NoOutputException: Pipe to subprocess seems to be broken! No output read.
Serializer Exception:
python: can't open file 'parser_bolt.py': [Errno 2] No such file or directory

I have searched everywhere on the internet but not able to resolve this issue. I can see the respective python file in the resources folder when I unzip the compiled jar but somehow when deploying the jar its unable to find the python files from the topology.

答:
I too had the same error with a Python bolt that I created.  My issue was I forgot to call run on the class at the bottom of the Python code.  Example code below.

```<code>import storm

class TestStuff(storm.BasicBolt)

     def initialize(self,conf,context):
          self._conf = conf;
          self._context = context;

     def process(self, tuple):
          storm.logInfo("test")

TestStuff().run()
</code>```

The last line of the sample code is what I forgot to put in, thus causing the error.  Make sure you have that.

Body:
I too had the same error with a Python bolt that I created.  My issue was I forgot to call run on the class at the bottom of the Python code.  Example code below.

import storm

class TestStuff(storm.BasicBolt)

     def initialize(self,conf,context):
          self._conf = conf;
          self._context = context;

     def process(self, tuple):
          storm.logInfo("test")

TestStuff().run()

The last line of the sample code is what I forgot to put in, thus causing the error.  Make sure you have that.


问:
Hibernate insert into Database new records only
I am trying to write some object into the database, I wrote the following code which is working fine but the problem is that because I am using a while loop, hibernate is treating every object as a new record, which causing the database to be filled with already existed value

My question is, which annotation or technique that I can use to only write the new records (new object's value) into the database, without writing the same object again incase it was written before (Insert only if not exists)

Here is my code

```<code>public class Parser {
  public static void logParser() throws IOException {
    // Creating the configuration object
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");
    // Ccreating the session factory object
    SessionFactory factory = cfg.buildSessionFactory();
    String fileName = "example.txt";
    File logfile = new File("fileName");
    Scanner scanner = new Scanner(new File(fileName), "UTF-8");
    while (scanner.hasNext()) {
      String s = scanner.nextLine();
      if (s.startsWith("Start")) {
        String[] logArray = s.split("\\|");
         System.out.println(Arrays.toString(logArray));
        // here is the session object
        Session session = factory.openSession();
        // transaction
        Transaction t = session.beginTransaction();
        // here is where the object is being written into the DB
        NetGroup ng = new NetGroup();
        ng.setNetGroup(logArray[2]);
        session.persist(ng);
        session.saveOrUpdate(ng);
        t.commit();
        session.close();
        System.out.println("Successfully created an object and wrote its values into database ");
        System.out.println();
      }
    }
    scanner.close();
    System.out.println("Successfully updated the Data Base");
  }
  }
</code>```

答:
I think you can use the primary key concept there to remove the duplicacy of rows and use the saveOrUpdate method.

If we work with hibernate API there should be one PK in the class.

session.saveOrUpdate(ng);

That  above method check the record on the basis of primary key, if PK does not exists in the DB then it fire the insert query if exists then it update the same record rather than inserting new one.

```<code>public class NetGroup

{

private int primaryKeyId;

public int getprimaryKeyId() {
        return primaryKeyId;
    }

    public void setprimaryKeyId(int primaryKeyId) {
        this.primaryKeyId = primaryKeyId;
    }

}
</code>```

Body:
I am trying to write some object into the database, I wrote the following code which is working fine but the problem is that because I am using a while loop, hibernate is treating every object as a new record, which causing the database to be filled with already existed value

My question is, which annotation or technique that I can use to only write the new records (new object's value) into the database, without writing the same object again incase it was written before (Insert only if not exists)

Here is my code

public class Parser {
  public static void logParser() throws IOException {
    // Creating the configuration object
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");
    // Ccreating the session factory object
    SessionFactory factory = cfg.buildSessionFactory();
    String fileName = "example.txt";
    File logfile = new File("fileName");
    Scanner scanner = new Scanner(new File(fileName), "UTF-8");
    while (scanner.hasNext()) {
      String s = scanner.nextLine();
      if (s.startsWith("Start")) {
        String[] logArray = s.split("\\|");
         System.out.println(Arrays.toString(logArray));
        // here is the session object
        Session session = factory.openSession();
        // transaction
        Transaction t = session.beginTransaction();
        // here is where the object is being written into the DB
        NetGroup ng = new NetGroup();
        ng.setNetGroup(logArray[2]);
        session.persist(ng);
        session.saveOrUpdate(ng);
        t.commit();
        session.close();
        System.out.println("Successfully created an object and wrote its values into database ");
        System.out.println();
      }
    }
    scanner.close();
    System.out.println("Successfully updated the Data Base");
  }
  }

Body:
I think you can use the primary key concept there to remove the duplicacy of rows and use the saveOrUpdate method.

If we work with hibernate API there should be one PK in the class.

session.saveOrUpdate(ng);

That  above method check the record on the basis of primary key, if PK does not exists in the DB then it fire the insert query if exists then it update the same record rather than inserting new one.

public class NetGroup

{

private int primaryKeyId;

public int getprimaryKeyId() {
        return primaryKeyId;
    }

    public void setprimaryKeyId(int primaryKeyId) {
        this.primaryKeyId = primaryKeyId;
    }

}


问:
Python Gtk3, MessageDialog, default focused response after hiding dialog?
after destroying dialog we can create new one with default focused response using set_default_response method. but when we hide dialog instead of destroying, this method does not work. how can I do this ?

example

```<code>#dialog variable is a GtkMessage dialog.
dialog.run()
dialog.hide()
dialog.run() # default focus doesn't work when we run dialog again after hiding.
</code>```

Thanks.

Note: sorry for asking questions frequently

答: This does not happen because the dialog widget will keep its state. This is the expected behavior. If you destroy and create a new one, it will be initialized.</p>

Body:
after destroying dialog we can create new one with default focused response using set_default_response method. but when we hide dialog instead of destroying, this method does not work. how can I do this ?

example

#dialog variable is a GtkMessage dialog.
dialog.run()
dialog.hide()
dialog.run() # default focus doesn't work when we run dialog again after hiding.

Thanks.

Note: sorry for asking questions frequently


问:
Jackson, deserialize string into date
I have the following JSON property:

```<code>"created_at":"2017-12-08T10:56:01.000Z"
</code>```

I would like to deserialize the JSON document using Jackson into the following property:

```<code>@JsonProperty("created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-ddTHH:mm:ss.SSSZ")
private java.util.Date createdAt;
</code>```

but it fails with the following exception:

```<code>org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.domain.Product] and content type [application/json;charset=utf-8]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:119)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:986)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:969)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:717)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:671)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:587)
</code>```

What am I doing wrong and how to fix it?

答:
The issue is with the pattern part of JsonFormat.

Use "yyyy-MM-dd'T'HH:mm:ss.SSSZ" instead of "yyyy-MM-ddTHH:mm:ss.SSSZ".

"yyyy-MM-dd'T'HH:mm:ss.SSSZ" for "2017-12-08T13:50:07.811+0000"

"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" for "2017-12-08T13:49:42.128Z"

Title: Jackson, deserialize string into date

Body:
I have the following JSON property:

"created_at":"2017-12-08T10:56:01.000Z"

I would like to deserialize the JSON document using Jackson into the following property:

@JsonProperty("created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-ddTHH:mm:ss.SSSZ")
private java.util.Date createdAt;

but it fails with the following exception:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.domain.Product] and content type [application/json;charset=utf-8]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:119)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:986)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:969)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:717)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:671)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:587)

What am I doing wrong and how to fix it?


问:
JGroups RpcDispatcher calling method from another class
How can I get an RpcDispatcher to remotely invoke the methods of a different class? The examples I've seen online all seem to demonstrate how it works when they're all instances of the same class. E.g. this one from the JGroups manual works fine for me because you just start multiple instances of RpcDispatcherTest and they all contain the print(int) method.

So how excatly could I get said RpcDispatcherTest to invoke from another, separate JGroups class, e.g. something like the SimpleChat example (also from the JGroups manual).

I've tried asking RpcDispatcherTest to connect to the same channel as SimpleChat: channel.connect("ChatCluster");. They seem to register eachother, and you can see the updated view with the multiple classes running, but I've failed to get the RpcDispatcherTest to actually invoke a method from SimpleChat, even if I copy the exact same print(int) method into it.

答: When you create an RpcDispatcher, you pass in a channel and a server object as arguments. The latter is the instance on which the RPCs will get invoked. In the examples, it is this, but you can pass in any object that implements the methods you want to invoke.


问:
TypeError: iter() returned non-iterator of type 'Layer' for Python 3
This is in connection with my other question in GIS stackexchange.

Why does TypeError gets raised in Python 3 when in fact the same code being run in Python 2 gets executed with no errors?

Code:

```<code>net = nx.DiGraph()
print(path)
shp = ogr.Open(path)
for lyr in shp:
    print (type(lyr))
    print (lyr)
    fields = [x.GetName() for x in lyr.schema]
    print (lyr.schema)
    print(fields)
    for f in lyr:
        print(f)
</code>```

Error

File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/networkx/readwrite/nx_shp.py", line 81, in read_shp
      for f in lyr:
  TypeError: iter() returned non-iterator of type 'Layer'

答:
import networkx as nx
author = """Ben Reilly (benwreilly@gmail.com)"""
all = ['read_shp', 'write_shp']

[docs]def read_shp(path, simplify=True):
    """Generates a networkx.DiGraph from shapefiles. Point geometries are
    translated into nodes, lines into edges. Coordinate tuples are used as
    keys. Attributes are preserved, line geometries are simplified into start
    and end coordinates. Accepts a single shapefile or directory of many
    shapefiles.

```<code>"The Esri Shapefile or simply a shapefile is a popular geospatial vector
data format for geographic information systems software [1]_."

Parameters
----------
path : file or string
   File, directory, or filename to read.

simplify:  bool
    If ``True``, simplify line geometries to start and end coordinates.
    If ``False``, and line feature geometry has multiple segments, the
    non-geometric attributes for that feature will be repeated for each
    edge comprising that feature.

Returns
-------
G : NetworkX graph

Examples
--------
>>> G=nx.read_shp('test.shp') # doctest: +SKIP

References
----------
.. [1] http://en.wikipedia.org/wiki/Shapefile
"""
try:
    from osgeo import ogr
except ImportError:
    raise ImportError("read_shp requires OGR: http://www.gdal.org/")

if not isinstance(path, str):
    return

net = nx.DiGraph()
shp = ogr.Open(path)
for lyr in shp:
    fields = [x.GetName() for x in lyr.schema]
    for f in lyr:
        flddata = [f.GetField(f.GetFieldIndex(x)) for x in fields]
        g = f.geometry()
        attributes = dict(zip(fields, flddata))
        attributes["ShpName"] = lyr.GetName()
        if g.GetGeometryType() == 1:  # point
            net.add_node((g.GetPoint_2D(0)), attributes)
        if g.GetGeometryType() == 2:  # linestring
            last = g.GetPointCount() - 1
            if simplify:
                attributes["Wkb"] = g.ExportToWkb()
                attributes["Wkt"] = g.ExportToWkt()
                attributes["Json"] = g.ExportToJson()
                net.add_edge(g.GetPoint_2D(0), g.GetPoint_2D(last), attributes)
            else:
                # separate out each segment as individual edge
                for i in range(last):
                    pt1 = g.GetPoint_2D(i)
                    pt2 = g.GetPoint_2D(i + 1)
                    segment = ogr.Geometry(ogr.wkbLineString)
                    segment.AddPoint_2D(pt1[0], pt1[1])
                    segment.AddPoint_2D(pt2[0], pt2[1])
                    attributes["Wkb"] = segment.ExportToWkb()
                    attributes["Wkt"] = segment.ExportToWkt()
                    attributes["Json"] = segment.ExportToJson()
                    net.add_edge(pt1, pt2, attributes)

return net
</code>```

Body:
This is in connection with my other question in GIS stackexchange.

Why does TypeError gets raised in Python 3 when in fact the same code being run in Python 2 gets executed with no errors?

Code:

net = nx.DiGraph()
print(path)
shp = ogr.Open(path)
for lyr in shp:
    print (type(lyr))
    print (lyr)
    fields = [x.GetName() for x in lyr.schema]
    print (lyr.schema)
    print(fields)
    for f in lyr:
        print(f)

Error

File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/networkx/readwrite/nx_shp.py", line 81, in read_shp
      for f in lyr:
  TypeError: iter() returned non-iterator of type 'Layer'

Body:
import networkx as nx
author = """Ben Reilly (benwreilly@gmail.com)"""
all = ['read_shp', 'write_shp']

[docs]def read_shp(path, simplify=True):
    """Generates a networkx.DiGraph from shapefiles. Point geometries are
    translated into nodes, lines into edges. Coordinate tuples are used as
    keys. Attributes are preserved, line geometries are simplified into start
    and end coordinates. Accepts a single shapefile or directory of many
    shapefiles.

"The Esri Shapefile or simply a shapefile is a popular geospatial vector
data format for geographic information systems software [1]_."

Parameters
----------
path : file or string
   File, directory, or filename to read.

simplify:  bool
    If ``True``, simplify line geometries to start and end coordinates.
    If ``False``, and line feature geometry has multiple segments, the
    non-geometric attributes for that feature will be repeated for each
    edge comprising that feature.

Returns
-------
G : NetworkX graph

Examples
--------
>>> G=nx.read_shp('test.shp') # doctest: +SKIP

References
----------
.. [1] http://en.wikipedia.org/wiki/Shapefile
"""
try:
    from osgeo import ogr
except ImportError:
    raise ImportError("read_shp requires OGR: http://www.gdal.org/")

if not isinstance(path, str):
    return

net = nx.DiGraph()
shp = ogr.Open(path)
for lyr in shp:
    fields = [x.GetName() for x in lyr.schema]
    for f in lyr:
        flddata = [f.GetField(f.GetFieldIndex(x)) for x in fields]
        g = f.geometry()
        attributes = dict(zip(fields, flddata))
        attributes["ShpName"] = lyr.GetName()
        if g.GetGeometryType() == 1:  # point
            net.add_node((g.GetPoint_2D(0)), attributes)
        if g.GetGeometryType() == 2:  # linestring
            last = g.GetPointCount() - 1
            if simplify:
                attributes["Wkb"] = g.ExportToWkb()
                attributes["Wkt"] = g.ExportToWkt()
                attributes["Json"] = g.ExportToJson()
                net.add_edge(g.GetPoint_2D(0), g.GetPoint_2D(last), attributes)
            else:
                # separate out each segment as individual edge
                for i in range(last):
                    pt1 = g.GetPoint_2D(i)
                    pt2 = g.GetPoint_2D(i + 1)
                    segment = ogr.Geometry(ogr.wkbLineString)
                    segment.AddPoint_2D(pt1[0], pt1[1])
                    segment.AddPoint_2D(pt2[0], pt2[1])
                    attributes["Wkb"] = segment.ExportToWkb()
                    attributes["Wkt"] = segment.ExportToWkt()
                    attributes["Json"] = segment.ExportToJson()
                    net.add_edge(pt1, pt2, attributes)

return net