问:
Why does `overflow:hidden` prevent `position:sticky` from working?
In the following snippet, there is a sticky div positioned inside a container. It sticks to the top of the scrolling panel while staying inside its container all the time. This is the same behavior as that of the UITableView headers on iOS, where the headers stay visible until the next header is at the top.

In the second snippet, everything is the same except that the container has an overflow:hidden CSS rule. This seems to prevent the position:sticky behavior from working correctly.

.parent {
  position: relative;
  background: #ccc;
  width: 500px;
  height: 150px;
  overflow: auto;
  margin-bottom: 20px;
}

.hidden-overflow {
  overflow: hidden;
}

.sticky {
  position: sticky;
  background: #333;
  text-align: center;
  color: #fff;
  top: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div>
    <div class="sticky">
      Hi, I am a sticky inside the container which contains the first paragraph.
    </div>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.
    </p>
  </div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat
    nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
    himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.
  </p>
  <p>
    Integer congue augue a quam tincidunt, vitae dictum sem iaculis. Proin feugiat nibh vitae leo facilisis, eget laoreet augue dictum. Nunc facilisis tempor feugiat. Aenean eget interdum diam. Maecenas non risus iaculis, scelerisque ipsum eu, facilisis urna.
    Integer velit justo, vestibulum vel vulputate vel, bibendum eu lorem. Phasellus viverra nisl a mi pretium eleifend.
  </p>
</div>
<div class="parent">
  <div class="hidden-overflow">
    <div class="sticky">
      Hi, I am another sticky in the container which contains the first paragraph, but my container has overflow:hidden.
    </div>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.
    </p>
  </div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat
    nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
    himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.
  </p>
  <p>
    Integer congue augue a quam tincidunt, vitae dictum sem iaculis. Proin feugiat nibh vitae leo facilisis, eget laoreet augue dictum. Nunc facilisis tempor feugiat. Aenean eget interdum diam. Maecenas non risus iaculis, scelerisque ipsum eu, facilisis urna.
    Integer velit justo, vestibulum vel vulputate vel, bibendum eu lorem. Phasellus viverra nisl a mi pretium eleifend.
  </p>
</div></code>```

(Snippet adapted from @Daniel's here)

Why doesn't position:sticky work in a container with overflow:hidden?

答:
overflow: hidden is not preventing position: sticky from working. But if you set overflow to hidden on any ancestor of your sticky element, then this ancestor element will be the scrolling container for your sticky element. If you switch the overflow value on your ancestor from hidden to scroll and scroll this ancestor (not the window), then you can see that sticky is still working.

See also https://github.com/wilddeer/stickyfill#pro-tips:

Any non-default value (not visible) for overflow, overflow-x, or
  overflow-y on any of the predecessor elements anchors the sticky to
  the overflow context of that predecessor. Simply speaking, scrolling
  the predecessor will cause the sticky to stick, scrolling the window
  will not. This is expected with overflow: auto and overflow: scroll,
  but often causes problems and confusion with overflow: hidden.

Or http://www.coreyford.name/files/position-sticky-presentation/:

The box's position depends on its containing block (established as for
  position:static) as well as its scrolling container, defined by the
  nearest ancestor in the same document with a computed value for
  'overflow-x' or 'overflow-y' other than 'visible', or the viewport if
  no such ancestor exists.

Or the CSS Positioned Layout Module Level 3
W3C Working Draft:

A stickily positioned box is positioned similarly to a relatively
  positioned box, but the offset is computed with reference to the
  nearest ancestor with a scrolling box, or the viewport if no ancestor
  has a scrolling box.

Body:
In the following snippet, there is a sticky div positioned inside a container. It sticks to the top of the scrolling panel while staying inside its container all the time. This is the same behavior as that of the UITableView headers on iOS, where the headers stay visible until the next header is at the top.

In the second snippet, everything is the same except that the container has an overflow:hidden CSS rule. This seems to prevent the position:sticky behavior from working correctly.

.parent {
  position: relative;
  background: #ccc;
  width: 500px;
  height: 150px;
  overflow: auto;
  margin-bottom: 20px;
}

.hidden-overflow {
  overflow: hidden;
}

.sticky {
  position: sticky;
  background: #333;
  text-align: center;
  color: #fff;
  top: 10px;
}

      Hi, I am a sticky inside the container which contains the first paragraph.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat
    nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
    himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.

    Integer congue augue a quam tincidunt, vitae dictum sem iaculis. Proin feugiat nibh vitae leo facilisis, eget laoreet augue dictum. Nunc facilisis tempor feugiat. Aenean eget interdum diam. Maecenas non risus iaculis, scelerisque ipsum eu, facilisis urna.
    Integer velit justo, vestibulum vel vulputate vel, bibendum eu lorem. Phasellus viverra nisl a mi pretium eleifend.

      Hi, I am another sticky in the container which contains the first paragraph, but my container has overflow:hidden.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus volutpat sed metus et porttitor. Integer bibendum lacus eget massa ultricies fermentum. Donec cursus magna eu congue posuere. Sed eget ligula quam. Sed laoreet enim sapien, eget volutpat
    nisl pellentesque vel. Nulla id dolor sed dolor sodales tristique. Curabitur feugiat massa sed massa bibendum semper et ac orci. In imperdiet nibh quis iaculis viverra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
    himenaeos. Quisque vestibulum, nunc non volutpat tristique, nisl nisi volutpat nibh, quis pulvinar purus ex nec justo. Sed a cursus turpis. Quisque nulla odio, lacinia quis vestibulum sit amet, elementum laoreet nisi. Etiam aliquet ligula sagittis,
    consectetur ipsum sit amet, sodales augue.

    Integer congue augue a quam tincidunt, vitae dictum sem iaculis. Proin feugiat nibh vitae leo facilisis, eget laoreet augue dictum. Nunc facilisis tempor feugiat. Aenean eget interdum diam. Maecenas non risus iaculis, scelerisque ipsum eu, facilisis urna.
    Integer velit justo, vestibulum vel vulputate vel, bibendum eu lorem. Phasellus viverra nisl a mi pretium eleifend.

(Snippet adapted from @Daniel's here)

Why doesn't position:sticky work in a container with overflow:hidden?


来源: stackexchange

问:
Error calling function _this3.xxxxx() is not a function
Hi I am getting the following error when clicking on a TouchableOpacity that is created within a loop.

The TouchableOpacity that calls it is here

```<code>    constructor() {

    super();

    this.pressRowContact = this.pressRowContact.bind(this);
    this.fetchData = this.fetchData.bind(this);
    this.goBack = this.goBack.bind(this);
    this.onAddedContactPress = this.onAddedContactPress.bind(this);
    this.sendMessage = this.sendMessage.bind(this);

    this.state = {
      loadingVisible: false,
      inputText: "",
      arrayContactsSelected: [],
      dataContactList: [],
      showContactList: false,
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  onChangeTextHandler = (e) => {
    this.textInputValue = e;
  }

  onAddedContactPress(){}

  render() {

    const { navigate } = this.props.navigation;

    console.log(this.state.showContactList);

    if(this.state.showContactList == true){
        var contactListView = <View style={styles.contactListWrapper}>
            <FlatList
                data = {this.state.dataContactList}
                renderItem={({item}) => <TouchableOpacity onPress={() => this.pressRowContact( item )} >
                <View style={styles.contactRow}>
                    <View style={styles.standardProfilePicWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 30, height: 30}}/>
                    </View>
                    <Text>Someone Name Here</Text>
                </View>
            </TouchableOpacity>}
            />
        </View>
    }else {
        var contactListView;
    }

    var selectedUsers = this.state.arrayContactsSelected.map(function(item) {
        return (
            <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.userID} style={styles.selectedUserItem} >
                <View style={styles.smallProfilePictureWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 14, height: 14}}/>
                    </View>
                <Text style={styles.contactSelectedName} >Oliver Rice</Text>
            </TouchableOpacity>
        );
     });

    /*<TextInput
                            style={styles.addContactInput}
                            onChangeText={this.onChangeTextHandler}
                            value={this.state.inputText}
                          />*/

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="NEW MESSAGE" backButton={true} />
            </View>
            <View style={styles.contentWrapper}>
                <View style={styles.addContactWrapper} >
                    <View style={styles.addContactLeft} >
                        <Text style={styles.contactTo}>To:</Text>
                    </View>
                    <View style={styles.addContactRight} >
                        {selectedUsers}
                        <TouchableOpacity style={styles.addedContactWrapper} onPress={() => this.showContacts("")}>
                            <Image source={require('../../images/icons/IconAddContact.png')} style={{width: 18, height: 18}}/>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={styles.mainContentWrapper} >
                    {contactListView}
                    <TextInput
                        style={styles.inputTextMainMessage}
                        multiline={true}
                        placeholder="Your message here"
                        blurOnSubmit={true}
                    />
                </View>
                <TouchableOpacity onPress={() => this.sendMessage( )} style={styles.buttonWrapper} >
                    <Text style={styles.sendMessage}>Send Message</Text>
                </TouchableOpacity>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }
</code>```

I thought I could solve the issue by adding this.onAddedContactPress = this.onAddedContactPress.bind(this); in the constructor but it isn't having any impact.

答:
onAddedContactPress must be outside of rendering function if you want to call this. this refer to the component itself. For es6 syntax, try

```<code>onAddedContactPress = (item) => {
    console.log(item);
}

render() {
   return (
     this.state.arrayContactsSelected.map(function(item) {
      <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.userID} style={styles.selectedUserItem} >
        <View style={styles.smallProfilePictureWrapper}>
                <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 14, height: 14}}/>
            </View>
        <Text style={styles.contactSelectedName} >Name</Text>
      </TouchableOpacity> }
   );
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I am getting the following error when clicking on a TouchableOpacity that is created within a loop.

The TouchableOpacity that calls it is here

    constructor() {

    super();

    this.pressRowContact = this.pressRowContact.bind(this);
    this.fetchData = this.fetchData.bind(this);
    this.goBack = this.goBack.bind(this);
    this.onAddedContactPress = this.onAddedContactPress.bind(this);
    this.sendMessage = this.sendMessage.bind(this);

    this.state = {
      loadingVisible: false,
      inputText: "",
      arrayContactsSelected: [],
      dataContactList: [],
      showContactList: false,
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  onChangeTextHandler = (e) => {
    this.textInputValue = e;
  }

  onAddedContactPress(){}

  render() {

    const { navigate } = this.props.navigation;

    console.log(this.state.showContactList);

    if(this.state.showContactList == true){
        var contactListView = <View style={styles.contactListWrapper}>
            <FlatList
                data = {this.state.dataContactList}
                renderItem={({item}) => <TouchableOpacity onPress={() => this.pressRowContact( item )} >
                <View style={styles.contactRow}>
                    <View style={styles.standardProfilePicWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 30, height: 30}}/>
                    </View>
                    <Text>Someone Name Here</Text>
                </View>
            </TouchableOpacity>}
            />
        </View>
    }else {
        var contactListView;
    }

    var selectedUsers = this.state.arrayContactsSelected.map(function(item) {
        return (
            <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.userID} style={styles.selectedUserItem} >
                <View style={styles.smallProfilePictureWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 14, height: 14}}/>
                    </View>
                <Text style={styles.contactSelectedName} >Oliver Rice</Text>
            </TouchableOpacity>
        );
     });

    /*<TextInput
                            style={styles.addContactInput}
                            onChangeText={this.onChangeTextHandler}
                            value={this.state.inputText}
                          />*/

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="NEW MESSAGE" backButton={true} />
            </View>
            <View style={styles.contentWrapper}>
                <View style={styles.addContactWrapper} >
                    <View style={styles.addContactLeft} >
                        <Text style={styles.contactTo}>To:</Text>
                    </View>
                    <View style={styles.addContactRight} >
                        {selectedUsers}
                        <TouchableOpacity style={styles.addedContactWrapper} onPress={() => this.showContacts("")}>
                            <Image source={require('../../images/icons/IconAddContact.png')} style={{width: 18, height: 18}}/>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={styles.mainContentWrapper} >
                    {contactListView}
                    <TextInput
                        style={styles.inputTextMainMessage}
                        multiline={true}
                        placeholder="Your message here"
                        blurOnSubmit={true}
                    />
                </View>
                <TouchableOpacity onPress={() => this.sendMessage( )} style={styles.buttonWrapper} >
                    <Text style={styles.sendMessage}>Send Message</Text>
                </TouchableOpacity>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }

I thought I could solve the issue by adding this.onAddedContactPress = this.onAddedContactPress.bind(this); in the constructor but it isn't having any impact.

Body:
onAddedContactPress must be outside of rendering function if you want to call this. this refer to the component itself. For es6 syntax, try

onAddedContactPress = (item) => {
    console.log(item);
}

render() {
   return (
     this.state.arrayContactsSelected.map(function(item) {
      <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.userID} style={styles.selectedUserItem} >
        <View style={styles.smallProfilePictureWrapper}>
                <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 14, height: 14}}/>
            </View>
        <Text style={styles.contactSelectedName} >Name</Text>
      </TouchableOpacity> }
   );
}


问:
While coding, an error of "name not defined" is generated
I was coding for the question "Write a Python function that takes two lists and returns True if they have at least one common member"

Code:

```<code>first = [a,b,c,d,e,f]
second = [a,s,d,f,g,h]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")
</code>```

Error:

```<code>first = list[a,b,c,d,e,f]
NameError: name 'a' is not defined
</code>```

How can I fix this?

答:
You need to use quotes for strings.</p>

```<code>first = ['a', 'b', 'c', 'd', 'e', 'f']
second = ['a', 's', 'd', 'f', 'g', 'h']
</code>```

Body:
I was coding for the question "Write a Python function that takes two lists and returns True if they have at least one common member"

Code:

first = [a,b,c,d,e,f]
second = [a,s,d,f,g,h]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")

Error:

first = list[a,b,c,d,e,f]
NameError: name 'a' is not defined

How can I fix this?

Body:
You need to use quotes for strings.

first = ['a', 'b', 'c', 'd', 'e', 'f']
second = ['a', 's', 'd', 'f', 'g', 'h']


问:
Oracle 9i: Supposedly missing right parenthesis
I have a simple function written in Oracle 9i (version 9.2.0.4.0) to simulate an in-line IF. For those interested, here's the code:

```<code>create or replace
FUNCTION IIF
   (testExpression NUMBER,
    trueResult NUMBER,
    falseResult NUMBER)
RETURN NUMBER
AS
BEGIN
   /*
      A simple in-line IF function for use with SQL queries. If the test
      expression evaluates to any non-zero value, it is considered to be
      true, and the trueResult is returned. Otherwise, falseResult is
      returned.
   */
   IF (testExpression is null) or (testExpression = 0) THEN
      return falseResult;
   ELSE
      return trueResult;
   END IF;
END IIF;
</code>```

This isn't rocket science. Now, here's the big mystery: if I execute the following SQL statements, everything is just fine, and works exactly as I expect:

```<code>SELECT IIF(1, 'true', 'false') FROM DUAL;
SELECT IIF(0, 'false', 'true') FROM DUAL;
</code>```

However, the following generates a really bizarre error from Oracle:

```<code>SELECT IIF((0 = 1), 'false', 'true') FROM DUAL;
</code>```

That error is as follows:

```<code>ORA-00907: missing right parenthesis.
</code>```

Clearly, that isn't the case. Would anyone happen to have an explanation for this little bit of bizarreness?

It's taking a whole lot of self-control at the moment to restrain myself from hurling the Oracle server out the window. Oracle seems rife with these kinds of inanities.

EDIT: Is there some kind of magic syntax I have to use to use an equality operator in a select statement?

答:
You want

```<code>SELECT CASE WHEN *expr* then 'true' else 'false' end col_alias FROM DUAL;
</code>```

or for simple equality test

```<code>SELECT DECODE(*val1*,*val2*,'true','false') col_alias FROM dual;
</code>```

This will perform much better than dropping out to a PL/SQL function.
There's a number of reasons why your approach doesn't work.

