问:
How to set State when value is derived from Array in React App
I have a react App, which renders a table from an array in the state.

I am trying to have an "EDIT MODE" which transforms some fields into textbox's so that I can update each row in the table.

I'm not sure how I can handle the onChange event when the value is derived from an element inside an array in the state.
here is my code, I have explained the problem in the comments:

```<code>class AddProjectType extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editMode: false
        }
        this.changeEditMode = this.changeEditMode.bind(this);         //Bind This so I can use this.setState
        this.changeProjectName = this.changeProjectName.bind(this);   //Bind This so I can use this.setState

    }
    componentDidMount() {
        this.props.fetchProjectTypes();      //This fetched the table from the nodejs server
    }
    changeEditMode() {
        this.setState({ editMode: !this.state.editMode });    //Convert into edit mode and change rows in the table to inputs
    }
    changeProjectName(event){
        //this.setState - Unsure how to set state of a particular array HERE IS THE PROBLEM
    }

    render() {
        if (!this.props.projectTypes) {
            return (
                <CenterLoader />   //loading the table from server - show loader
            )
        }
        else
            return (
                <div className="container">
                    <table className="ProjectType-Table">
                        <tbody>
                            <tr>
                                <th>
                                    Id
                                </th>
                                <th>
                                    Project Type
                                </th>
                                <th>

                                </th>
                            </tr>
                            {this.props.projectTypes.map((projectType, i) => {    //RENDER ALL ROWS
                                return (
                                    <tr key={i}>
                                        <td>
                                            {projectType._id}
                                        </td>
                                        <td>
                                            {this.state.editMode ?
                                                <input type="text" className="browser-default" defaultValue={projectType.name} onChange={this.changeProjectName}/>  //On change, I need to save back to the state this value
                                                :
                                                projectType.name
                                            }
                                        </td>
                                        <td>
                                            <button className="btn btn-small mr-1" onClick={this.changeEditMode}>Edit</button>
                                            <button className="btn btn-small">Delete</button>
                                        </td>
                                    </tr>

                                )
                            }
                            )}
                        </tbody>
                    </table>
                </div>
            );
    }

}

function mapStateToProps(state) {
    return { projectTypes: state.quizz.projectTypes };
}

export default connect(mapStateToProps, actions)(AddProjectType);
</code>```

答:
Attach data-idx={i} in the input like this,

```<code><input type="text" className="browser-default" defaultValue={projectType.name} onChange={this.changeProjectName} data-idx={i}/>
</code>```

In your changeProjectName(event) handler,

```<code>var index = event.target.dataset.idx; // Here you will get index
</code>```

Body:
I have a react App, which renders a table from an array in the state.

I am trying to have an "EDIT MODE" which transforms some fields into textbox's so that I can update each row in the table.

I'm not sure how I can handle the onChange event when the value is derived from an element inside an array in the state.
here is my code, I have explained the problem in the comments:

class AddProjectType extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editMode: false
        }
        this.changeEditMode = this.changeEditMode.bind(this);         //Bind This so I can use this.setState
        this.changeProjectName = this.changeProjectName.bind(this);   //Bind This so I can use this.setState

    }
    componentDidMount() {
        this.props.fetchProjectTypes();      //This fetched the table from the nodejs server
    }
    changeEditMode() {
        this.setState({ editMode: !this.state.editMode });    //Convert into edit mode and change rows in the table to inputs
    }
    changeProjectName(event){
        //this.setState - Unsure how to set state of a particular array HERE IS THE PROBLEM
    }

    render() {
        if (!this.props.projectTypes) {
            return (
                <CenterLoader />   //loading the table from server - show loader
            )
        }
        else
            return (

                                    Id

                                    Project Type

                            {this.props.projectTypes.map((projectType, i) => {    //RENDER ALL ROWS
                                return (

                                            {projectType._id}

                                            {this.state.editMode ?
                                                <input type="text" className="browser-default" defaultValue={projectType.name} onChange={this.changeProjectName}/>  //On change, I need to save back to the state this value
                                                :
                                                projectType.name
                                            }

                                            <button className="btn btn-small mr-1" onClick={this.changeEditMode}>Edit</button>
                                            <button className="btn btn-small">Delete</button>

                                )
                            }
                            )}

            );
    }

}

function mapStateToProps(state) {
    return { projectTypes: state.quizz.projectTypes };
}

export default connect(mapStateToProps, actions)(AddProjectType);

Body:
Attach data-idx={i} in the input like this,

<input type="text" className="browser-default" defaultValue={projectType.name} onChange={this.changeProjectName} data-idx={i}/>

In your changeProjectName(event) handler,

var index = event.target.dataset.idx; // Here you will get index


来源: stackexchange

问:
HttpClient & Windows Auth: Pass logged in User of Consumer to Service
I am struggling to understand and set up a Service and Consumer where the Service will run as the user logged into the Consumer.

My consumer is an MVC application. My Service is a Web Api application. Both run on separate servers within the same domain. Both are set to use Windows Auth.

My consumer code is:

```<code>private T GenericGet<T>(string p)
    {
        T result = default(T);

        HttpClientHandler handler = new HttpClientHandler() { PreAuthenticate = true, UseDefaultCredentials = true };
        using (HttpClient client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri(serviceEndPoint);

            HttpResponseMessage response = client.GetAsync(p).Result;
            if (response.IsSuccessStatusCode)
                result = response.Content.ReadAsAsync<T>().Result;
        }

        return result;
    }
</code>```

In my Service I call User.Identity.Name to get the caller ID but this always comes back as the consumer App Pool ID, not the logged in user. The consumer App Pool is running as a Network Service, the server itself is trusted for delegation. So how do I get the logged in User? Service code:

```<code>    // GET: /Modules/5/Permissions/
    [Authorize]
    public ModulePermissionsDTO Get(int ModuleID)
    {
        Module module= moduleRepository.Find(ModuleID);
        if (module== null)
            throw new HttpResponseException(HttpStatusCode.NotFound);

        // This just shows as the App Pool the MVC consumer is running as (Network Service).
        IPrincipal loggedInUser = User;

        // Do I need to do something with this instead?
        string authHeader = HttpContext.Current.Request.Headers["Authorization"];

        ModulePermissionsDTO dto = new ModulePermissionsDTO();
        // Construct object here based on User...

        return dto;
    }
</code>```

According to this question, Kerberos is required to make this set up work because the HttpClient runs in a separate thread. However this confuses me because I thought the request sends an Authorization header and so the service should be able to use this and retrieve the user token. Anyway, I have done some testing with Kerberos to check that this correctly works on my domain using the demo in "Situation 5" here and this works but my two applications still wont correctly pass the logged in user across.

So what do I need to do to make this work? Is Kerberos needed or do I need to do something in my Service to unpack the Authorisation header and create a principal object from the token? All advice appreciated.

答:
If you are trying to access service which is hosted on windows authentication then do following.

```<code>var request = new RestRequest(Method.POST);
</code>```

If you want to use applications default credentials which must have access on hosted service server

```<code>request.UseDefaultCredentials = true;
</code>```

or user below to pass the credentials manually