Booleans aren't an Oracle data type.

They are a PL/SQL datatype, but even then there's no implicit conversion to numbers (zero false, non-zero true)

There's no 'expression' datatype, so the SQL engine can't pass the expression to PL/SQL.

Even if you passes the expression as a string to PL/SQL, the PL/SQL engine cannot dynamically evaluate an expression in a string. It would have to build the string into a dynamic SQL statement and execute that dynamically, returning a result (in a valid SQL datatype, like a string or number).

OwnerDisplayName: Mike Hofer

ContentLicense: CC BY-SA 2.5

Body:
I have a simple function written in Oracle 9i (version 9.2.0.4.0) to simulate an in-line IF. For those interested, here's the code:

create or replace
FUNCTION IIF
   (testExpression NUMBER,
    trueResult NUMBER,
    falseResult NUMBER)
RETURN NUMBER
AS
BEGIN
   /*
      A simple in-line IF function for use with SQL queries. If the test
      expression evaluates to any non-zero value, it is considered to be
      true, and the trueResult is returned. Otherwise, falseResult is
      returned.
   */
   IF (testExpression is null) or (testExpression = 0) THEN
      return falseResult;
   ELSE
      return trueResult;
   END IF;
END IIF;

This isn't rocket science. Now, here's the big mystery: if I execute the following SQL statements, everything is just fine, and works exactly as I expect:

SELECT IIF(1, 'true', 'false') FROM DUAL;
SELECT IIF(0, 'false', 'true') FROM DUAL;

However, the following generates a really bizarre error from Oracle:

SELECT IIF((0 = 1), 'false', 'true') FROM DUAL;

That error is as follows:

ORA-00907: missing right parenthesis.

Clearly, that isn't the case. Would anyone happen to have an explanation for this little bit of bizarreness?

It's taking a whole lot of self-control at the moment to restrain myself from hurling the Oracle server out the window. Oracle seems rife with these kinds of inanities.

EDIT: Is there some kind of magic syntax I have to use to use an equality operator in a select statement?

Body:
You want

SELECT CASE WHEN *expr* then 'true' else 'false' end col_alias FROM DUAL;

or for simple equality test

SELECT DECODE(*val1*,*val2*,'true','false') col_alias FROM dual;

This will perform much better than dropping out to a PL/SQL function.
There's a number of reasons why your approach doesn't work.

Booleans aren't an Oracle data type.

They are a PL/SQL datatype, but even then there's no implicit conversion to numbers (zero false, non-zero true)

There's no 'expression' datatype, so the SQL engine can't pass the expression to PL/SQL.

Even if you passes the expression as a string to PL/SQL, the PL/SQL engine cannot dynamically evaluate an expression in a string. It would have to build the string into a dynamic SQL statement and execute that dynamically, returning a result (in a valid SQL datatype, like a string or number).

ContentLicense: CC BY-SA 4.0


问:
Segmentation fault (SIGSEGV) using boost asio 1.64 when trying to close a SSL socket
I don't understand how I must close a boost::asio ssl socket. I have tried it in several ways but it always raises a Segmentation fault in some moment.

I have been reading the following post to solve this situation:
boost asio ssl async_shutdown always finishes with an error?

Specifically, I am trying to implement the

PartyA initiates shutdown() and waits for PartyB to respond with a
  shutdown()

Notice that both the client and the server are running in localhost.

Below is the client code:

```<code>typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLSocket;

MyClass::MyClass(const std::string &url,
    const std::string &port) throw() :
    m_socket(NULL), m_url(url), m_port(port), m_isConnected(false)
{
}

void MyClass::disconnect()
{
  // See the section "the disconnect method"
}

bool MyClass::tryConnect() throw()
{
  boost::asio::io_service ioService;
  boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
  m_socket = new SSLSocket(ioService, ctx);

  tcp::resolver resolver(ioService);
  tcp::resolver::query query(m_url, m_port);

  tcp::resolver::iterator end;
  tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

  boost::system::error_code error = boost::asio::error::host_not_found;
  boost::asio::connect(m_socket->lowest_layer(), endpoint_iterator, error);

  if(endpoint_iterator == end || error)
  {
    m_isConnected = false;
  }
  else
  {
    m_socket->set_verify_mode(boost::asio::ssl::verify_none);
    m_socket->handshake(SSLSocket::client);

    m_isConnected = true;
  }

  return m_isConnected;
}

void MyClass::write(const std::string &message)
{
  boost::asio::write(*m_socket, boost::asio::buffer(message));
}

std::string MyClass::readUntil(const std::string &until)
{
  boost::asio::read_until(*m_socket, response, until);
  ...
  return response;
}

int main()
{
  MyClass mc(...);

  while(true)
  {
    bool connected = mc.isConnected();

    if(!connected)
    {
      connected = mc.tryConnect();
    }

    if(connected)
    {
      mc.send(...);
      std::string resp = mc.readUntil(...);
      mc.disconnect();
    }
  }
}
</code>```

The disconnect method

I have read the post linked in the comments and I have updated both the ssl server and the client. Now, both of them perform the shutdown() operation to close the ssl connection properly, but I still have an error when closing the socket.

I have updated the disconnect() method (which is always where the program crashes) as following:

```<code>...
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> *m_socket;
...
void MyClass::disconnect()
{
  // Shutdown the connection
  // TODO is this the correct way to close a boost asio socket?
  if(m_socket != NULL)
  {
    std::cout << "shutting down the socket, thread = " <<
        pthread_self() << std::endl;

    // I have checked that the thread is always the same, so the problem
    // is not related with race conditions or similar.

    boost::system::error_code ec;
    m_socket->lowest_layer().shutdown(
        boost::asio::ip::tcp::socket::shutdown_both, ec);

    std::cout <<
        "Shut down, err = " << ec << ", " <<
        "Category: " << ec.category().name() << std::endl;

    if(!ec)
    {
      std::cout << "closing the socket, thread = " <<
         pthread_self() << std::endl;

      if(m_socket->lowest_layer().is_open())
      {
        m_socket->lowest_layer().close(ec);
      }

      std::cout <<
        "Socket closed, err = " << ec << ", " <<  "Category: " <<
        ec.category().name() << std::endl;

      if(!ec)
      {
        std::cout << "Deleting socket... " << std::endl;
        delete m_socket;
        m_socket = NULL;
        std::cout << "Socket deleted" << std::endl;
      }
    }
  }

  m_isConnected = false;
}
</code>```

The error backtrace

The bkactrace (from the disconnect method) is here:

```<code>#0  0x4158114f in boost::system::error_code::operator=<boost::asio::error::basic_errors> (this=0x1d, val=boost::asio::error::operation_aborted)
    at .../include/boost/system/error_code.hpp:344
#1  0x41587308 in boost::asio::detail::epoll_reactor::deregister_descriptor (this=0x46463045, descriptor=27, descriptor_data=@0x812ef14: 0x8151ea8,
    closing=true) at .../include/boost/asio/detail/impl/epoll_reactor.ipp:351
#2  0x41588550 in boost::asio::detail::reactive_socket_service_base::close (this=0x812efbc, impl=..., ec=...)
    at .../include/boost/asio/detail/impl/reactive_socket_service_base.ipp:104
#3  0x415885da in boost::asio::stream_socket_service<boost::asio::ip::tcp>::close (this=0x812efa8, impl=..., ec=...)
    at .../include/boost/asio/stream_socket_service.hpp:174
#4  0x41588630 in boost::asio::basic_socket<boost::asio::ip::tcp, boost::asio::stream_socket_service<boost::asio::ip::tcp> >::close (this=0x812ef08, ec=...)
    at .../include/boost/asio/basic_socket.hpp:385
#5  0x41576383 in MyClass::disconnect (this=0x80a6f58) at ...
</code>```

Inspecting the frame 1, it can be seen that the error that boost is creating is boost::asio::error::operation_aborted;

In addition, running the process with gdb, simetimes I see the following assertion failure:

```<code>pthread_mutex_lock.c:312: __pthread_mutex_lock_full: Assertion `(-(e)) != 3 || !robust' failed.
</code>```

答:
I have found the problem.

I was openning the socket in a method like:

```<code>void connect()
{
  ...
  boost::asio::io_service m_ioService
  ...
  m_sock = new SSLSocket(m_ioService, ...)
}
</code>```

When the connect method returns, m_ioService is out of scope, so the socket crashes since the ioService has been deleted. Notice that the m_ioService is passed by reference, moreover, it is non-copyable.

Body:
I don't understand how I must close a boost::asio ssl socket. I have tried it in several ways but it always raises a Segmentation fault in some moment.

I have been reading the following post to solve this situation:
boost asio ssl async_shutdown always finishes with an error?

Specifically, I am trying to implement the

PartyA initiates shutdown() and waits for PartyB to respond with a
  shutdown()

Notice that both the client and the server are running in localhost.

Below is the client code:

typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLSocket;

MyClass::MyClass(const std::string &url,
    const std::string &port) throw() :
    m_socket(NULL), m_url(url), m_port(port), m_isConnected(false)
{
}

void MyClass::disconnect()
{
  // See the section "the disconnect method"
}

bool MyClass::tryConnect() throw()
{
  boost::asio::io_service ioService;
  boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
  m_socket = new SSLSocket(ioService, ctx);

  tcp::resolver resolver(ioService);
  tcp::resolver::query query(m_url, m_port);

  tcp::resolver::iterator end;
  tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

  boost::system::error_code error = boost::asio::error::host_not_found;
  boost::asio::connect(m_socket->lowest_layer(), endpoint_iterator, error);

  if(endpoint_iterator == end || error)
  {
    m_isConnected = false;
  }
  else
  {
    m_socket->set_verify_mode(boost::asio::ssl::verify_none);
    m_socket->handshake(SSLSocket::client);

    m_isConnected = true;
  }

  return m_isConnected;
}

void MyClass::write(const std::string &message)
{
  boost::asio::write(*m_socket, boost::asio::buffer(message));
}

std::string MyClass::readUntil(const std::string &until)
{
  boost::asio::read_until(*m_socket, response, until);
  ...
  return response;
}

int main()
{
  MyClass mc(...);

  while(true)
  {
    bool connected = mc.isConnected();

    if(!connected)
    {
      connected = mc.tryConnect();
    }

    if(connected)
    {
      mc.send(...);
      std::string resp = mc.readUntil(...);
      mc.disconnect();
    }
  }
}

The disconnect method

I have read the post linked in the comments and I have updated both the ssl server and the client. Now, both of them perform the shutdown() operation to close the ssl connection properly, but I still have an error when closing the socket.

I have updated the disconnect() method (which is always where the program crashes) as following:

...
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> *m_socket;
...
void MyClass::disconnect()
{
  // Shutdown the connection
  // TODO is this the correct way to close a boost asio socket?
  if(m_socket != NULL)
  {
    std::cout << "shutting down the socket, thread = " <<
        pthread_self() << std::endl;

    // I have checked that the thread is always the same, so the problem
    // is not related with race conditions or similar.

    boost::system::error_code ec;
    m_socket->lowest_layer().shutdown(
        boost::asio::ip::tcp::socket::shutdown_both, ec);

    std::cout <<
        "Shut down, err = " << ec << ", " <<
        "Category: " << ec.category().name() << std::endl;

    if(!ec)
    {
      std::cout << "closing the socket, thread = " <<
         pthread_self() << std::endl;

      if(m_socket->lowest_layer().is_open())
      {
        m_socket->lowest_layer().close(ec);
      }

      std::cout <<
        "Socket closed, err = " << ec << ", " <<  "Category: " <<
        ec.category().name() << std::endl;

      if(!ec)
      {
        std::cout << "Deleting socket... " << std::endl;
        delete m_socket;
        m_socket = NULL;
        std::cout << "Socket deleted" << std::endl;
      }
    }
  }

  m_isConnected = false;
}

The error backtrace

The bkactrace (from the disconnect method) is here:

#0  0x4158114f in boost::system::error_code::operator=<boost::asio::error::basic_errors> (this=0x1d, val=boost::asio::error::operation_aborted)
    at .../include/boost/system/error_code.hpp:344
#1  0x41587308 in boost::asio::detail::epoll_reactor::deregister_descriptor (this=0x46463045, descriptor=27, descriptor_data=@0x812ef14: 0x8151ea8,
    closing=true) at .../include/boost/asio/detail/impl/epoll_reactor.ipp:351
#2  0x41588550 in boost::asio::detail::reactive_socket_service_base::close (this=0x812efbc, impl=..., ec=...)
    at .../include/boost/asio/detail/impl/reactive_socket_service_base.ipp:104
#3  0x415885da in boost::asio::stream_socket_service<boost::asio::ip::tcp>::close (this=0x812efa8, impl=..., ec=...)
    at .../include/boost/asio/stream_socket_service.hpp:174
#4  0x41588630 in boost::asio::basic_socket<boost::asio::ip::tcp, boost::asio::stream_socket_service<boost::asio::ip::tcp> >::close (this=0x812ef08, ec=...)
    at .../include/boost/asio/basic_socket.hpp:385
#5  0x41576383 in MyClass::disconnect (this=0x80a6f58) at ...

Inspecting the frame 1, it can be seen that the error that boost is creating is boost::asio::error::operation_aborted;

In addition, running the process with gdb, simetimes I see the following assertion failure:

pthread_mutex_lock.c:312: __pthread_mutex_lock_full: Assertion `(-(e)) != 3 || !robust' failed.

Body:
I have found the problem.

I was openning the socket in a method like:

void connect()
{
  ...
  boost::asio::io_service m_ioService
  ...
  m_sock = new SSLSocket(m_ioService, ...)
}

When the connect method returns, m_ioService is out of scope, so the socket crashes since the ioService has been deleted. Notice that the m_ioService is passed by reference, moreover, it is non-copyable.


问:
Liferay Control panel programmatic access
I'm trying to fetch the setting value of the email reply address with:

PropsUtil.get(PropsKeys.ADMIN_EMAIL_FROM_ADDRESS)

But this returns the original value from the portal-ext.properties file, which has since been updated in the Control panel to a different value.

What *Service or *Util do I use to access settings in the Liferay control panel?

I've hunted through the source of Liferay but I can't seem to find a way.

Any ideas?

答: Use PrefsPropsUtil instead of PropsUtil

Body: Use PrefsPropsUtil instead of PropsUtil


问:
Conditional statement- compare to values store in array
Need help figuring out working perl code to put in place of "any of the elements in @array" </p>

```<code>%hash = (key1 => 'value1',key2 => 'value2',key3 => 'value3',);

@array= ('value3','value4','value6');

if ($hash{ 'key1' } ne <<any of the elements in @array>>) {print "YAY!";}
</code>```

答:
A 5.10+ solution: Use a smart-match!</p>

```<code>say 'Modern Yay!' unless $hash{$key} ~~ @array;
</code>```

Body:
Need help figuring out working perl code to put in place of "any of the elements in @array"

%hash = (key1 => 'value1',key2 => 'value2',key3 => 'value3',);

@array= ('value3','value4','value6');

if ($hash{ 'key1' } ne <<any of the elements in @array>>) {print "YAY!";}

Body:
A 5.10+ solution: Use a smart-match!

say 'Modern Yay!' unless $hash{$key} ~~ @array;


问:
Open non text file without windows line ending
I took over a project that use the following function to read files:

```<code>char *fetchFile(char *filename) {
    char *buffer;
    int len;
    FILE *f = fopen(filename, "rb");
    if(f) {
        if(verbose) {
            fprintf(stdout, "Opened file %s successfully\n", filename);
        }
        fseek(f, 0, SEEK_END);
        len = ftell(f);
        fseek(f, 0, SEEK_SET);
        if(verbose) {
            fprintf(stdout, "Allocating memory for buffer for %s\n", filename);
        }
        buffer = malloc(len + 1);
        if(buffer) fread (buffer, 1, len, f);
        fclose (f);
        buffer[len] = '\0';
    } else {
        fprintf(stderr, "Error reading file %s\n", filename);
        exit(1);
    }
    return buffer;
}
</code>```