```<code>request.Credentials = new NetworkCredential("Username", "Password", "Domain");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am struggling to understand and set up a Service and Consumer where the Service will run as the user logged into the Consumer.

My consumer is an MVC application. My Service is a Web Api application. Both run on separate servers within the same domain. Both are set to use Windows Auth.

My consumer code is:

private T GenericGet<T>(string p)
    {
        T result = default(T);

        HttpClientHandler handler = new HttpClientHandler() { PreAuthenticate = true, UseDefaultCredentials = true };
        using (HttpClient client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri(serviceEndPoint);

            HttpResponseMessage response = client.GetAsync(p).Result;
            if (response.IsSuccessStatusCode)
                result = response.Content.ReadAsAsync<T>().Result;
        }

        return result;
    }

In my Service I call User.Identity.Name to get the caller ID but this always comes back as the consumer App Pool ID, not the logged in user. The consumer App Pool is running as a Network Service, the server itself is trusted for delegation. So how do I get the logged in User? Service code:

    // GET: /Modules/5/Permissions/
    [Authorize]
    public ModulePermissionsDTO Get(int ModuleID)
    {
        Module module= moduleRepository.Find(ModuleID);
        if (module== null)
            throw new HttpResponseException(HttpStatusCode.NotFound);

        // This just shows as the App Pool the MVC consumer is running as (Network Service).
        IPrincipal loggedInUser = User;

        // Do I need to do something with this instead?
        string authHeader = HttpContext.Current.Request.Headers["Authorization"];

        ModulePermissionsDTO dto = new ModulePermissionsDTO();
        // Construct object here based on User...

        return dto;
    }

According to this question, Kerberos is required to make this set up work because the HttpClient runs in a separate thread. However this confuses me because I thought the request sends an Authorization header and so the service should be able to use this and retrieve the user token. Anyway, I have done some testing with Kerberos to check that this correctly works on my domain using the demo in "Situation 5" here and this works but my two applications still wont correctly pass the logged in user across.

So what do I need to do to make this work? Is Kerberos needed or do I need to do something in my Service to unpack the Authorisation header and create a principal object from the token? All advice appreciated.

Body:
If you are trying to access service which is hosted on windows authentication then do following.

var request = new RestRequest(Method.POST);

If you want to use applications default credentials which must have access on hosted service server

request.UseDefaultCredentials = true;

or user below to pass the credentials manually

request.Credentials = new NetworkCredential("Username", "Password", "Domain");


问:
Conditional Dynamic validator using "Python Descriptors"
I want to build a simple "DataSource" class with has attributes named as "data_source_type" and "data_source_path". Where "data_source_type" is a ENUM and "data_source_path" is a string, depending on "data_source_type" I want to set appropriate validations like "ValidFilePath" or "ValidHttpURL" to "data_source_path".

I don't want to write IF-ELSE and have a spaghetti data-source class, I want to leverage  "Python Descriptors" or Any other elegant Python constructs which would consider SRP ( Single Responsibility Principle ) and support functional programming construct.

data_source.py

```<code>1 import re
2 from enum import Enum
3 import os
4
5
6 class ValidFilePath(object):
7     def __set__(self, obj, val):
8         if not os.path.exists():
9             raise ValueError("Please enter a valid file path")
10             self.__url = val
11
12     def __get__(self, obj, objtype):
13         return self.__url
14
15
16 class ValidHttpURL(object):
17     def __set__(self, obj, val):
18         if (val is None or re.compile(
19                 r'^https?://'  # http:// or https://
20                 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...
21                 r'localhost|'  # localhost...
22                 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
23                 r'(?::\d+)?'  # optional port
24                 r'(?:/?|[/?]\S+)$', re.IGNORECASE).search(val) is None):
25             raise ValueError("Please set an valid HTTP(S) URL")
26             self.__url = val
27
28     def __get__(self, obj, objtype):
29         return self.__url
30
31
32 class DataSourceType(Enum):
33     HTTP = 100,
34     LOCAL_FILE = 200,
35     HDFS_FILE = 300
36
37
38 class ValidDataSourceType(object):
39     def __set__(self, obj, val):
40         if val is None or not DataSourceType.__contains__(DataSourceType[val]):
41             raise ValueError("Please set a valid Data Source Type Enum, "
42                              " possible values are -> ", [e.name for e in DataSourceType])
43         self.__data_source_type = DataSourceType[val]
44
45     def __get__(self, obj, objtype):
46         return self.__data_source_type
47
48
49 class DataSource(object):
50     data_source_type = ValidDataSourceType()
51     data_source_path = ValidHttpURL()
</code>```

In line number 51 as of now I have put "ValidHttpURL", where I want to set the appropriate validation descriptor depending on the "data_source_type"

Expected behavior

```<code>ds1 = DataSource()
ds1.data_source_type = 'HTTP'
ds1.data_source_path = 'http://www.google.com'
ds2 = DataSource()
ds2.data_source_type = 'LOCAL_FILE'
ds2.data_source_path = '/var/www/index.html'
print("All is well")
</code>```

Actual behavior

```<code>ds1 = DataSource()
ds1.data_source_type = 'HTTP'
ds1.data_source_path = 'http://www.google.com'
ds2 = DataSource()
ds2.data_source_type = 'LOCAL_FILE'
ds2.data_source_path = '/var/www/index.html'

**ValueError: Please set an valid HTTP(S) URL**
</code>```

***UPDATED ANSWER ****

```<code>  1 import os
  2 import re
  3 from enum import Enum
  4 from weakref import WeakKeyDictionary
  5
  6
  7 def valid_file_path(value):
  8     if not os.path.exists(value):
  9         raise ValueError(value, " is not present. Please make sure the file exists")
 10     return value
 11
 12
 13 def valid_http_url(value):
 14     if (value is None or re.compile(
 15             r'^https?://'  # http:// or https://
 16             r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...
 17             r'localhost|'  # localhost...
 18             r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
 19             r'(?::\d+)?'  # optional port
 20             r'(?:/?|[/?]\S+)$', re.IGNORECASE).search(value) is None):
 21         raise ValueError("Please set an valid HTTP(S) URL")
 22     return value
 23
 24
 25 class DataSourceType(Enum):
 26     NOT_DEFINED = (0, None)
 27     HTTP = (100, valid_http_url)
 28     LOCAL_FILE = (200, valid_file_path)
 29
 30     def __init__(self, enum_id, enum_validator):
 31         self._id = enum_id
 32         self._validator = enum_validator
 33
 34     @property
 35     def validator(self):
 36         return self._validator
 37
 38
 39 class ValidDataSourceType(object):
 40     def __init__(self):
 41         self.default = DataSourceType.NOT_DEFINED
 42         self.values = WeakKeyDictionary()
 43
 44     def __get__(self, instance, owner):
 45         return self.values.get(instance, self.default)
 46
 47     def __set__(self, instance, value):
 48         if value is None or not DataSourceType.__contains__(DataSourceType[value]):
 49             raise ValueError("Please set a valid Data Source Type Enum, "
 50                              " possible values are -> ", [e.name for e in DataSourceType])
 51         self.values[instance] = DataSourceType[value]
 52
 53     def __delete__(self, instance):
 54         del self.values[instance]
 55
 56
 57 class ValidDataSourcePath(object):
 58     def __init__(self, default_data_source_type_field='data_source_type'):
 59         self._default = ''
 60         self._default_data_source_type_field = default_data_source_type_field
 61         self.values = WeakKeyDictionary()
 62
 63     def __get__(self, instance, owner):
 64         return self.values.get(instance, self._default)
 65
 66     def __set__(self, instance, *value):
 67         data_source_type_field = self._default_data_source_type_field
 68         value_to_set = None
 69
 70         if value and len(value) == 1 and isinstance(value[0], str):  # user sent only the value
 71             value_to_set = value[0]
 72         if value and len(value) == 1 and isinstance(value[0], tuple):  # user sent the value , and the validation field
 73             value_to_set = value[0][0]
 74             data_source_type_field = value[0][1]
 75
 76         _data_source_type = getattr(instance, data_source_type_field, None)
 77         if not _data_source_type:
 78             raise ValueError(" Valid source path depends on ValidDataSourceType , "
 79                              " please make sure you have an attribute named ValidDataSourceType")
 80         _data_source_type.validator(value_to_set)
 81         self.values[instance] = value_to_set
 82
 83
 84 class DataSource(object):
 85     data_source_type = ValidDataSourceType()
 86     data_source_path = ValidDataSourcePath()
 87
 88
 89 class SomeOtherDomainModel(object):
 90     data_source_type_ext = ValidDataSourceType()
 91     data_source_path = ValidDataSourcePath()
 92
 93
 94 print(" **************** Scenario 1 - Start **************** ")
 95 ds1 = DataSource()
 96 ds1.data_source_type = 'HTTP'
 97 ds1.data_source_path = "http://www.google.com"
 98 print(ds1.data_source_path)
 99 print(" **************** Scenario 1 - End **************** ")
100
101 print(" **************** Scenario 2 - Start **************** ")
102 ds2 = SomeOtherDomainModel()
103 ds2.data_source_type_ext = 'HTTP'
104 ds2.data_source_path = ("http://www.yahoo.com", 'data_source_type_ext')
105 print(ds2.data_source_path)
106 print(" **************** Scenario 2 - Start **************** ")
</code>```

答:
So, building off my comments above, here's how DataSource would look (using @property), along with the idea that the validator classes should just be functions that return a boolean of whether the path is valid (and raises an error if it would like) instead of being more descriptors:

```<code>class DataSource(object):
    data_source_type = ValidDataSourceType()

    @property
    def data_source_path(self):
        # can put in a check to make sure _data_source_path exists
        return _data_source_path

    @data_source_path.setter
    def data_source_path(self, path):
        if self.data_source_type.validator(path):
            self._data_source_path = path
</code>```

Descriptors can be difficult to work with and around (I should know; I literally wrote the book), and should be avoided when a simpler solution can be found, so that's why I turned your validators into predicate functions. There is also no shame in using @property instead of a custom descriptor.

Body:
I want to build a simple "DataSource" class with has attributes named as "data_source_type" and "data_source_path". Where "data_source_type" is a ENUM and "data_source_path" is a string, depending on "data_source_type" I want to set appropriate validations like "ValidFilePath" or "ValidHttpURL" to "data_source_path".

I don't want to write IF-ELSE and have a spaghetti data-source class, I want to leverage  "Python Descriptors" or Any other elegant Python constructs which would consider SRP ( Single Responsibility Principle ) and support functional programming construct.

data_source.py

1 import re
2 from enum import Enum
3 import os
4
5
6 class ValidFilePath(object):
7     def __set__(self, obj, val):
8         if not os.path.exists():
9             raise ValueError("Please enter a valid file path")
10             self.__url = val
11
12     def __get__(self, obj, objtype):
13         return self.__url
14
15
16 class ValidHttpURL(object):
17     def __set__(self, obj, val):
18         if (val is None or re.compile(
19                 r'^https?://'  # http:// or https://
20                 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...
21                 r'localhost|'  # localhost...
22                 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
23                 r'(?::\d+)?'  # optional port
24                 r'(?:/?|[/?]\S+)$', re.IGNORECASE).search(val) is None):
25             raise ValueError("Please set an valid HTTP(S) URL")
26             self.__url = val
27
28     def __get__(self, obj, objtype):
29         return self.__url
30
31
32 class DataSourceType(Enum):
33     HTTP = 100,
34     LOCAL_FILE = 200,
35     HDFS_FILE = 300
36
37
38 class ValidDataSourceType(object):
39     def __set__(self, obj, val):
40         if val is None or not DataSourceType.__contains__(DataSourceType[val]):
41             raise ValueError("Please set a valid Data Source Type Enum, "
42                              " possible values are -> ", [e.name for e in DataSourceType])
43         self.__data_source_type = DataSourceType[val]
44
45     def __get__(self, obj, objtype):
46         return self.__data_source_type
47
48
49 class DataSource(object):
50     data_source_type = ValidDataSourceType()
51     data_source_path = ValidHttpURL()

In line number 51 as of now I have put "ValidHttpURL", where I want to set the appropriate validation descriptor depending on the "data_source_type"

Expected behavior

ds1 = DataSource()
ds1.data_source_type = 'HTTP'
ds1.data_source_path = 'http://www.google.com'
ds2 = DataSource()
ds2.data_source_type = 'LOCAL_FILE'
ds2.data_source_path = '/var/www/index.html'
print("All is well")

Actual behavior

ds1 = DataSource()
ds1.data_source_type = 'HTTP'
ds1.data_source_path = 'http://www.google.com'
ds2 = DataSource()
ds2.data_source_type = 'LOCAL_FILE'
ds2.data_source_path = '/var/www/index.html'

**ValueError: Please set an valid HTTP(S) URL**

***UPDATED ANSWER ****

  1 import os
  2 import re
  3 from enum import Enum
  4 from weakref import WeakKeyDictionary
  5
  6
  7 def valid_file_path(value):
  8     if not os.path.exists(value):
  9         raise ValueError(value, " is not present. Please make sure the file exists")
 10     return value
 11
 12
 13 def valid_http_url(value):
 14     if (value is None or re.compile(
 15             r'^https?://'  # http:// or https://
 16             r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...
 17             r'localhost|'  # localhost...
 18             r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
 19             r'(?::\d+)?'  # optional port
 20             r'(?:/?|[/?]\S+)$', re.IGNORECASE).search(value) is None):
 21         raise ValueError("Please set an valid HTTP(S) URL")
 22     return value
 23
 24
 25 class DataSourceType(Enum):
 26     NOT_DEFINED = (0, None)
 27     HTTP = (100, valid_http_url)
 28     LOCAL_FILE = (200, valid_file_path)
 29
 30     def __init__(self, enum_id, enum_validator):
 31         self._id = enum_id
 32         self._validator = enum_validator
 33
 34     @property
 35     def validator(self):
 36         return self._validator
 37
 38
 39 class ValidDataSourceType(object):
 40     def __init__(self):
 41         self.default = DataSourceType.NOT_DEFINED
 42         self.values = WeakKeyDictionary()
 43
 44     def __get__(self, instance, owner):
 45         return self.values.get(instance, self.default)
 46
 47     def __set__(self, instance, value):
 48         if value is None or not DataSourceType.__contains__(DataSourceType[value]):
 49             raise ValueError("Please set a valid Data Source Type Enum, "
 50                              " possible values are -> ", [e.name for e in DataSourceType])
 51         self.values[instance] = DataSourceType[value]
 52
 53     def __delete__(self, instance):
 54         del self.values[instance]
 55
 56
 57 class ValidDataSourcePath(object):
 58     def __init__(self, default_data_source_type_field='data_source_type'):
 59         self._default = ''
 60         self._default_data_source_type_field = default_data_source_type_field
 61         self.values = WeakKeyDictionary()
 62
 63     def __get__(self, instance, owner):
 64         return self.values.get(instance, self._default)
 65
 66     def __set__(self, instance, *value):
 67         data_source_type_field = self._default_data_source_type_field
 68         value_to_set = None
 69
 70         if value and len(value) == 1 and isinstance(value[0], str):  # user sent only the value
 71             value_to_set = value[0]
 72         if value and len(value) == 1 and isinstance(value[0], tuple):  # user sent the value , and the validation field
 73             value_to_set = value[0][0]
 74             data_source_type_field = value[0][1]
 75
 76         _data_source_type = getattr(instance, data_source_type_field, None)
 77         if not _data_source_type:
 78             raise ValueError(" Valid source path depends on ValidDataSourceType , "
 79                              " please make sure you have an attribute named ValidDataSourceType")
 80         _data_source_type.validator(value_to_set)
 81         self.values[instance] = value_to_set
 82
 83
 84 class DataSource(object):
 85     data_source_type = ValidDataSourceType()
 86     data_source_path = ValidDataSourcePath()
 87
 88
 89 class SomeOtherDomainModel(object):
 90     data_source_type_ext = ValidDataSourceType()
 91     data_source_path = ValidDataSourcePath()
 92
 93
 94 print(" **************** Scenario 1 - Start **************** ")
 95 ds1 = DataSource()
 96 ds1.data_source_type = 'HTTP'
 97 ds1.data_source_path = "http://www.google.com"
 98 print(ds1.data_source_path)
 99 print(" **************** Scenario 1 - End **************** ")
100
101 print(" **************** Scenario 2 - Start **************** ")
102 ds2 = SomeOtherDomainModel()
103 ds2.data_source_type_ext = 'HTTP'
104 ds2.data_source_path = ("http://www.yahoo.com", 'data_source_type_ext')
105 print(ds2.data_source_path)
106 print(" **************** Scenario 2 - Start **************** ")

Body:
So, building off my comments above, here's how DataSource would look (using @property), along with the idea that the validator classes should just be functions that return a boolean of whether the path is valid (and raises an error if it would like) instead of being more descriptors:

class DataSource(object):
    data_source_type = ValidDataSourceType()

    @property
    def data_source_path(self):
        # can put in a check to make sure _data_source_path exists
        return _data_source_path

    @data_source_path.setter
    def data_source_path(self, path):
        if self.data_source_type.validator(path):
            self._data_source_path = path

Descriptors can be difficult to work with and around (I should know; I literally wrote the book), and should be avoided when a simpler solution can be found, so that's why I turned your validators into predicate functions. There is also no shame in using @property instead of a custom descriptor.


问:
AutoCompleteExtender Returns HTML Instead of JSON
UPDATE 3:

Code behind for the GetGrowers call:

```<code>using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.ServiceModel.Web;