The rb mode is used because sometimes the file can be a spreadsheet and therefore I want the information as in a text file.

The program runs on a linux machine but the files to read come from linux and windows.

I am not sure of what approach is better to not have windows line ending mess with my code.

I was thinking of using dos2unix at the start of this function.
I also thought of opening in r mode, but I believe that could potentially mess things up when opening non-text files.

I would like to understand better the differences between using:

dos2unix,

r vs rb mode,

or any other solution which would fit
better the problem.

Note: I believe that I understand r vs rb modes, but if you could explain why it is a bad or good solution for this specific situation (I think it wouldn't be good because sometimes it opens spreadsheets but I am not sure of that).

答:
If my understanding is correct the rb mode is used because sometimes the file can be a spreadsheet and therefore the programs just want the information as in a text file.

You seem uncertain, and though perhaps you do understand correctly, your explanation does not give me any confidence in that.

C knows about two distinct kinds of streams: binary streams and text streams.  A binary stream is simply an ordered sequence of bytes, written and / or read as-is without any kind of transformation.  On the other hand,

A text stream is an ordered sequence of characters composed into
  lines, each line consisting of zero or more characters plus a
  terminating new-line character. Whether the last line requires a
  terminating new-line character is implementation-defined. Characters
  may have to be added, altered, or deleted on input and output to
  conform to differing conventions for representing text in the host
  environment. Thus, there need not be a one- to-one correspondence
  between the characters in a stream and those in the external
  representation. [...]

(C2011 7.21.2/2)

For some implementations, such as POSIX-compliant ones, this is a distinction without a difference.  For other implementations, such as those targeting Windows, the difference matters.  In particular, on Windows, text streams convert on the fly between carriage-return / line-feed pairs in the external representation and newlines (only) in the internal representation.

The b in your fopen() mode specifies that the file should be opened as a binary stream -- that is, no translation will be performed on the bytes read from the file.  Whether this is the right thing to do depends on your environment and the application's requirements.  This is moot on Linux or another Unix, however, as there is no observable difference between text and binary streams on such systems.

dos2unix converts carriage-return / line-feed pairs in the input file to single line-feed (newline) characters.  This will convert a Windows-style text file or one with mixed Windows / Unix line terminators to Unix text file convention.  It is irreversible if there are both Windows-style and Unix-style line terminators in the file, and it is furthermore likely to corrupt your file if it is not a text file in the first place.

If your inputs are sometimes binary files then opening in binary mode is appropriate, and conversion via dos2unix probably is not.  If that's the case and you also need translation for text-file line terminators, then you first and foremost need a way to distinguish which case applies for any particular file -- for example, by command-line argument or by pre-analyzing the file via libmagic.  You then must provide different handling for text files; your main options are

Perform the line terminator conversion in your own code.

Provide separate versions of the fetchFile() function for text and binary files.

Body:
I took over a project that use the following function to read files:

char *fetchFile(char *filename) {
    char *buffer;
    int len;
    FILE *f = fopen(filename, "rb");
    if(f) {
        if(verbose) {
            fprintf(stdout, "Opened file %s successfully\n", filename);
        }
        fseek(f, 0, SEEK_END);
        len = ftell(f);
        fseek(f, 0, SEEK_SET);
        if(verbose) {
            fprintf(stdout, "Allocating memory for buffer for %s\n", filename);
        }
        buffer = malloc(len + 1);
        if(buffer) fread (buffer, 1, len, f);
        fclose (f);
        buffer[len] = '\0';
    } else {
        fprintf(stderr, "Error reading file %s\n", filename);
        exit(1);
    }
    return buffer;
}

The rb mode is used because sometimes the file can be a spreadsheet and therefore I want the information as in a text file.

The program runs on a linux machine but the files to read come from linux and windows.

I am not sure of what approach is better to not have windows line ending mess with my code.

I was thinking of using dos2unix at the start of this function.
I also thought of opening in r mode, but I believe that could potentially mess things up when opening non-text files.

I would like to understand better the differences between using:

dos2unix,

r vs rb mode,

or any other solution which would fit
better the problem.

Note: I believe that I understand r vs rb modes, but if you could explain why it is a bad or good solution for this specific situation (I think it wouldn't be good because sometimes it opens spreadsheets but I am not sure of that).


问:
Would Docker swarm assist me with managing containers with specific environment variables?
Essentially I need to be able to start container with a specific environment variable (an account ID). And I need to run a multiple number of such containers (each with different account IDs).

I'd need to be able to start additional containers, without having to stop the existing containers. I'd also need to be able to stop specific containers. So kind of like a dynamic docker-compose config.

Is Docker swarm something that could assist with the above functionality? Are there other tools (Kubernetes maybe?) alternatively?

Otherwise, if I handled this with the docker-cli, I would start the containers using docker run passing the relevant environment variable, I'd need to make sure that a container does not already exist with this environment variable and restart the container if it exists.

答:
You can create a new service for each account ID and pass that information as an environment variable. Here is an example:

```<code>docker service create --name service-for-account-123 --env accountId=123 imagename:latest
</code>```

To stop the containers of this service you can scale it to zero, like this:

```<code>docker service scale service-for-account-123=0
</code>```

To remove all containers you must remove the service:

```<code>docker service rm service-for-account-123
</code>```

Body:
You can create a new service for each account ID and pass that information as an environment variable. Here is an example:

docker service create --name service-for-account-123 --env accountId=123 imagename:latest

To stop the containers of this service you can scale it to zero, like this:

docker service scale service-for-account-123=0

To remove all containers you must remove the service:

docker service rm service-for-account-123


问:
i am trying to create tables but it show me 2 errors, how i fix it?
2 errors were found during analysis.

Unexpected beginning of statement. (near "admin_id" at position 349)
  Unrecognized statement type. (near "INT" at position 358)

```<code>CREATE TABLE Users (
  user_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  name VARCHAR(50) NOT NULL,
  phone VARCHAR(20) NOT NULL,
  gender VARCHAR(6) NOT NULL,
  fbinfo  VARCHAR(50) NOT NULL,
  age INT NOT NULL,
  PRIMARY KEY (user_id),
  UNIQUE INDEX (email)
)

CREATE TABLE Admin (
  admin_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  PRIMARY KEY (admin_id),
  UNIQUE INDEX (email)
)

CREATE TABLE Task (
  task_id INT NOT NULL AUTO_INCREMENT,
  tex VARCHAR(140) NOT NULL,
  datetime DATE,
  status INT,
  calendar BOOLEAN,
  PRIMARY KEY (task_id),
  lat DECIMAL(9,6),
  long DECIMAL(9,6)
)
</code>```

答:
If you are doing this in one execution, you would need to include a ; at the end of each of your table creation statements.

```<code>CREATE TABLE Users (
  user_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  name VARCHAR(50) NOT NULL,
  phone VARCHAR(20) NOT NULL,
  gender VARCHAR(6) NOT NULL,
  fbinfo  VARCHAR(50) NOT NULL,
  age INT NOT NULL,
  PRIMARY KEY (user_id),
  UNIQUE INDEX (email)
);

CREATE TABLE Admin (
  admin_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  PRIMARY KEY (admin_id),
  UNIQUE INDEX (email)
);

CREATE TABLE Task (
  task_id INT NOT NULL AUTO_INCREMENT,
  tex VARCHAR(140) NOT NULL,
  datetime DATE,
  status INT,
  calendar BOOLEAN,
  PRIMARY KEY (task_id),
  lat DECIMAL(9,6),
  long DECIMAL(9,6)
);
</code>```

Body:
2 errors were found during analysis.

Unexpected beginning of statement. (near "admin_id" at position 349)
  Unrecognized statement type. (near "INT" at position 358)

CREATE TABLE Users (
  user_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  name VARCHAR(50) NOT NULL,
  phone VARCHAR(20) NOT NULL,
  gender VARCHAR(6) NOT NULL,
  fbinfo  VARCHAR(50) NOT NULL,
  age INT NOT NULL,
  PRIMARY KEY (user_id),
  UNIQUE INDEX (email)
)

CREATE TABLE Admin (
  admin_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  PRIMARY KEY (admin_id),
  UNIQUE INDEX (email)
)

CREATE TABLE Task (
  task_id INT NOT NULL AUTO_INCREMENT,
  tex VARCHAR(140) NOT NULL,
  datetime DATE,
  status INT,
  calendar BOOLEAN,
  PRIMARY KEY (task_id),
  lat DECIMAL(9,6),
  long DECIMAL(9,6)
)

Body:
If you are doing this in one execution, you would need to include a ; at the end of each of your table creation statements.

CREATE TABLE Users (
  user_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  name VARCHAR(50) NOT NULL,
  phone VARCHAR(20) NOT NULL,
  gender VARCHAR(6) NOT NULL,
  fbinfo  VARCHAR(50) NOT NULL,
  age INT NOT NULL,
  PRIMARY KEY (user_id),
  UNIQUE INDEX (email)
);

CREATE TABLE Admin (
  admin_id INT NOT NULL AUTO_INCREMENT,
  email VARCHAR(80) NOT NULL,
  password CHAR(41) NOT NULL,
  PRIMARY KEY (admin_id),
  UNIQUE INDEX (email)
);

CREATE TABLE Task (
  task_id INT NOT NULL AUTO_INCREMENT,
  tex VARCHAR(140) NOT NULL,
  datetime DATE,
  status INT,
  calendar BOOLEAN,
  PRIMARY KEY (task_id),
  lat DECIMAL(9,6),
  long DECIMAL(9,6)
);


问:
Deployment and USB device issue
I am using my physical Android device to do the deployment of my project. After I moved the folder to a new location in my computer, I am since unable to select(or even view) my device from the emulator list.

Now I try to run the app on the emulator, which after building gives this error:

It also gives a red line under this piece of code:

```<code>public App()
{
      **InitializeComponent();**

      MainPage = new LoginSystem.MainPage();
}
</code>```

The "Quick Actions" tool tells me that - "The name 'InitializeComponent' does not exist in the current context."

If I remove the initialize component line, I am able to build and deploy my project. However, i really need that line of code. How can I fix it?

UPDATE

After following the link suggested by PiLHA - getting an error on InitializeComponent() on xaml.cs files

I am able to build the project and deploy it, however, i get a new error:

And I am still not able to get the USB connected device to show up in the emulator's list.

I am assuming that there is a problem with the debugger, that is causing the error and not showing the USB device. I have researched quite a bit, yet no solid solution. Please help.

UPDATE 2

I have set my device to allow for debugging. I had been using this device for this purpose before, it's just that this is a new obstacle is am facing at the moment.

答:
For the USB Debug device - it turns out that i just had to "repair" my Visual Studio 2017.

As for the Error:

mono.debugging.soft.connectionexception

I literally created a new project and transferred my folders there. This was the only solution i could come up with, took me hours but now it's done.

Title: Deployment and USB device issue

Body:
I am using my physical Android device to do the deployment of my project. After I moved the folder to a new location in my computer, I am since unable to select(or even view) my device from the emulator list.

Now I try to run the app on the emulator, which after building gives this error:

It also gives a red line under this piece of code:

public App()
{
      **InitializeComponent();**

      MainPage = new LoginSystem.MainPage();
}

The "Quick Actions" tool tells me that - "The name 'InitializeComponent' does not exist in the current context."

If I remove the initialize component line, I am able to build and deploy my project. However, i really need that line of code. How can I fix it?

UPDATE

After following the link suggested by PiLHA - getting an error on InitializeComponent() on xaml.cs files

I am able to build the project and deploy it, however, i get a new error:

And I am still not able to get the USB connected device to show up in the emulator's list.

I am assuming that there is a problem with the debugger, that is causing the error and not showing the USB device. I have researched quite a bit, yet no solid solution. Please help.

UPDATE 2

I have set my device to allow for debugging. I had been using this device for this purpose before, it's just that this is a new obstacle is am facing at the moment.


问:
How can I replace/speed up a text search query which uses LIKE?
I'm trying to speed up my query...

```<code>select PadID from Pads WHERE (keywords like '%$search%' or
ProgramName like '%$search%' or English45 like '%$search%') AND
RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC
</code>```

I've done some work already, I have a keywords table so I can add

```<code>... PadID IN (SELECT PadID FROM Keywords WHERE word = '$search') ...
</code>```

However its going to be a nightmare to split up the words from English45 and ProgramName into a word table.

Any ideas ?
EDIT : (also provided actual table names)

答:
Have you tried FULLTEXT indexing?  Here is a good article about it:

http://devzone.zend.com/article/1304

Also, look into using SOUNDEX functions, that might help, but it might not.

Body:
I'm trying to speed up my query...

select PadID from Pads WHERE (keywords like '%$search%' or
ProgramName like '%$search%' or English45 like '%$search%') AND
RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC

I've done some work already, I have a keywords table so I can add

... PadID IN (SELECT PadID FROM Keywords WHERE word = '$search') ...

However its going to be a nightmare to split up the words from English45 and ProgramName into a word table.

Any ideas ?
EDIT : (also provided actual table names)


问:
WPF Add more interaction to listview items
I am binding my listview to a viewmodel using Caliburn. My view's code is the following:

```<code><ListView  x:Name="ListView" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding ProjectsPMod}" Margin="110,0,110,131" HorizontalContentAlignment="Stretch" BorderThickness="0" Height="111" VerticalAlignment="Bottom">
        <interactivity:Interaction.Triggers>
            <interactivity:EventTrigger EventName="SelectionChanged">
                <cal:ActionMessage MethodName="OpenProjectShell">
                    <cal:Parameter Value="{Binding ElementName=ListView, Path=SelectedItem}" />
                </cal:ActionMessage>
            </interactivity:EventTrigger>
        </interactivity:Interaction.Triggers>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />
                        <Label Content="{Binding Name}"/>
                    </StackPanel>

                    <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

Right now each item in every row just displays its name and a briefcase icon. If I wanted to add an "Edit"further down that row, where if you clicked on it something happened (perhaps a popup appears), how would I do it?

答:
You can make an ordinary Button look like a link using a template. Just add a Button to your StackPanel and bind it to a command:

```<code><ListView  x:Name="ListView" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding ProjectsPMod}" Margin="110,0,110,131" HorizontalContentAlignment="Stretch" BorderThickness="0" Height="111" VerticalAlignment="Bottom">
    <interactivity:Interaction.Triggers>
        <interactivity:EventTrigger EventName="SelectionChanged">
            <cal:ActionMessage MethodName="OpenProjectShell">
                <cal:Parameter Value="{Binding ElementName=ListView, Path=SelectedItem}" />
            </cal:ActionMessage>
        </interactivity:EventTrigger>
    </interactivity:Interaction.Triggers>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />
                    <Label Content="{Binding Name}"/>
                </StackPanel>

                <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>

                <Button Margin="0 10 0 0" Content="Link" Cursor="Hand" Command="{Binding YourCommand}">
                    <Button.Template>
                        <ControlTemplate TargetType="Button">
                            <TextBlock TextDecorations="Underline">
                                <ContentPresenter />
                            </TextBlock>
                        </ControlTemplate>
                    </Button.Template>
                    <Button.Style>
                        <Style TargetType="Button">
                            <Setter Property="Foreground" Value="Blue" />
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Foreground" Value="Red" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Button.Style>
                </Button>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

You can control the position of the Button within the StackPanel using its Margin property.

Body:
I am binding my listview to a viewmodel using Caliburn. My view's code is the following:

<ListView  x:Name="ListView" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding ProjectsPMod}" Margin="110,0,110,131" HorizontalContentAlignment="Stretch" BorderThickness="0" Height="111" VerticalAlignment="Bottom">
        <interactivity:Interaction.Triggers>
            <interactivity:EventTrigger EventName="SelectionChanged">
                <cal:ActionMessage MethodName="OpenProjectShell">
                    <cal:Parameter Value="{Binding ElementName=ListView, Path=SelectedItem}" />
                </cal:ActionMessage>
            </interactivity:EventTrigger>
        </interactivity:Interaction.Triggers>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />

                    </StackPanel>

                    <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Right now each item in every row just displays its name and a briefcase icon. If I wanted to add an "Edit"further down that row, where if you clicked on it something happened (perhaps a popup appears), how would I do it?