namespace AmericanApple
{
public partial class ReceivingStation : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bcDataTextBox.Focus();

    }

    [ScriptMethod]
    [WebMethod]
    public static string[] GetGrowers(string prefixText, int count)
    {
        string[] growers = { "American Apple", "Lewis", "Grice" };
        return growers;
    }
}
}
</code>```

UPDATE 2:

I think I've identified the problem. When viewing the "Network" tab in Chrome developer tools, I can see the call to GetGrowers, and in the request headers, it's asking for application/json format, but in the response header, it returns text/html. So all those characters in the dropdown is actually the entire page in html.

In the working example I have, the response header for the Auto CE call is application/json. So for whatever reason, my project's response for this is not in the right format. I have checked the web.config file and don't see any differences between my working example and the project I'm working on.

UPDATE:

Image of what's happening in Chrome:

ORIGINAL:

I cannot get my AutoCompleteExtender to work. In Chrome and FireFox my auto complete results are a bunch of (random?) characters. In Internet Explorer only, when I click in the TextBox the page freezes and my Visual Studio output looks like this:

Exception was thrown at line 39, column 3 in eval code

  0x800a1391 - JavaScript runtime error: 's' is undefined

  Exception was thrown at line 37, column 3 in eval code

  0x800a1391 - JavaScript runtime error: 'r' is undefined

  Exception was thrown at line 31, column 3 in eval code

  0x800a1391 - JavaScript runtime error: 'e' is undefined

...and keeps going like that indefinitely.

I have the latest AjaxControlToolkit installed: 17.1.1.
I'm using VS Pro 2015 version 14.0.25420.01 Update 3.
.NET Framework version 4.7.02046

In my Site.Master page I'm declaring

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

at the top and my script manager in the body:

```<code><asp:ScriptManager runat="server" EnablePageMethods="true" EnablePartialRendering="true">
        <Scripts>
            <%--To learn more about bundling scripts in ScriptManager see http://go.microsoft.com/fwlink/?LinkID=301884 --%>
            <%--Framework Scripts--%>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="bootstrap" />
            <asp:ScriptReference Name="respond" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
            <%--Site Scripts--%>
        </Scripts>
    </asp:ScriptManager>
</code>```

On the page running the AutoCompleteExtender:

```<code><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<cc1:AutoCompleteExtender ID="AutoCompleteGrower" runat="server" TargetControlID="txtGrower"
    MinimumPrefixLength="0" CompletionInterval="100" EnableCaching="true" UseContextKey="false"
    ServiceMethod="GetGrowers" CompletionListCssClass="autocomplete_List" CompletionListItemCssClass="autocomplete_ListItem"
    CompletionListHighlightedItemCssClass="autocomplete_HighlightedListItem" FirstRowSelected="true">