Body:
You can make an ordinary Button look like a link using a template. Just add a Button to your StackPanel and bind it to a command:

<ListView  x:Name="ListView" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding ProjectsPMod}" Margin="110,0,110,131" HorizontalContentAlignment="Stretch" BorderThickness="0" Height="111" VerticalAlignment="Bottom">
    <interactivity:Interaction.Triggers>
        <interactivity:EventTrigger EventName="SelectionChanged">
            <cal:ActionMessage MethodName="OpenProjectShell">
                <cal:Parameter Value="{Binding ElementName=ListView, Path=SelectedItem}" />
            </cal:ActionMessage>
        </interactivity:EventTrigger>
    </interactivity:Interaction.Triggers>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />
                    <Label Content="{Binding Name}"/>
                </StackPanel>

                <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>

                <Button Margin="0 10 0 0" Content="Link" Cursor="Hand" Command="{Binding YourCommand}">
                    <Button.Template>
                        <ControlTemplate TargetType="Button">
                            <TextBlock TextDecorations="Underline">
                                <ContentPresenter />
                            </TextBlock>
                        </ControlTemplate>
                    </Button.Template>
                    <Button.Style>
                        <Style TargetType="Button">
                            <Setter Property="Foreground" Value="Blue" />
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Foreground" Value="Red" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Button.Style>
                </Button>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

You can control the position of the Button within the StackPanel using its Margin property.


问:
Hiding all elements that doesn't have a particular class nested deep in them
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

```<code>let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}
</code>```

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

答:
With jQuery

You don't need an explicit loop if you use jQuery's :has() selector.

```<code>$(".card:has('.pro-content')").hide();
</code>```

This will select all .card elements have have a descendant with the pro-content class.

Without jQuery

To do this without a library dependency, use querySelector/All.

```<code>for (const card of document.querySelectorAll(".card")) {
  if (!card.querySelector(".pro-content")) {
    card.style.display = "none";
  }
}
</code>```

Or you can use the native .closest() method like this if you prefer:

```<code>for (const pro of document.querySelectorAll(".pro-content")) {
  const card = pro.closest(".card");
  if (card) {
    card.style.display = "none";
  }
}
</code>```

Though you'll need to patch .closest() into some browsers that don't have it yet.

Body:
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

Body:
With jQuery

You don't need an explicit loop if you use jQuery's :has() selector.

$(".card:has('.pro-content')").hide();

This will select all .card elements have have a descendant with the pro-content class.

Without jQuery

To do this without a library dependency, use querySelector/All.

for (const card of document.querySelectorAll(".card")) {
  if (!card.querySelector(".pro-content")) {
    card.style.display = "none";
  }
}

Or you can use the native .closest() method like this if you prefer:

for (const pro of document.querySelectorAll(".pro-content")) {
  const card = pro.closest(".card");
  if (card) {
    card.style.display = "none";
  }
}

Though you'll need to patch .closest() into some browsers that don't have it yet.


问:
Using Jdbc Template with DataSourceUtils.getConnection method
I am not sure below is the correct way to manage a db connectivity in a connection pooled environment using Jdbc template with DataSourceUtils.getConnection.

What I have done:

We are using apache dbcp for connection pooling.In Spring appconfig configured connection pooling and Jdbc template as shown below

<bean id="dbName"
    class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${oracle.driver}" />
    <property name="url" value="${xxxx.oracle.url}" />
    <property name="username" value="${xxxx.oracle.username}" />
    <property name="password" value="${xxxx.oracle.password}" />
    <property name="minIdle" value="1" />
</bean>
<bean id="jdbcTemplateUib"
class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dbName" />
</bean>

In DAOImpl, inside the method we have to invoke a stored procedure with custom SQL data types. Hence we are required to get connection object for the same. We are getting the connection as follows :

this.connection =
DataSourceUtils.getConnection(jdbcTemplate.getDataSource());

where DataSourceUtils is a Spring implementation described here.

The above configuration is working fine in local but we are bit worried on the following aspects of this program:

If we access connection in this manner will it override the connection pooling mechanism in appconfig file?

As per documnetation here, DataSourceUtils.getConnection(DataSource dataSource) will reuse existing connection. So I am assuming this will not break any connection created via JdbcTemplate and dbcp objects.

No need of explicitly releasing this connection since it is managed by the jdbcTemplate.

I am not quite sure on the above mentioned items. Need some expert opinion.

答:
Spring JDBC offers various utilities for calling stored procedures with custom SQL data types:

JdbcOperations#call

SimpleJdbcCall

GenericStoredProcedure

subclassing StoredProcedure


问:
How to delete cookies on an ASP.NET website
In my website when the user clicks on the "Logout" button, the Logout.aspx page loads with code Session.Clear().

In ASP.NET/C#, does this clear all cookies? Or is there any other code that needs to be added to remove all of the cookies of my website?

答:
Though this is an old thread, i thought if someone is still searching for solution in the future. </p>

```<code>HttpCookie mycookie = new HttpCookie("aa");
mycookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(mycookie1);
</code>```

<p>Thats what did the trick for me. </p>

Body:
Though this is an old thread, i thought if someone is still searching for solution in the future.

HttpCookie mycookie = new HttpCookie("aa");
mycookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(mycookie1);

Thats what did the trick for me.


问:
Is it good to serve static files under Rails' public folder?
I have a front-end single page app written in AngularJS, and I want to use Rails to build a back-end API.