</cc1:AutoCompleteExtender>
</code>```

My TextBox:

```<code><asp:TableCell><asp:TextBox ID="txtGrower" runat="server" CssClass="form-control" AutoCompleteType="None"></asp:TextBox></asp:TableCell>
</code>```

I have not found an AutoCompleteExtender question on SO with this same error. What am I missing here? The error is occurring before my ServiceMethod can return, I know that much.

答:
Well the solution that worked was to add the method to a web service file (asmx.cs).

So the class declaration looks like this:

```<code>[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AmericanAppleServices : System.Web.Services.WebService
{
</code>```

And the method declaration:

```<code>[WebMethod]
public string[] GetGrowers(string prefixText, int count)
{
</code>```

Using this method I also have to have the Service path declared in my AutoCompleteExtender in my .aspx page:

ServicePath="AmericanAppleServices.asmx"

I still do not know why the other way did not work, but this will do for now. @MikhailTymchukDX thanks for all your help!

Body:
UPDATE 3:

Code behind for the GetGrowers call:

using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.ServiceModel.Web;

namespace AmericanApple
{
public partial class ReceivingStation : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bcDataTextBox.Focus();

    }

    [ScriptMethod]
    [WebMethod]
    public static string[] GetGrowers(string prefixText, int count)
    {
        string[] growers = { "American Apple", "Lewis", "Grice" };
        return growers;
    }
}
}

UPDATE 2:

I think I've identified the problem. When viewing the "Network" tab in Chrome developer tools, I can see the call to GetGrowers, and in the request headers, it's asking for application/json format, but in the response header, it returns text/html. So all those characters in the dropdown is actually the entire page in html.

In the working example I have, the response header for the Auto CE call is application/json. So for whatever reason, my project's response for this is not in the right format. I have checked the web.config file and don't see any differences between my working example and the project I'm working on.

UPDATE:

Image of what's happening in Chrome:

ORIGINAL:

I cannot get my AutoCompleteExtender to work. In Chrome and FireFox my auto complete results are a bunch of (random?) characters. In Internet Explorer only, when I click in the TextBox the page freezes and my Visual Studio output looks like this:

Exception was thrown at line 39, column 3 in eval code

  0x800a1391 - JavaScript runtime error: 's' is undefined

  Exception was thrown at line 37, column 3 in eval code

  0x800a1391 - JavaScript runtime error: 'r' is undefined

  Exception was thrown at line 31, column 3 in eval code

  0x800a1391 - JavaScript runtime error: 'e' is undefined

...and keeps going like that indefinitely.

I have the latest AjaxControlToolkit installed: 17.1.1.
I'm using VS Pro 2015 version 14.0.25420.01 Update 3.
.NET Framework version 4.7.02046

In my Site.Master page I'm declaring

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

at the top and my script manager in the body:

<asp:ScriptManager runat="server" EnablePageMethods="true" EnablePartialRendering="true">

    </asp:ScriptManager>

On the page running the AutoCompleteExtender:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<cc1:AutoCompleteExtender ID="AutoCompleteGrower" runat="server" TargetControlID="txtGrower"
    MinimumPrefixLength="0" CompletionInterval="100" EnableCaching="true" UseContextKey="false"
    ServiceMethod="GetGrowers" CompletionListCssClass="autocomplete_List" CompletionListItemCssClass="autocomplete_ListItem"
    CompletionListHighlightedItemCssClass="autocomplete_HighlightedListItem" FirstRowSelected="true">
</cc1:AutoCompleteExtender>

My TextBox:

<asp:TableCell><asp:TextBox ID="txtGrower" runat="server" CssClass="form-control" AutoCompleteType="None"></asp:TextBox></asp:TableCell>

I have not found an AutoCompleteExtender question on SO with this same error. What am I missing here? The error is occurring before my ServiceMethod can return, I know that much.

Body:
Well the solution that worked was to add the method to a web service file (asmx.cs).

So the class declaration looks like this:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AmericanAppleServices : System.Web.Services.WebService
{

And the method declaration:

[WebMethod]
public string[] GetGrowers(string prefixText, int count)
{

Using this method I also have to have the Service path declared in my AutoCompleteExtender in my .aspx page:

ServicePath="AmericanAppleServices.asmx"

I still do not know why the other way did not work, but this will do for now. @MikhailTymchukDX thanks for all your help!


问:
Where orWhere Laravel 5.5 logical DB issue
I am in agony

This is my helper

```<code>$friend_query = Friend::where([
        'user_id' => Auth::id(),
        'friend_id' => $friend_id,
        ])->orWhere([
        'user_id' => $friend_id,
        'friend_id' => Auth::id(),
        ])->first();

        $friendship = new stdClass();
        $friendship->exist = false;
        $friendship->accepted = false;

        if (! is_null($friend_query))
        {
        $friendship->accepted = $friend_query->accepted;
        $friendship->exist = true;
    }
        var_dump($friendship->exist);
        exit;
        return $friendship;
</code>```

And when I am logged as 'user_id' => auth::id() - everything is fine but when I am logged as 'friend_id' who got request always var_dump return me true... This is third day I can not find solution. The photo of DB included in post.

答:
Thank you,
just little syntax error should be

```<code>->orWhere(function ($query) {
</code>```

but there is one problem - Undefined variable: friend_id

it goes like this

```<code>function friendship($friend_id){
friend_query = Friend::where([
        'user_id' => Auth::id(),
        'friend_id' => $friend_id,
        ])->orWhere(function ($query) {
                                $query->where([
                                        'user_id' => $friend_id,
                                        'friend_id' => Auth::id(),
                                        ]);
                            })
                    ->first();
... }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am in agony

This is my helper

$friend_query = Friend::where([
        'user_id' => Auth::id(),
        'friend_id' => $friend_id,
        ])->orWhere([
        'user_id' => $friend_id,
        'friend_id' => Auth::id(),
        ])->first();

        $friendship = new stdClass();
        $friendship->exist = false;
        $friendship->accepted = false;

        if (! is_null($friend_query))
        {
        $friendship->accepted = $friend_query->accepted;
        $friendship->exist = true;
    }
        var_dump($friendship->exist);
        exit;
        return $friendship;

And when I am logged as 'user_id' => auth::id() - everything is fine but when I am logged as 'friend_id' who got request always var_dump return me true... This is third day I can not find solution. The photo of DB included in post.

Body:
Thank you,
just little syntax error should be

->orWhere(function ($query) {

but there is one problem - Undefined variable: friend_id

it goes like this

function friendship($friend_id){
friend_query = Friend::where([
        'user_id' => Auth::id(),
        'friend_id' => $friend_id,
        ])->orWhere(function ($query) {
                                $query->where([
                                        'user_id' => $friend_id,
                                        'friend_id' => Auth::id(),
                                        ]);
                            })
                    ->first();
... }


问:
Passing a string variable between two functions in Python
I am having trouble passing a variable from one function to another:

```<code>def name():

    first_name=input("What is your name? ")

    if len(first_name)==0:
            print("\nYou did not enter a name!")
            return name()

    else:
            print("\nHello %s." % first_name)
            return surname()

def surname():

    last_name=input("\nCan you tell my your last name please?")

    if len(last_name)==0:
            print("\nYou did not enter a last name!")
            return surname()
    else:

            print("Nice to meet you %s %s." % (first_name,last_name))
</code>```

I want the last command to print the inputed first_name from def name() and last name from def surname()

I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:

```<code>    print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
</code>```

What am I doing wrong?

答:
```<code>def functionname(untypedparametername):
    # do smth with untypedparametername which holds "Jim" for this example

name = "Jim"

functionname(name) # this will provide "Jim" to the function
</code>```

You can see how they are used if you look at the examples in the documentation, f.e. here: https://docs.python.org/3/library/functions.html

Maybe you should read up on some of the tutorials for basics, you can find lots of them on the python main page: https://wiki.python.org/moin/BeginnersGuide

Body:
I am having trouble passing a variable from one function to another:

def name():

    first_name=input("What is your name? ")

    if len(first_name)==0:
            print("\nYou did not enter a name!")
            return name()

    else:
            print("\nHello %s." % first_name)
            return surname()

def surname():

    last_name=input("\nCan you tell my your last name please?")

    if len(last_name)==0:
            print("\nYou did not enter a last name!")
            return surname()
    else:

            print("Nice to meet you %s %s." % (first_name,last_name))

I want the last command to print the inputed first_name from def name() and last name from def surname()

I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:

    print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined

What am I doing wrong?

Body:
def functionname(untypedparametername):
    # do smth with untypedparametername which holds "Jim" for this example

name = "Jim"

functionname(name) # this will provide "Jim" to the function

You can see how they are used if you look at the examples in the documentation, f.e. here: https://docs.python.org/3/library/functions.html

Maybe you should read up on some of the tutorials for basics, you can find lots of them on the python main page: https://wiki.python.org/moin/BeginnersGuide


问:
Clojure test with multiple assertions
I am starting to learn how to write tests for my Clojure program.
I have a test with multiple assertions (calls to is).
I want the test to stop running as soon as the first assertion fails.
Here is my test:

```<code>(deftest register-one-command
  (testing "Register-one-command"
    (do
      (is (= 0 (count @test/list-of-commands)))
      (test/add-to-list-of-commands ["A"])
      (is (= 1 (count @test/list-of-commands))))))
</code>```

If the first is fails, I want the whole thing to fail.

答:
The simplest way is to just wrap the different tests in an and

```<code>(deftest register-one-command
  (testing "Register-one-command"
    (is (and
          (= 0 (count @test/list-of-commands))
          (test/add-to-list-of-commands ["A"])
          (= 1 (count @test/list-of-commands))))))
</code>```

If possible, however, I would try to restructure the tests so that this extra bit of complexity is unnecessary.

Title: Clojure test with multiple assertions

Body:
I am starting to learn how to write tests for my Clojure program.
I have a test with multiple assertions (calls to is).
I want the test to stop running as soon as the first assertion fails.
Here is my test:

(deftest register-one-command
  (testing "Register-one-command"
    (do
      (is (= 0 (count @test/list-of-commands)))
      (test/add-to-list-of-commands ["A"])
      (is (= 1 (count @test/list-of-commands))))))

If the first is fails, I want the whole thing to fail.

Body:
The simplest way is to just wrap the different tests in an and

(deftest register-one-command
  (testing "Register-one-command"
    (is (and
          (= 0 (count @test/list-of-commands))
          (test/add-to-list-of-commands ["A"])
          (= 1 (count @test/list-of-commands))))))

If possible, however, I would try to restructure the tests so that this extra bit of complexity is unnecessary.


问:
Syntax error on multiple join statement

Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks

```<code>String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
    "FROM tblStudent LEFT JOIN tblSchool " +
    "ON (tblStudent.schoolID = tblSchool.schoolID) " +
    "LEFT JOIN tblAgents " +
    "ON (tblStudent.agentID = tblAgents.agentID) " +
    "WHERE tblStudent.StudentID='" + studentID + "'";
</code>```

I was hoping that I could do multiple joins

But I am getting a syntax error.

答:
```<code>        String sql = "Select
        tblStudent.StudentID,tblStudent.studentFirstName,"+
        tblStudent.studentLastName,tblSchool.schoolName," +
        tblAgents.agentFirstName,tblAgents.agentLastName " +
        "FROM (tblStudent LEFT JOIN tblSchool " +
        "ON (tblStudent.schoolID = tblSchool.schoolID)) " +
        "LEFT JOIN tblAgents " +
        "ON (tblStudent.agentID = tblAgents.agentID) " +
        "WHERE tblStudent.StudentID=@studentID";
</code>```

Title: Syntax error on multiple join statement

Body:
Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks

String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
    "FROM tblStudent LEFT JOIN tblSchool " +
    "ON (tblStudent.schoolID = tblSchool.schoolID) " +
    "LEFT JOIN tblAgents " +
    "ON (tblStudent.agentID = tblAgents.agentID) " +
    "WHERE tblStudent.StudentID='" + studentID + "'";

I was hoping that I could do multiple joins

But I am getting a syntax error.


问:
How to use for loop to drastically reduce code length?
Can someone help me to use a for loop or whatever to drastically reduce the length of this code? I just have to copy some data from datAgg sheet to f5 sheet, but I would like to do it using arrays and for loop. I tried different times but it always give me error

```<code>  function regValori(){
      var datAgg =
      SpreadsheetApp.getActiveSpreadsheet().getSheetByName("dati
      aggiornati");
      var f5 =
      SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");
      var score1 = datAgg.getRange("P2").getValue(); // we want to store
                                                        this
      //collecting names and values
      var Cname1=datAgg.getRange("A2").getValue();
      var score2 = datAgg.getRange("P3").getValue();
      var Cname2 = datAgg.getRange("A3").getValue();
      var score3 = datAgg.getRange("P4").getValue();
      var Cname3 = datAgg.getRange("A4").getValue();
      var score4 = datAgg.getRange("P5").getValue();
      var Cname4 = datAgg.getRange("A5").getValue();
      var score5 = datAgg.getRange("P6").getValue();
      var Cname5 = datAgg.getRange("A6").getValue();

      // get the row number where to put data
      // in correspodance with today date

      var riga = f5.getRange(2, 2).getValue();

      f5.getRange(2,3).setValue(Cname1);
      f5.getRange(2,4).setValue(Cname2);
      f5.getRange(2,5).setValue(Cname3);
      f5.getRange(2,6).setValue(Cname4);
      f5.getRange(2,7).setValue(Cname5);

     // this one to put the value for every day

     f5.getRange(riga, 3).setValue(score1);
     f5.getRange(riga, 4).setValue(score2);
     f5.getRange(riga, 5).setValue(score3);
     f5.getRange(riga, 6).setValue(score4);
     f5.getRange(riga, 7).setValue(score5);

}
</code>```

答:
I'd do it like this

```<code>function regValori(){
    var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
    var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");

    var riga = f5.getRange(2, 2).getValue();
    for (var i = 2; i <= 6; ++i) {
        f5.getRange(riga, i + 1).setValue(datAgg.getRange("P" + i).getValue());
        f5.getRange(2, i + 1).setValue(datAgg.getRange("A" + i).getValue());
    }

}
</code>```

All you need to do is have the index i going from the lowest to the highest value and build the strings for getRange(). There's also no need for so many intermediary variables or an array, since you can do every operation in one loop.

Body:
Can someone help me to use a for loop or whatever to drastically reduce the length of this code? I just have to copy some data from datAgg sheet to f5 sheet, but I would like to do it using arrays and for loop. I tried different times but it always give me error

  function regValori(){
      var datAgg =
      SpreadsheetApp.getActiveSpreadsheet().getSheetByName("dati
      aggiornati");
      var f5 =
      SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");
      var score1 = datAgg.getRange("P2").getValue(); // we want to store
                                                        this
      //collecting names and values
      var Cname1=datAgg.getRange("A2").getValue();
      var score2 = datAgg.getRange("P3").getValue();
      var Cname2 = datAgg.getRange("A3").getValue();
      var score3 = datAgg.getRange("P4").getValue();
      var Cname3 = datAgg.getRange("A4").getValue();
      var score4 = datAgg.getRange("P5").getValue();
      var Cname4 = datAgg.getRange("A5").getValue();
      var score5 = datAgg.getRange("P6").getValue();
      var Cname5 = datAgg.getRange("A6").getValue();

      // get the row number where to put data
      // in correspodance with today date

      var riga = f5.getRange(2, 2).getValue();

      f5.getRange(2,3).setValue(Cname1);
      f5.getRange(2,4).setValue(Cname2);
      f5.getRange(2,5).setValue(Cname3);
      f5.getRange(2,6).setValue(Cname4);
      f5.getRange(2,7).setValue(Cname5);

     // this one to put the value for every day

     f5.getRange(riga, 3).setValue(score1);
     f5.getRange(riga, 4).setValue(score2);
     f5.getRange(riga, 5).setValue(score3);
     f5.getRange(riga, 6).setValue(score4);
     f5.getRange(riga, 7).setValue(score5);

}

Body:
I'd do it like this

function regValori(){
    var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
    var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");

    var riga = f5.getRange(2, 2).getValue();
    for (var i = 2; i <= 6; ++i) {
        f5.getRange(riga, i + 1).setValue(datAgg.getRange("P" + i).getValue());
        f5.getRange(2, i + 1).setValue(datAgg.getRange("A" + i).getValue());
    }

}

All you need to do is have the index i going from the lowest to the highest value and build the strings for getRange(). There's also no need for so many intermediary variables or an array, since you can do every operation in one loop.


问:
Handling ExecuteScalar() when no results are returned
I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:

```<code>sql = "select username from usermst where userid=2"
string getusername = command.ExecuteScalar();
</code>```

It is showing me this error message:

System.NullReferenceException: Object reference not set to an instance of an object

This error occurs when there is no row in the database table for userid=2.

How should I handle this situation?

答:
SQL NULL value

equivalent in C# is DBNull.Value

if a NULLABLE column has no value, this is what is returned

comparison in SQL: IF ( value IS NULL )

comparison in C#: if (obj == DBNull.Value)

visually represented in C# Quick-Watch as {}

Best practice when reading from a data reader:

```<code>var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());
</code>```

In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be

```<code>select MAX(ID) from <table name> where <impossible condition>
</code>```

The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)

```<code>var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));
</code>```

Body:
I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:

sql = "select username from usermst where userid=2"
string getusername = command.ExecuteScalar();

It is showing me this error message:

System.NullReferenceException: Object reference not set to an instance of an object

This error occurs when there is no row in the database table for userid=2.

How should I handle this situation?

Body:
SQL NULL value

equivalent in C# is DBNull.Value

if a NULLABLE column has no value, this is what is returned

comparison in SQL: IF ( value IS NULL )

comparison in C#: if (obj == DBNull.Value)

visually represented in C# Quick-Watch as {}

Best practice when reading from a data reader:

var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());

In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be

select MAX(ID) from <table name> where <impossible condition>

The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)

var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));


问:
out of bounds error when down sampling image
Does anyone know why my index matrix[k][m]=sum/9 is out of range? I'm pretty sure that my solution is correct. I tried debugging it, but I still cannot think
why it's not working.

```<code>def downsample_by_3(image):

    matrix_image = copy.deepcopy(image)
    matrix=[ [], [], [] ]
    k=0
    m=0
    for i in range(0,len(matrix_image),3):

        for j in range(0,len(matrix_image[i]),3):

            sum=0

            for r in range(i,i+3):
                for c in range(j,j+3):
                    sum+=matrix_image[r][c]
            m+=1
            matrix[k][m]=sum/9

        m=0
        k+=1

    return matrix
</code>```

The image is presented as a matrix (list of lists).

Let's say I took this list,

```<code>print(downsample_by_3([[2,2,2],[2,2,2],[2,2,2]]))
</code>```

it should return a list with 18.

Another example of it to understand it better:

答:
You have a list of empty lists. So while matrix[0] is fine, matrix[0][0] is out of bounds.

You have to either preallocate the lengths of the sublists beforehand if you wish to access them by index, or you append the averages as shown in Gary02127's answer. If you choose the former, you must also increment m after matrix[k][m]=sum/9.

However, your code has another out-of-bounds bug waiting to be triggered. Suppose you have a 3x4 image, i.e., one of the dimensions isn't divisible by 3. You average the first 3x3 block just fine, and then you try to access the pixels at column indices 3-5.

If your dimensions aren't divisible by the downsample factor, you have 3 choices:

raise an error at the beginning of the function call,

add extra rows/columns to make your matrix divisible by your factor (you can use the value of the last element of the row/column to extend it further), or

use only as many elements are you have left.

Here's an implementation with approach #3 and preallocating your matrix.

```<code>def downsample(image, factor):
    height = len(image)
    # this assumes that all sublists have the same length!
    width = len(image[0])
    matrix = [[None] * ((width + factor - 1) // factor)
              for _ in range((height + factor - 1) // factor)]
    k = 0
    m = 0
    for i in range(0, height, factor):
        for j in range(0, width, factor):
            # don't overshadow the `sum` builtin
            total = 0
            count = 0
            for r in range(i, min(i+factor, height)):
                for c in range(j, min(j+factor, width)):
                    total += image[r][c]
                    count += 1
            matrix[k][m] = total / count
            m += 1
        m = 0
        k += 1
    return matrix
</code>```

Body:
Does anyone know why my index matrix[k][m]=sum/9 is out of range? I'm pretty sure that my solution is correct. I tried debugging it, but I still cannot think
why it's not working.

def downsample_by_3(image):

    matrix_image = copy.deepcopy(image)
    matrix=[ [], [], [] ]
    k=0
    m=0
    for i in range(0,len(matrix_image),3):

        for j in range(0,len(matrix_image[i]),3):

            sum=0

            for r in range(i,i+3):
                for c in range(j,j+3):
                    sum+=matrix_image[r][c]
            m+=1
            matrix[k][m]=sum/9

        m=0
        k+=1

    return matrix

The image is presented as a matrix (list of lists).

Let's say I took this list,

print(downsample_by_3([[2,2,2],[2,2,2],[2,2,2]]))

it should return a list with 18.

Another example of it to understand it better:

Body:
You have a list of empty lists. So while matrix[0] is fine, matrix[0][0] is out of bounds.

You have to either preallocate the lengths of the sublists beforehand if you wish to access them by index, or you append the averages as shown in Gary02127's answer. If you choose the former, you must also increment m after matrix[k][m]=sum/9.

However, your code has another out-of-bounds bug waiting to be triggered. Suppose you have a 3x4 image, i.e., one of the dimensions isn't divisible by 3. You average the first 3x3 block just fine, and then you try to access the pixels at column indices 3-5.

If your dimensions aren't divisible by the downsample factor, you have 3 choices:

raise an error at the beginning of the function call,

add extra rows/columns to make your matrix divisible by your factor (you can use the value of the last element of the row/column to extend it further), or

use only as many elements are you have left.

Here's an implementation with approach #3 and preallocating your matrix.

def downsample(image, factor):
    height = len(image)
    # this assumes that all sublists have the same length!
    width = len(image[0])
    matrix = [[None] * ((width + factor - 1) // factor)
              for _ in range((height + factor - 1) // factor)]
    k = 0
    m = 0
    for i in range(0, height, factor):
        for j in range(0, width, factor):
            # don't overshadow the `sum` builtin
            total = 0
            count = 0
            for r in range(i, min(i+factor, height)):
                for c in range(j, min(j+factor, width)):
                    total += image[r][c]
                    count += 1
            matrix[k][m] = total / count
            m += 1
        m = 0
        k += 1
    return matrix


问:
SAP Hybris Update description of Front Tile Component
I am new to Hybris and I still do not know how impex works.
I would like to know how to make an impex script to update a description of a front tile component.

Thank you.

答:
You can find here the syntax of the impex file :

https://help.hybris.com/6.3.0/hcd/1c8f5bebdc6e434782ff0cfdb0ca1847.html#loio1c8f5bebdc6e434782ff0cfdb0ca1847

Basically it's a csv file (semicolon-separated) with specific structure/header,

```<code>mode type[modifier=value];attribute[modifier=value];attribute[modifier=value];attribute[modifier=value]
</code>```

mode : action to be executed -> INSERT, UPDATE, INSERT_UPDATE, REMOVE.

type : item to be processed -> Product, Category, Customer,...

attribute : the attribute of the item -> Product.name, category.description,...

modifier : additional information to process an attribute -> unique, lang, ...

Example :

Assuming we have the following Item type :

```<code>public class ProductModel {

    private String code;

    private String name;

}
</code>```

The impex to import Products would be like :

```<code>INSERT Product  ;code[unique=true]  ; name[lang=en]         ;name[lang=fr]
                ;123456;            ; This a product name   ;nom du produit
</code>```

To answer your question specifically -> to Update the description of a front tile component, thte impex file should be something like :

```<code>INSERT_UPDATE Name_of_the_Component ;code[unique=true]      ; description[lang=en]
                                    ;code of the component  ; The description to update
</code>```

Body:
You can find here the syntax of the impex file :

https://help.hybris.com/6.3.0/hcd/1c8f5bebdc6e434782ff0cfdb0ca1847.html#loio1c8f5bebdc6e434782ff0cfdb0ca1847

Basically it's a csv file (semicolon-separated) with specific structure/header,

mode type[modifier=value];attribute[modifier=value];attribute[modifier=value];attribute[modifier=value]

mode : action to be executed -> INSERT, UPDATE, INSERT_UPDATE, REMOVE.

type : item to be processed -> Product, Category, Customer,...

attribute : the attribute of the item -> Product.name, category.description,...

modifier : additional information to process an attribute -> unique, lang, ...

Example :

Assuming we have the following Item type :

public class ProductModel {

    private String code;

    private String name;

}

The impex to import Products would be like :

INSERT Product  ;code[unique=true]  ; name[lang=en]         ;name[lang=fr]
                ;123456;            ; This a product name   ;nom du produit

To answer your question specifically -> to Update the description of a front tile component, thte impex file should be something like :

INSERT_UPDATE Name_of_the_Component ;code[unique=true]      ; description[lang=en]
                                    ;code of the component  ; The description to update


问:
Will StreamReader and StreamWriter close auto after steam close?
I have this code:

```<code>let client = listener.AcceptTcpClient()
let stream = client.GetStream()
let sr = new StreamReader(stream)
let sw = new StreamWriter(stream)
</code>```

How should I close these things after I use them?

If I close client,will stream,sr,sw auto close?Or I need to close them one by one?Or should I use "use" to replace let,then I need not to close them manual?

If I want to use "use" keyword like this:

```<code>let listener=new TcpListener(IPAddress.Parse("127.0.0.1"),2000)

let  private loop (client : TcpClient, sr : StreamReader, sw : StreamWriter) =
async {
    sw.WriteLine("a")
}

let private startLoop () =
    while true do
        use client = listener.AcceptTcpClient()
        use stream = client.GetStream()
        use sr = new StreamReader(stream)
        use sw = new StreamWriter(stream)
        sw.AutoFlush <- true
        Async.Start(loop (client, sr, sw))

listener.Start()
startLoop ()
</code>```

When client connect,server got error:can't write to closed TextWriter

So when I use "use",the handle will dispose in startLoop function?

In this program,I need to use let,then close client,sr,sw,stream manual?

Thanks

答:
StreamReader.Dispose closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources.
That's why theoretically it is enough to use Dispose only on StreamReader
In your first code (without async) use "use" keyword for all disposable objects even if there is single real unmanaged resource in Stream class.
There are situations when you have one raw stream and you pass it sequentially to many other methods to read peace's of stream using StremReader's.

```<code>let  readPart stream =
    // note there is no dispose to don't close external stream
    let reader = new StreamReader(stream)
    // read data and return result

use stream = File.Open()
//read first part
let data1 = readPart stream
let data2 = readPart stream
// here stream should be closed
</code>```

In async code you should close streams after usage. You may open stream in infinite loop but don't dispose it there and close StreamWriter after write operation. StreamWriter will dispose will close your stream.

```<code>sw.WriteLine("a")
</code>```

https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged

Body:
I have this code:

let client = listener.AcceptTcpClient()
let stream = client.GetStream()
let sr = new StreamReader(stream)
let sw = new StreamWriter(stream)

How should I close these things after I use them?

If I close client,will stream,sr,sw auto close?Or I need to close them one by one?Or should I use "use" to replace let,then I need not to close them manual?

If I want to use "use" keyword like this:

let listener=new TcpListener(IPAddress.Parse("127.0.0.1"),2000)

let  private loop (client : TcpClient, sr : StreamReader, sw : StreamWriter) =
async {
    sw.WriteLine("a")
}

let private startLoop () =
    while true do
        use client = listener.AcceptTcpClient()
        use stream = client.GetStream()
        use sr = new StreamReader(stream)
        use sw = new StreamWriter(stream)
        sw.AutoFlush <- true
        Async.Start(loop (client, sr, sw))

listener.Start()
startLoop ()

When client connect,server got error:can't write to closed TextWriter

So when I use "use",the handle will dispose in startLoop function?

In this program,I need to use let,then close client,sr,sw,stream manual?

Thanks

Body:
StreamReader.Dispose closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources.
That's why theoretically it is enough to use Dispose only on StreamReader
In your first code (without async) use "use" keyword for all disposable objects even if there is single real unmanaged resource in Stream class.
There are situations when you have one raw stream and you pass it sequentially to many other methods to read peace's of stream using StremReader's.

let  readPart stream =
    // note there is no dispose to don't close external stream
    let reader = new StreamReader(stream)
    // read data and return result

use stream = File.Open()
//read first part
let data1 = readPart stream
let data2 = readPart stream
// here stream should be closed

In async code you should close streams after usage. You may open stream in infinite loop but don't dispose it there and close StreamWriter after write operation. StreamWriter will dispose will close your stream.

sw.WriteLine("a")

https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged


问:
start-stop-daemon and python
I'm trying to start python script with start-stop-daemon:

```<code>sudo /sbin/start-stop-daemon --start --pidfile /home/loop.pid \
--user www-data --group www-data -b --make-pidfile --chuid www-data \
--exec /usr/bin/python /home/loop.py --verbose
</code>```

but no python script in my processes. What i do wrong?

loop.py:

```<code>import time
while True:
    print "working..."
    time.sleep(3)
</code>```

答:
Rather than exec python directly, if you --exec (or --startas) a nested shell, then you can do the redirection in there (as per this answer):

```<code>start-stop-daemon --start --quiet --chuid $DAEMONUSER    \
 --make-pidfile --pidfile $PIDFILE --background       \
 --startas /bin/bash -- -c "exec $DAEMON $DAEMON_ARGS > /var/log/some.log 2>&1"
</code>```

This works for me and logs my Python stdout quite happily once I realized the output was buffered (my script wasn't writing very much)! I then found this article which uses 'stdbuf' to flush to the output more eagerly than the default (and also explains it quite well):

```<code>start-stop-daemon --start --background \
            --pidfile $PIDFILE --make-pidfile --startas /bin/bash \
            -- -c "exec stdbuf -oL -eL $DAEMON $DAEMONARGS > $LOGFILE 2>&1"
</code>```

Title: start-stop-daemon and python

Body:
I'm trying to start python script with start-stop-daemon:

sudo /sbin/start-stop-daemon --start --pidfile /home/loop.pid \
--user www-data --group www-data -b --make-pidfile --chuid www-data \
--exec /usr/bin/python /home/loop.py --verbose

but no python script in my processes. What i do wrong?

loop.py:

import time
while True:
    print "working..."
    time.sleep(3)

Body:
Rather than exec python directly, if you --exec (or --startas) a nested shell, then you can do the redirection in there (as per this answer):

start-stop-daemon --start --quiet --chuid $DAEMONUSER    \
 --make-pidfile --pidfile $PIDFILE --background       \
 --startas /bin/bash -- -c "exec $DAEMON $DAEMON_ARGS > /var/log/some.log 2>&1"

This works for me and logs my Python stdout quite happily once I realized the output was buffered (my script wasn't writing very much)! I then found this article which uses 'stdbuf' to flush to the output more eagerly than the default (and also explains it quite well):

start-stop-daemon --start --background \
            --pidfile $PIDFILE --make-pidfile --startas /bin/bash \
            -- -c "exec stdbuf -oL -eL $DAEMON $DAEMONARGS > $LOGFILE 2>&1"


问:
Errors running junit test with spring-cloud-task annotation
I have strange errors running junit tests in my spring-cloud-task based app and have not been able to find a cause for this.

This is a fragment of my test class followed by the error stack trace. I've notice that removing the @EnableTask annotation there's no problems running test.

Does anyone has any suggestion?

Thanx

```<code>package eu.wheesbee.cloud.stream.app.discoverit.fundedproject.task.config;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

@DirtiesContext
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FundedProjectImporterBatchTest.FundedProjectImporterTestConfiguration.class,
                        webEnvironment = SpringBootTest.WebEnvironment.NONE)
public abstract class FundedProjectImporterBatchTest {

  @Autowired
  protected ResourceLoader resourceLoader;

  public static class TestBatchConfigurationSuccess extends FundedProjectImporterBatchTest {

    @Test
    public void testBatchConfigurationSuccess() throws Exception {
      System.out.println("-----------------------------------------   Ciao!!!!!!!!");
    }
  }

  @EnableTask
  @SpringBootApplication
  public static class FundedProjectImporterTestConfiguration {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
     protected void initialize() {
      ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
      populator.addScript(resourceLoader.getResource("classpath:db/schema-all.sql"));
      populator.addScript(resourceLoader.getResource("classpath:db/data.sql"));
      populator.setContinueOnError(false);

      DatabasePopulatorUtils.execute(populator, dataSource);
    }
  }

}
</code>```

Here the stacktrace :

```<code>java.lang.IllegalStateException: The ApplicationContext loaded for [[MergedContextConfiguration@69b794e2 testClass = FundedProjectImporterBatchTest.TestBatchConfigurationSuccess, locations = '{}', classes = '{class eu.wheesbee.cloud.stream.app.discoverit.fundedproject.task.config.FundedProjectImporterBatchTest$FundedProjectImporterTestConfiguration, class eu.wheesbee.cloud.stream.app.discoverit.fundedproject.task.config.FundedProjectImporterBatchTest$FundedProjectImporterTestConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@23faf8f2, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@64729b1e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@6895a785, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@ea1a8d5], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]] is not active. Ensure that the context has not been closed programmatically.
    at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:87) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) ~[spring-boot-test-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207) [.cp/:na]
</code>```

答:
I found the solution: use standard @SpringBootTest with @TestPropertySource(properties = {"spring.cloud.task.closecontext_enable=false"} as described here

https://docs.spring.io/spring-cloud-task/docs/1.2.0.M2/reference/htmlsingle/#_writing_your_test

TNX

Body:
I have strange errors running junit tests in my spring-cloud-task based app and have not been able to find a cause for this.

This is a fragment of my test class followed by the error stack trace. I've notice that removing the @EnableTask annotation there's no problems running test.

Does anyone has any suggestion?

Thanx

package eu.wheesbee.cloud.stream.app.discoverit.fundedproject.task.config;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

@DirtiesContext
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FundedProjectImporterBatchTest.FundedProjectImporterTestConfiguration.class,
                        webEnvironment = SpringBootTest.WebEnvironment.NONE)
public abstract class FundedProjectImporterBatchTest {

  @Autowired
  protected ResourceLoader resourceLoader;

  public static class TestBatchConfigurationSuccess extends FundedProjectImporterBatchTest {

    @Test
    public void testBatchConfigurationSuccess() throws Exception {
      System.out.println("-----------------------------------------   Ciao!!!!!!!!");
    }
  }

  @EnableTask
  @SpringBootApplication
  public static class FundedProjectImporterTestConfiguration {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
     protected void initialize() {
      ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
      populator.addScript(resourceLoader.getResource("classpath:db/schema-all.sql"));
      populator.addScript(resourceLoader.getResource("classpath:db/data.sql"));
      populator.setContinueOnError(false);

      DatabasePopulatorUtils.execute(populator, dataSource);
    }
  }

}

Here the stacktrace :

java.lang.IllegalStateException: The ApplicationContext loaded for [[MergedContextConfiguration@69b794e2 testClass = FundedProjectImporterBatchTest.TestBatchConfigurationSuccess, locations = '{}', classes = '{class eu.wheesbee.cloud.stream.app.discoverit.fundedproject.task.config.FundedProjectImporterBatchTest$FundedProjectImporterTestConfiguration, class eu.wheesbee.cloud.stream.app.discoverit.fundedproject.task.config.FundedProjectImporterBatchTest$FundedProjectImporterTestConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@23faf8f2, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@64729b1e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@6895a785, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@ea1a8d5], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]] is not active. Ensure that the context has not been closed programmatically.
    at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:87) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) ~[spring-boot-test-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207) [.cp/:na]


问:
Are there any classification algorithms which target data with a one to many (1:n) relationship?
Has there been any research in the field of data-mining regarding classifying data which has a one to many relationship?

For example of a problem like this, say I am trying to predict which students are going to drop out of university based on their class grades and personal information. Obviously there is a one to many relationship between the students personal information and the grades they achieved in their classes.

Obvious approaches include:

Aggregate - The multiple records could be aggregated together in some way reducing the problem to a basic classification problem. In the case of the student classification, the average of their grades could be combined with their personal data. While this solution is simple, often key information is lost. For example what if most students who take organic chemistry and get below a C- end up dropping out even if their average is above a B+ rating.

Voting - Create multiple classifiers (often weak ones) and have them cast votes to determine the overall class of the data in question. This would be like if two classifiers were built, one for the student's course data and one for their personal data. Each course record would be passed to the course classifier and based on the grade and the course name, the classifier would predict whether the student would drop out using that course record alone. The personal data record would be classified using the personal data classifier. Then all the class record predictions along with the personal information record prediction would be voted together. This voting could be done in a number of different ways, but most likely would take into account how accurate the classifiers are and how certain the classifier was of the vote. Clearly this scheme allows for more complicated classification patterns than aggregation, yet there is a lot of extra complexity involved. Also if the voting is not performed well, accuracy can easily suffer.

So I am looking for other possible solutions to the classification of data with a one to many relationship.

答:
I envision two basic paths forward:

As you call it, the "aggregate" solution, which would utilize various summaries of each student's situation: how many classes were taken, what percent of classes were introductory 101 classes, average grade, lowest quartile grade, etc.

Some type of evidence accumulator, such as a naive Bayes model (as already suggested by Steve) or a fuzzy logic rule base.  Such solutions naturally handle varying amounts of incoming data.  I suppose this could be achieved with enough data, using one giant conventional model (neural network, etc.) and a very large set of inputs (most of which would be set to a neutral value for "missing"), but I doubt it would work as well as other options.

Sorry, but I think the "gang of simple solutions" would be weak in this particular case.  That's not to say that it wouldn't work, but I'd start somewhere else.

ContentLicense: CC BY-SA 2.5


问:
Execute Docker Run and check parameter is not empty
How do I check if the parameter ENV  was passed while executing the docker run.

I want to display an error message if the paramenter is not passed.

Thanks

答:
You could do this, inside your StartUP Script for the Service.</p>

```<code>#!/bin/bash
if [ -z "$VARIABLE" ]; then
  echo "The VARIABLE is not set"
  exit 1
fi
</code>```

Body:
You could do this, inside your StartUP Script for the Service.

#!/bin/bash
if [ -z "$VARIABLE" ]; then
  echo "The VARIABLE is not set"
  exit 1
fi


问:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="primary-content">
  <p class="intro">
  Austin, Texas is not only the capital.<br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
  </p>
  <div id="container2">
    <div id="container1">
      <div id="About">
        <h2>About</h2>
        <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.
        </p>
      <!-- Column one end -->
      </div>
      <div id="Capitalbuilding">
      <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
      <!-- Column two end -->
      </div>
    </div>
  </div>
</div><!-- End .primary-content --></code>```

答:
If you don't want to use any framework(like bootstrap) just add float to your container and add overflow:hidden to the parent container.</p>

```<code><div class="wrapper">
    <div class="col-1">Your content here</div>
    <div class="col-2">Your content here</div>
</div>

.wrapper {
    overflow:hidden;
}
.col-1, .col-2 {
    float:left;
    width: 50%;
}
</code>```

Body:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}

  Austin, Texas is not only the capital.
It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.

About

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.

Body:
If you don't want to use any framework(like bootstrap) just add float to your container and add overflow:hidden to the parent container.

<div class="wrapper">
    <div class="col-1">Your content here</div>
    <div class="col-2">Your content here</div>
</div>

.wrapper {
    overflow:hidden;
}
.col-1, .col-2 {
    float:left;
    width: 50%;
}