I wonder if it is OK to put all front-end files in Rails' public folder, and mount all Rails' API routes on api/xxxx. In this way, I can save developers' efforts so they don't need to run two server when developing (front-end server and back-end rails' server). Also, I don't need to care about Rails' assets pipeline. I can use totally pure front-end solution to optimize fron-tend application. All I need to do is just put them into one single applications.

Is there any drawback of such design?

答: Yes, that perfectly fine.  In fact, this is what rake assets:precompile does.


问:
Building OpenWrt with ImageBuilder offline
I'm having a Carambola2 developer Board and building a firmware with the ImageBuilder from OpenWrt. This works great. But I would like to build the firmware when I'm offline. Because by default it tries to download data from 8devices.com. When I'm offline it compiles well but it's slow because it tries to access the internet. Any sugestions?</p>

答:
The only solution I have found is the following:

Step 1: Remove the rm-command for DL_DIR in the clean target of the Makefile.

Step 2: Add pkg.8devices.com to hosts.deny file.

So you will need an internet connection only the first time and every time you want to add a new package.

I think it's not a clean solution, but it works for me.


问:
Round-off numbers in symbolic expression
I have a 1*1 vector created with a symbol in Matlab. Because of the symbol (t) all values are converted to integers such as

```<code>(142731759660517923771*exp(t))/2814749767106560000 -
    (2384496775230702879947559372750244401*exp(2*t)) / 30948500982134506872478105600000000
</code>```

But I want this expression as 50.7085*exp(t)- 77.0472*exp(2*t).

Body:
I have a 1*1 vector created with a symbol in Matlab. Because of the symbol (t) all values are converted to integers such as

(142731759660517923771*exp(t))/2814749767106560000 -
    (2384496775230702879947559372750244401*exp(2*t)) / 30948500982134506872478105600000000

But I want this expression as 50.7085*exp(t)- 77.0472*exp(2*t).

Body:
You can use vpa as like this:

 expression = (142731759660517923771*exp(t))/2814749767106560000 -
  (2384496775230702879947559372750244401*exp(2*t))
      /30948500982134506872478105600000000;
 vpa(expression, 4);

See details of usage from the documentation.


问:
xml xpath read big file, from one part to other
I have very long xml file, like this:

```<code><cars>
    <car>
        <name>Ford</name>
        <number>F33</number>
        <color>Blue</color>
    </car>
    <car>
        <name>Ford</name>
        <number>F43</number>
        <color>Red</color>
    </car>
    <car>
        <name>Ford</name>
        <number>F53</number>
        <color>Red</color>
    </car>
    <car>
        <name>Audi</name>
        <number>A001</number>
        <color>Red</color>
    </car>
    <car>
        <name>Audi</name>
        <number>A032</number>
        <color>White</color>
    </car>
       .......
</cars>
</code>```

How with php xpath read from one part to ather.

For example like sql LIMIT 10, 30
show elemens from 10 to 30

答:
How with php xpath read from one part
  to ather.

For example like sql LIMIT 10, 30 show
  elemens from 10 to 30

Use:

```<code>/*/car[position() > 9 and not(position() > 30)]
</code>```

Body:
I have very long xml file, like this:

<cars>
    <car>
        <name>Ford</name>
        <number>F33</number>
        <color>Blue</color>
    </car>
    <car>
        <name>Ford</name>
        <number>F43</number>
        <color>Red</color>
    </car>
    <car>
        <name>Ford</name>
        <number>F53</number>
        <color>Red</color>
    </car>
    <car>
        <name>Audi</name>
        <number>A001</number>
        <color>Red</color>
    </car>
    <car>
        <name>Audi</name>
        <number>A032</number>
        <color>White</color>
    </car>
       .......
</cars>

How with php xpath read from one part to ather.

For example like sql LIMIT 10, 30
show elemens from 10 to 30

Body:
How with php xpath read from one part
  to ather.

For example like sql LIMIT 10, 30 show
  elemens from 10 to 30

Use:

/*/car[position() > 9 and not(position() > 30)]


问:
Bootstrap clear space
I want clear space form my HTML code.

```<code><div class="row">
    <div class="col-xs-1">
        <img src="~/Content/assets/images/male.jpg" style="height:35px;" class="img-responsive" alt="Cinque Terre">
    </div>
    <div class="col-md-10">
        <p class="pull-left text-primary text-capitalize text-weight-bold">Deneme</p>
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
    </div>
</div>
</code>```

答:
I don't think it is possible because the space between the user image and the username is default by the bootstrap grid system.

By the way, you have a col-xs-1 and a col-md-10 in one row, I don't know for sure if that is 100% right...

Title: Bootstrap clear space

Body:
I want clear space form my HTML code.

Deneme

        "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."


问:
Previous data is lost because of new data
I am creating some html tag and assigning data as below.

```<code>MyCombo = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "MyList()" onkeyup="MyList()" style="width:100% " >' +
        '<ul id="myUL" hidden=false>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }

    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '<li><a href="#">' + jsonc[i]['VALUE'] + '</a></li>';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
}
</code>```

Now when I pass my second div, previous data is getting lost. And for first div I am getting second data.

This how I am calling the class :

For the first instance

```<code>var myCombo = new liveSearch({
    "url": "data1.json",
    "divID": "ID1",
});
</code>```

For the second instance

```<code>var myCombo2 = new liveSearch({
    "url": "data2.json",
    "divID": "ID2",
});
</code>```

Any idea how to overcome this?

答:
Append instead of replacing

```<code>document.getElementById('myUL').appendChild(new_opt);
</code>```

or you can append to the old

```<code>old_html = document.getElementById('myUL').innerHTML;
document.getElementById('myUL').innerHTML = old_html+new_opt;
</code>```

Body:
I am creating some html tag and assigning data as below.

MyCombo = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "MyList()" onkeyup="MyList()" style="width:100% " >' +
        '
' + '
' + '' + '
' + '
';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }

    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '
' + jsonc[i]['VALUE'] + '
';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
}

Now when I pass my second div, previous data is getting lost. And for first div I am getting second data.

This how I am calling the class :

For the first instance

var myCombo = new liveSearch({
    "url": "data1.json",
    "divID": "ID1",
});

For the second instance

var myCombo2 = new liveSearch({
    "url": "data2.json",
    "divID": "ID2",
});

Any idea how to overcome this?

Body:
Append instead of replacing

document.getElementById('myUL').appendChild(new_opt);

or you can append to the old

old_html = document.getElementById('myUL').innerHTML;
document.getElementById('myUL').innerHTML = old_html+new_opt;


问:
Magick++ Issue when converting to Mat Opencv
Good day everyone,

I have this problem which I need to convert the Magick++ Image to OpenCV Mat. Though I successfully converted it however the problem occurs which the color of the Mat is not correct (Please see attached Image). In my case, I have a PDF file which I converted it to Magick++ Image page by page and to use my Image Processing methods, I need to convert it to OpenCV Mat. When I use other PDF file, the colors are correct. I really appreciate any help in this issue, Thanks.
My working code is displayed below, thanks.
Note: I use ImageMagick-7.0.6-Q16 and OpenCV 2.4.11

```<code>try {
    string fName = "";
    vector<Magick::Image> imageList;
    cout << "Please Input the File name of the PDF." << endl;
    cin >> fName;
    cout << "Please wait while converting the PDF to Images...." << endl;
    readImages(&imageList, fName);
    bool isDecoded = false;
    for (int i = 0; i < imageList.size(); i++){
        if (!isDecoded){

            int w = imageList[i].columns();
            int h = imageList[i].rows();

            Mat opencvImage(h,w,CV_8UC4);

            imageList[i].write(0, 0, w, h, "RGBA" , Magick::CharPixel, opencvImage.data);

            string decoded = QRScanner(opencvImage);
            imshow("opencvImage", opencvImage);
            if (decoded != ""){
                cout << "Result: " << decoded << endl;
                isDecoded = true;
            }

            waitKey();
        }
    }
}
catch (Magick::Exception &error_)
{
    cout << "Caught exception: " << error_.what() << endl;
}
cout << "Convert Complete!" << endl;
system("pause");
</code>```

Sample Code
Image Problem

答:
I think the majority of the problem has been addressed in the comments above, but I believe this can be quickly fixed by adjusting the channel map to what OpenCV is expecting.

imageList[i].write(0, 0, w, h, "BGRA" , Magick::CharPixel, opencvImage.data);
                                ^^^^
```

No need to worry about cvtColor or negation as you already can control how the data stream is exported.

Body:
Good day everyone,

I have this problem which I need to convert the Magick++ Image to OpenCV Mat. Though I successfully converted it however the problem occurs which the color of the Mat is not correct (Please see attached Image). In my case, I have a PDF file which I converted it to Magick++ Image page by page and to use my Image Processing methods, I need to convert it to OpenCV Mat. When I use other PDF file, the colors are correct. I really appreciate any help in this issue, Thanks.
My working code is displayed below, thanks.
Note: I use ImageMagick-7.0.6-Q16 and OpenCV 2.4.11

try {
    string fName = "";
    vector<Magick::Image> imageList;
    cout << "Please Input the File name of the PDF." << endl;
    cin >> fName;
    cout << "Please wait while converting the PDF to Images...." << endl;
    readImages(&imageList, fName);
    bool isDecoded = false;
    for (int i = 0; i < imageList.size(); i++){
        if (!isDecoded){

            int w = imageList[i].columns();
            int h = imageList[i].rows();

            Mat opencvImage(h,w,CV_8UC4);

            imageList[i].write(0, 0, w, h, "RGBA" , Magick::CharPixel, opencvImage.data);

            string decoded = QRScanner(opencvImage);
            imshow("opencvImage", opencvImage);
            if (decoded != ""){
                cout << "Result: " << decoded << endl;
                isDecoded = true;
            }

            waitKey();
        }
    }
}
catch (Magick::Exception &error_)
{
    cout << "Caught exception: " << error_.what() << endl;
}
cout << "Convert Complete!" << endl;
system("pause");

Sample Code
Image Problem

Body:
I think the majority of the problem has been addressed in the comments above, but I believe this can be quickly fixed by adjusting the channel map to what OpenCV is expecting.

imageList[i].write(0, 0, w, h, "BGRA" , Magick::CharPixel, opencvImage.data);
                                ^^^^

No need to worry about cvtColor or negation as you already can control how the data stream is exported.