问:
2 questions, Python OverflowError: (34, 'Result too large') and wrong function results
1st of all, I'm trying to understand why I'm getting an overflow error.  the first function "fibGen" works fine unless I give it an insanely large nth Fibonacci term.

```<code>    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))
</code>```

The second function "elemFib" will give me the correct answer but then errors out if number is over 1500.

```<code>    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))
</code>```

lastly, the function "pythonic" works like the "elemFib" function and does not give me an error code for even a very large number, why is that?  Also, I'm trying to get it to print the Fibonacci numbers like the first function "fibGen" but can't get it to work like that.

```<code>    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b
</code>```

My complete code for your review:

```<code>    import math
    import time

    #create the golden Ratio formula
    golden_ratio = (1 + math.sqrt(5)) / 2

    #the timer function
    def clockTime(start_time):
        print('\nRun Time:', time.time() - start_time)

    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))

    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))

    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b

    #display the Main Menu
    def dispMenu():
        print('---------------------Fibonacci Series ------------------\n')
        print('(A) Print Fibonacci numbers to the nth term')
        print('(B) Print Fibonacci numbers until element is less than Max number')
        print('(C) pythonic print')
        print('(Q) Quit the program\n')

    def  main():
              # set boolean control variable for loop
              loop = True

              #Create while loop for menu
              while loop:

                  #Display the menu
                  dispMenu()

                  #Get user's input
                  #choice = (input('Please make a selection: '))

                  #Get user's input
                  choice = input('Please make a selection: ').upper()

                  #Perform the selected action
                  if choice == 'A':
                      num = int(input("How many Fibonacci numbers should I print? "))
                      start_time = time.time()
                      fibGen(num)
                      clockTime(start_time)
                  elif choice == 'B':
                      num = int(input("the element should be less than? "))
                      start_time = time.time()
                      elemFib(num)
                      clockTime(start_time)
                  elif choice == 'C':
                      num = int(input('Pythonic Fibonacci series to the nth term? '))
                      start_time = time.time()
                      pythonic(num)
                      clockTime(start_time)
                  elif choice == 'Q':
                      print('\nExiting program, Thank you and Goodbye')
                      loop = False
                  else:
                      print('\nInvalid selection, try again\n')

    main()
</code>```

答:
Your functions crash once any value becomes too large. This is because internally, Python backs numbers with doubles.

Here is your elemFib function rewritten to use Decimals:

```<code>from decimal import Decimal

def elemFib(num):
        for number in range(0,num+1):
            val = golden_ratio ** Decimal(number) - (Decimal(1) - golden_ratio) ** Decimal(number) / Decimal(math.sqrt(5))
            if val < num:
                print('Fib({}): {}'.format(number, round(val)))
</code>```

This won't crash like the original. All I did was replace all numbers with Decimal objects. They're slower but can grow arbitrarily.

The reason your pythonic function doesn't crash the same way is simply because it doesn't create crazy big numbers, while the other two work by raising the golden ratio to some exponent, which requires much larger numbers.

Body:
1st of all, I'm trying to understand why I'm getting an overflow error.  the first function "fibGen" works fine unless I give it an insanely large nth Fibonacci term.

    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))

The second function "elemFib" will give me the correct answer but then errors out if number is over 1500.

    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))

lastly, the function "pythonic" works like the "elemFib" function and does not give me an error code for even a very large number, why is that?  Also, I'm trying to get it to print the Fibonacci numbers like the first function "fibGen" but can't get it to work like that.

    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b

My complete code for your review:

    import math
    import time

    #create the golden Ratio formula
    golden_ratio = (1 + math.sqrt(5)) / 2

    #the timer function
    def clockTime(start_time):
        print('\nRun Time:', time.time() - start_time)

    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))

    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))

    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b

    #display the Main Menu
    def dispMenu():
        print('---------------------Fibonacci Series ------------------\n')
        print('(A) Print Fibonacci numbers to the nth term')
        print('(B) Print Fibonacci numbers until element is less than Max number')
        print('(C) pythonic print')
        print('(Q) Quit the program\n')

    def  main():
              # set boolean control variable for loop
              loop = True

              #Create while loop for menu
              while loop:

                  #Display the menu
                  dispMenu()

                  #Get user's input
                  #choice = (input('Please make a selection: '))

                  #Get user's input
                  choice = input('Please make a selection: ').upper()

                  #Perform the selected action
                  if choice == 'A':
                      num = int(input("How many Fibonacci numbers should I print? "))
                      start_time = time.time()
                      fibGen(num)
                      clockTime(start_time)
                  elif choice == 'B':
                      num = int(input("the element should be less than? "))
                      start_time = time.time()
                      elemFib(num)
                      clockTime(start_time)
                  elif choice == 'C':
                      num = int(input('Pythonic Fibonacci series to the nth term? '))
                      start_time = time.time()
                      pythonic(num)
                      clockTime(start_time)
                  elif choice == 'Q':
                      print('\nExiting program, Thank you and Goodbye')
                      loop = False
                  else:
                      print('\nInvalid selection, try again\n')

    main()

Body:
Your functions crash once any value becomes too large. This is because internally, Python backs numbers with doubles.

Here is your elemFib function rewritten to use Decimals:

from decimal import Decimal

def elemFib(num):
        for number in range(0,num+1):
            val = golden_ratio ** Decimal(number) - (Decimal(1) - golden_ratio) ** Decimal(number) / Decimal(math.sqrt(5))
            if val < num:
                print('Fib({}): {}'.format(number, round(val)))

This won't crash like the original. All I did was replace all numbers with Decimal objects. They're slower but can grow arbitrarily.

The reason your pythonic function doesn't crash the same way is simply because it doesn't create crazy big numbers, while the other two work by raising the golden ratio to some exponent, which requires much larger numbers.


来源: stackexchange

问:
Pass navigation.navigate to Child Component
Building an app using react-navigation. I have a parent component that pulls from firebase and renders data in a listview. The listview render component 'ListName' has an onRowPress function but this.props.navigation.navigate comes up undefined because navigation is not in that child component's state.

Ive tried multiple ways of passing in navigation prop to the child and also importing navigation from react-navigation within the child.  Nothing works.

Thanks!

Here is my rootStackNavigator:

```<code>const RootStackNavigator = StackNavigator(
  {
    Login: { screen: LoginScreen },
    Main: { screen: MainTabNavigator },
    Feedback: { screen: ProvideInstanceScreen }
  },
  {
    navigationOptions: () => ({
      //headerTitleStyle: {
        //fontWeight: 'normal',
        tabBarVisible: false,
        header: null
      //},
    }),
  }
);
</code>```

Here is my Parent Component (which has navigation.navigate in its state)

```<code>import React from 'react';
import { ListView, StyleSheet, Text, Image } from 'react-native';
import { connect } from 'react-redux';
import _ from 'lodash';
import { MainButton, GenSection } from '../components/common';
import { namesFetch } from '../actions';
import ListName from '../components/ListName.js';

class ProvideScreen extends React.Component {

  static navigationOptions = {
    header: null,
  };

  componentWillMount() {
  //console.log('HOME HOME HOME  PRINT', this.props)
    this.props.namesFetch();

    this.createDataSource(this.props);
  }

  componentDidMount() {
    console.log('PROVIDE PROPS   PRINT', this.props)
    this.createDataSource(this.props);
  }

  componentWillReceiveProps(nextProps) {
    //nextProps are next set of props component is rendered with and this.props is still old props
    console.log('NEXT PROPS', nextProps)
    this.createDataSource(nextProps);
  }

  createDataSource({ names }) {
    var namesArray = names.map(function(a) {return [a.name, a.uid];});
    //console.log('NAMES ARRAY PRINT', namesArray)
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.dataSource = ds.cloneWithRows(namesArray);
  }

  renderRow(user) {
    return <ListName name={user[0]} />;
  }

  render() {
    return (
      <Image
        source={require('../components/images/mainBG.png')}
        style={styles.containerStyle}>
        <Text style={styles.textStyle}>
          Provide Feedback
        </Text>
        <GenSection style={{paddingTop: 8}} />
        <ListView
          enableEmptySections
          dataSource={this.dataSource}
          renderRow={this.renderRow}
          removeClippedSubviews={false}
        />

    </Image>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 15,
    backgroundColor: '#fff',
  },
  containerStyle: {
    flex: 1,
    width: undefined,
    height: undefined,
    backgroundColor:'transparent'
  },
  textStyle:
  {
    paddingTop: 20,
    paddingLeft: 12,
    fontSize: 32,
    fontWeight: '200',
    color: '#597abc'
  }
});

const mapStateToProps = state => {
  //console.log('STATE PRINT', state.feedbackInput)
  const names = _.map(state.feedbackInput, (val) => {
    return { ...val};
  });
  //console.log('NAMES PRINT', names)
  return { names };
};  //this is lodash   .map iterates over key value pairs and run function which assigns data to groups array

export default connect(mapStateToProps, { namesFetch })(ProvideScreen);
</code>```

Here is my child component (which does not have navigation.navigate in state):

```<code>import React, { Component } from 'react';
import { Text, TouchableWithoutFeedback, View } from 'react-native';
import { connect } from 'react-redux';
import { ListButton } from './common';

class ListName extends Component {
  onRowPress() {
    console.log('ON ROW PRESS  PRINT', this.props)
    this.props.navigation.navigate('Feedback', this.props);
  }

  componentDidMount() {
    //console.log('LIST NAME LIST NAME  PRINT', this.props)
  }

  render() {
    const name = this.props.name;
    //console.log('LISTNAME PRINT', name)

    return (
      <TouchableWithoutFeedback onPress={this.onRowPress.bind(this)}>
        <View>
          <ListButton>
            <Text style={styles.titleStyle}>
              {name}
            </Text>
          </ListButton>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

const styles = {
  titleStyle: {
    alignSelf: 'center',
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  }
};

const mapStateToProps = state => {
  //console.log('NAMES PRINT', names)
  return state
};  //this is lodash   .map iterates over key value pairs and run function which assigns data to groups array

export default connect(mapStateToProps)(ListName);
</code>```

答:
i just add this prop from parent and it worked:</p>

```<code><AppFooter navigation={this.props.navigation}  />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Building an app using react-navigation. I have a parent component that pulls from firebase and renders data in a listview. The listview render component 'ListName' has an onRowPress function but this.props.navigation.navigate comes up undefined because navigation is not in that child component's state.

Ive tried multiple ways of passing in navigation prop to the child and also importing navigation from react-navigation within the child.  Nothing works.

Thanks!

Here is my rootStackNavigator:

const RootStackNavigator = StackNavigator(
  {
    Login: { screen: LoginScreen },
    Main: { screen: MainTabNavigator },
    Feedback: { screen: ProvideInstanceScreen }
  },
  {
    navigationOptions: () => ({
      //headerTitleStyle: {
        //fontWeight: 'normal',
        tabBarVisible: false,
        header: null
      //},
    }),
  }
);

Here is my Parent Component (which has navigation.navigate in its state)

import React from 'react';
import { ListView, StyleSheet, Text, Image } from 'react-native';
import { connect } from 'react-redux';
import _ from 'lodash';
import { MainButton, GenSection } from '../components/common';
import { namesFetch } from '../actions';
import ListName from '../components/ListName.js';

class ProvideScreen extends React.Component {

  static navigationOptions = {
    header: null,
  };

  componentWillMount() {
  //console.log('HOME HOME HOME  PRINT', this.props)
    this.props.namesFetch();

    this.createDataSource(this.props);
  }

  componentDidMount() {
    console.log('PROVIDE PROPS   PRINT', this.props)
    this.createDataSource(this.props);
  }

  componentWillReceiveProps(nextProps) {
    //nextProps are next set of props component is rendered with and this.props is still old props
    console.log('NEXT PROPS', nextProps)
    this.createDataSource(nextProps);
  }

  createDataSource({ names }) {
    var namesArray = names.map(function(a) {return [a.name, a.uid];});
    //console.log('NAMES ARRAY PRINT', namesArray)
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.dataSource = ds.cloneWithRows(namesArray);
  }

  renderRow(user) {
    return <ListName name={user[0]} />;
  }

  render() {
    return (
      <Image
        source={require('../components/images/mainBG.png')}
        style={styles.containerStyle}>
        <Text style={styles.textStyle}>
          Provide Feedback
        </Text>
        <GenSection style={{paddingTop: 8}} />
        <ListView
          enableEmptySections
          dataSource={this.dataSource}
          renderRow={this.renderRow}
          removeClippedSubviews={false}
        />

    </Image>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 15,
    backgroundColor: '#fff',
  },
  containerStyle: {
    flex: 1,
    width: undefined,
    height: undefined,
    backgroundColor:'transparent'
  },
  textStyle:
  {
    paddingTop: 20,
    paddingLeft: 12,
    fontSize: 32,
    fontWeight: '200',
    color: '#597abc'
  }
});

const mapStateToProps = state => {
  //console.log('STATE PRINT', state.feedbackInput)
  const names = _.map(state.feedbackInput, (val) => {
    return { ...val};
  });
  //console.log('NAMES PRINT', names)
  return { names };
};  //this is lodash   .map iterates over key value pairs and run function which assigns data to groups array

export default connect(mapStateToProps, { namesFetch })(ProvideScreen);

Here is my child component (which does not have navigation.navigate in state):

import React, { Component } from 'react';
import { Text, TouchableWithoutFeedback, View } from 'react-native';
import { connect } from 'react-redux';
import { ListButton } from './common';

class ListName extends Component {
  onRowPress() {
    console.log('ON ROW PRESS  PRINT', this.props)
    this.props.navigation.navigate('Feedback', this.props);
  }

  componentDidMount() {
    //console.log('LIST NAME LIST NAME  PRINT', this.props)
  }

  render() {
    const name = this.props.name;
    //console.log('LISTNAME PRINT', name)

    return (
      <TouchableWithoutFeedback onPress={this.onRowPress.bind(this)}>
        <View>
          <ListButton>
            <Text style={styles.titleStyle}>
              {name}
            </Text>
          </ListButton>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

const styles = {
  titleStyle: {
    alignSelf: 'center',
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  }
};

const mapStateToProps = state => {
  //console.log('NAMES PRINT', names)
  return state
};  //this is lodash   .map iterates over key value pairs and run function which assigns data to groups array

export default connect(mapStateToProps)(ListName);

Body:
i just add this prop from parent and it worked:

<AppFooter navigation={this.props.navigation}  />

ContentLicense: CC BY-SA 4.0


问:
DB2 NOT ATOMIC WAS Expected , how can we fix this?
I m not sure , why I am getting the below error, while executing the below SQL in my SQL Editor for DB2 (DB2 for z/OS)

```<code>DECLARE GLOBAL TEMPORARY TABLE SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID INTEGER NOT NULL,
  PROC_SYS_CD VARCHAR(10) NOT NULL,
  VER_KEY_SET_CD VARCHAR(10) NOT NULL,
  TRNSLT_TP_CD VARCHAR(10) NOT NULL,
  SET_INDEX_NUM VARCHAR(10) NOT NULL,
  SET_MDK_DKI_NUM VARCHAR(10) NOT NULL,
  PACKET_NUM INTEGER NOT NULL ) ON COMMIT PRESERVE ROWS;

INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM
)
VALUES (500159, 'DB', 'MDK', '0', '1', '001', 766473)
UNION ALL
(500151, 'DB', 'MDK', '0', '2', '002', 766473);

select * from SESSION.VTI_GUI_TMP;

DROP TABLE SESSION.VTI_GUI_TMP;
</code>```

I am getting the below error , while executing the above the SQL

ILLEGAL USE OF KEYWORD UNION.  TOKEN FOR  NOT ATOMIC WAS EXPECTED. SQLCODE=-199, SQLSTATE=42601, DRIVER=3.63.75 SQL Code: -199, SQL State: 42601

Error occurred in:
       INSERT INTO SESSION.VTI_GUI_TMP (ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD, SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM) VALUES(500159, 'DB', 'MDK', '0', '1', '001', 766473) UNION ALL(500151, 'DB', 'MDK', '0', '2', '002', 766473)

How can we fix the above error ? I dont want to use the SELECT statement along with UNION ALL to fix. Is there any way to make this work.

I am using the below DB2 version

```<code>  SELECT GETVARIABLE('SYSIBM.VERSION') FROM SYSIBM.SYSDUMMY1
  -----------
  DSN11015
</code>```

What am I doing wrong?

答:
Can't you use two separate INSERT statements? For example:

```<code>DECLARE GLOBAL TEMPORARY TABLE SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID INTEGER NOT NULL,
  PROC_SYS_CD VARCHAR(10) NOT NULL,
  VER_KEY_SET_CD VARCHAR(10) NOT NULL,
  TRNSLT_TP_CD VARCHAR(10) NOT NULL,
  SET_INDEX_NUM VARCHAR(10) NOT NULL,
  SET_MDK_DKI_NUM VARCHAR(10) NOT NULL,
  PACKET_NUM INTEGER NOT NULL
) ON COMMIT PRESERVE ROWS;

INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM
) VALUES (500159, 'DB', 'MDK', '0', '1', '001', 766473)

INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM
) VALUES (500151, 'DB', 'MDK', '0', '2', '002', 766473);
</code>```

Or maybe:

```<code>INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM)
SELECT 500159, 'DB', 'MDK', '0', '1', '001', 766473 FROM sysibm.sysdummy1
UNION ALL
SELECT 500151, 'DB', 'MDK', '0', '2', '002', 766473 FROM sysibm.sysdummy1
</code>```

Body:
I m not sure , why I am getting the below error, while executing the below SQL in my SQL Editor for DB2 (DB2 for z/OS)

DECLARE GLOBAL TEMPORARY TABLE SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID INTEGER NOT NULL,
  PROC_SYS_CD VARCHAR(10) NOT NULL,
  VER_KEY_SET_CD VARCHAR(10) NOT NULL,
  TRNSLT_TP_CD VARCHAR(10) NOT NULL,
  SET_INDEX_NUM VARCHAR(10) NOT NULL,
  SET_MDK_DKI_NUM VARCHAR(10) NOT NULL,
  PACKET_NUM INTEGER NOT NULL ) ON COMMIT PRESERVE ROWS;

INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM
)
VALUES (500159, 'DB', 'MDK', '0', '1', '001', 766473)
UNION ALL
(500151, 'DB', 'MDK', '0', '2', '002', 766473);

select * from SESSION.VTI_GUI_TMP;

DROP TABLE SESSION.VTI_GUI_TMP;

I am getting the below error , while executing the above the SQL

ILLEGAL USE OF KEYWORD UNION.  TOKEN FOR  NOT ATOMIC WAS EXPECTED. SQLCODE=-199, SQLSTATE=42601, DRIVER=3.63.75 SQL Code: -199, SQL State: 42601

Error occurred in:
       INSERT INTO SESSION.VTI_GUI_TMP (ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD, SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM) VALUES(500159, 'DB', 'MDK', '0', '1', '001', 766473) UNION ALL(500151, 'DB', 'MDK', '0', '2', '002', 766473)

How can we fix the above error ? I dont want to use the SELECT statement along with UNION ALL to fix. Is there any way to make this work.

I am using the below DB2 version

  SELECT GETVARIABLE('SYSIBM.VERSION') FROM SYSIBM.SYSDUMMY1
  -----------
  DSN11015

What am I doing wrong?

Body:
Can't you use two separate INSERT statements? For example:

DECLARE GLOBAL TEMPORARY TABLE SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID INTEGER NOT NULL,
  PROC_SYS_CD VARCHAR(10) NOT NULL,
  VER_KEY_SET_CD VARCHAR(10) NOT NULL,
  TRNSLT_TP_CD VARCHAR(10) NOT NULL,
  SET_INDEX_NUM VARCHAR(10) NOT NULL,
  SET_MDK_DKI_NUM VARCHAR(10) NOT NULL,
  PACKET_NUM INTEGER NOT NULL
) ON COMMIT PRESERVE ROWS;

INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM
) VALUES (500159, 'DB', 'MDK', '0', '1', '001', 766473)

INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM
) VALUES (500151, 'DB', 'MDK', '0', '2', '002', 766473);

Or maybe:

INSERT INTO SESSION.VTI_GUI_TMP (
  ENCRP_PRC_RL_ID, PROC_SYS_CD, VER_KEY_SET_CD, TRNSLT_TP_CD,
  SET_INDEX_NUM, SET_MDK_DKI_NUM, PACKET_NUM)
SELECT 500159, 'DB', 'MDK', '0', '1', '001', 766473 FROM sysibm.sysdummy1
UNION ALL
SELECT 500151, 'DB', 'MDK', '0', '2', '002', 766473 FROM sysibm.sysdummy1


问:
how to send mail from .net?
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me</p>

```<code>SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }
</code>```

答:
Your "from" user must be in the form of a valid email address.

```<code>message.From = new MailAddress(smtpuser);
</code>```

Also, you will need to use the MailAddress constructor for the .To property as well.

Title: how to send mail from .net?

Body:
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me

SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }

Body:
Your "from" user must be in the form of a valid email address.

message.From = new MailAddress(smtpuser);

Also, you will need to use the MailAddress constructor for the .To property as well.


问:
How to call netlify function and pass variable within another js file?
I have an API that want to access whenever a user clicks on a certain state on the US Map. I’d like to get the state id (ex: CA) and send it to the netlify function.
The netlify function would then get everything I need from the API and return it to the client side js file I have.
Is this possible?</p>

答:
What stack are you using on front end, may be I can explain better in that case.?
For now my understanding is just call netlify API on onClick method and then pass the id as params. This is a generic way of using 3rd party API.

If you want to know more in details, provide more information. e.g API url you are trying to use.


问:
Convert xPath into CSS selector
Is there a way to convert these to a CSS selectors?

1) '//form//div[contains(@class,"myclass")]'

2) '//div[contains(@class,"myclass")]//input[@type="submit"]'

3) './/label[(substring(./@for, ((string-length(./@for) - string-length('_state')) + 1)) = '_state')]'

答:
Here are the css for the first 2.

'//form//div[contains(@class,"myclass")]'

form div[class*='myclass']

'//div[contains(@class,"myclass")]//input[@type="submit"]'

div[class*='myclass'] input[type='submit']

'.//label[(substring(./@for, ((string-length(./@for) - string-length('_state')) + 1)) = '_state')]'

label[for $='_state']

Title: Convert xPath into CSS selector


问:
How to select rows by range comparison in SQL Server?
I have following table named T in left as source table.

FINAL OUTPUT SHOULD BE AS FOLLOWING,

I want to take only those rows where Actual value is in between Basic, associated with the Model and Level columns.

For example if you take Model = HT65, the Actual value of 23.2 lies between Basic = 22 & 24, so that row should be selected where Basic = 24. i.e highlighted in yellow, same is true for JF97. Here you can refer right hand side table as reference result.

For the same model, if Actual is 21,  the first row should be chosen, with level = 1, like this:

If Actual column value is more than value in Basic Level should be marked as out highlighted in orange, as following,

I have not tried it as it seemed complex to me. your help would be appreciated.

答:
You could do this with a simple union.  While there are more complex ways to do this, this flow allows you to see the two separate comparisons easily and tweak as needed.

select model,level,actual from T

where actual between level and basic

union

select model,level,'out' from T

where actual > basic


问:
How to prevent while loop outputs from colliding with previous outputs?
After the first pass through the while loop, the output of the second pass appends to the last line of the first pass.

Here, I'm using a while loop with bash, I suspect that it's a \n problem.

There are two files, here's a bit of each:

```<code>input1
CGTGGGAA
TGTGGGAA
CGTGAGAA
</code>```

```<code>namePBM
AAAAAACAACAGGAGGGCATCATGGAGCTGTCCAGCCTGT    220.632711
AAAAAACAGCCGGATCACAATTTTGCCGAGAGCGACCTGT    221.514925
AAAAAACGTCCGGTACACCCCGTTCGGCGGCCCAGCCTGT    222.473157
AAAAAACTCTAGACCTTTAGCCCATCGTTGGCCAACCTGT    262.183554
</code>```

Here is the relevant snippet of code:

```<code>while IFS= read -r line
do
    OutputA1+=$(grep -o -P "$line" "$namePBM") #Shows Target Site
    OutputA2+=$(grep -o -P ".{0,2}$line" "$namePBM" | sed 's/........$//') #5' Flank
    OutputA3+=$(awk -v pat="$line" '$1~pat {print $2}' "$namePBM") #Intensity Values
done < "$input1"

OutputA4=$(paste <(echo "$OutputA1") <(echo "$OutputA2") <(echo "$OutputA3"))

echo "$OutputA4"
</code>```

The output looks like this:

```<code>CGTGGGAA        AT      500.306264
CGTGGGAA        GA      216.029774
CGTGGGAA        GT      226.937170
CGTGGGAA        CA      283.247237
CGTGGGAA        CC      383.089073
CGTGGGAA        TA      243.455285
CGTGGGAA        C       631.194970
CGTGGGAA        CT      318.330615
CGTGGGAA        AC      211.895150
CGTGGGAA                840.522056
CGTGGGAA        AG      194.045824
CGTGGGAA        AA      193.686006
CGTGGGAA        TC      282.153144
CGTGGGAA        GC      207.303981
CGTGGGAA        CG      225.282407
CGTGGGAA        TG      220.369882
CGTGGGAATGTGGGAA        TTTC    298.320734329.953276
TGTGGGAA        AG      203.847257
TGTGGGAA        GA      242.392699
TGTGGGAA        GT      211.894931
TGTGGGAA        AA      199.040909
TGTGGGAA        TT      228.433316
TGTGGGAA        TG      236.023833
TGTGGGAA        AT      320.913155
TGTGGGAA        CG      252.373388
TGTGGGAA        GC      257.858672
TGTGGGAA        TA      224.919676
TGTGGGAA        GG      176.379573
TGTGGGAA        CA      211.450761
TGTGGGAA        AC      315.362784
TGTGGGAA                666.500440
TGTGGGAACGTGAGAA        CCAG    187.171859233.376637
</code>```

The expected output should be TGTGGGAA and its associated data forms on the next line.

答:
OK easy answer right now is that you need to emit a newline at the end of each iteration of the loop.

By default I think the $() command capture discards the last newline, and that is what then causes the lines to overlap.

Adding && echo '' may be good enough:

```<code>while IFS= read -r line
do
  OutputA1+=$(grep -o -P "$line" "$namePBM" && echo '') #Shows Target Site
  OutputA2+=$(grep -o -P ".{0,2}$line" "$namePBM" | sed 's/........$//' && echo '') #5' Flank
  OutputA3+=$(awk -v pat="$line" '$1~pat {print $2}' "$namePBM" && echo '') #Intensity Values
done < "$input1"

OutputA4=$(paste <(echo "$OutputA1") <(echo "$OutputA2") <(echo "$OutputA3"))

echo "$OutputA4"
</code>```

In fact, no, $() discards all trailing lines (says @Gordon), so we are left with

```<code>while IFS= read -r line
do
  OutputA1+=$(grep -o -P "$line" "$namePBM") #Shows Target Site
  OutputA1+=$'\n'
  OutputA2+=$(grep -o -P ".{0,2}$line" "$namePBM" | sed 's/........$//') #5' Flank
  OutputA2+=$'\n'
  OutputA3+=$(awk -v pat="$line" '$1~pat {print $2}' "$namePBM") #Intensity Values
done < "$input1"
  OutputA3+=$'\n'

OutputA4=$(paste <(echo "$OutputA1") <(echo "$OutputA2") <(echo "$OutputA3"))

echo "$OutputA4"
</code>```

For debugging purposes it may be useful to also print the line number in namePBM where the match was found using the grep -n argument.

To do this in a single sed is backtick hell:

```<code>while IFS= read -r line
do
  sed -n 's/^\(\([^ ]\{0,2\}\)\|[^ ]*\([^ ]\{2,2\}\)\)\('"$line"'\)[^ ]*[ ]*\( [^ ]*\).*$/\4 \2\3 \5/p' $namePBM
done
</code>```

That is:

-n don't print non-matching lines

's substitute with everything escaped

/ capture pattern:

(\([^ ]\{0,2\}\)\|[^ ]*\([^ ]\{2,2\}\)\)   up to 2 characters in the first word, or any characters plus the 2 we want

\('"$line"'\)   Unescape and capture the phrase we want

[^ ]*   discard the rest of that word

[ ]*    discard any extra spaces until the next word

( [^ ]*) capture the space before and the second word completely

.*$      discard until the end of the line

/\4 \2\3 \5  replace with: the test phrase, up to 2 characters or exactly 2 characters before, the second word

/p'  print it (because of -n)

Oh, and you can use \S instead of [^ ] and \s instead of [ ]!

Another way would be to build up all the words we want into one variable and then sed just once, but this would unduplicate any lines that contain 2 or more of the patterns:

Building the string I leave as an exercise, but to show it works:

```<code>lines="CGTGGGAA""\|""TGTGGGAA""\|""CGTGAGAA"
sed -n 's/^\(\([^ ]\{0,2\}\)\|[^ ]*\([^ ]\{2,2\}\)\)\('"$lines"'\)[^ ]*[ ]*\( [^ ]*\).*$/\4 \2\3 \5/p' $namePBM
</code>```

Body:
After the first pass through the while loop, the output of the second pass appends to the last line of the first pass.

Here, I'm using a while loop with bash, I suspect that it's a \n problem.

There are two files, here's a bit of each:

input1
CGTGGGAA
TGTGGGAA
CGTGAGAA

namePBM
AAAAAACAACAGGAGGGCATCATGGAGCTGTCCAGCCTGT    220.632711
AAAAAACAGCCGGATCACAATTTTGCCGAGAGCGACCTGT    221.514925
AAAAAACGTCCGGTACACCCCGTTCGGCGGCCCAGCCTGT    222.473157
AAAAAACTCTAGACCTTTAGCCCATCGTTGGCCAACCTGT    262.183554

Here is the relevant snippet of code:

while IFS= read -r line
do
    OutputA1+=$(grep -o -P "$line" "$namePBM") #Shows Target Site
    OutputA2+=$(grep -o -P ".{0,2}$line" "$namePBM" | sed 's/........$//') #5' Flank
    OutputA3+=$(awk -v pat="$line" '$1~pat {print $2}' "$namePBM") #Intensity Values
done < "$input1"

OutputA4=$(paste <(echo "$OutputA1") <(echo "$OutputA2") <(echo "$OutputA3"))

echo "$OutputA4"

The output looks like this:

CGTGGGAA        AT      500.306264
CGTGGGAA        GA      216.029774
CGTGGGAA        GT      226.937170
CGTGGGAA        CA      283.247237
CGTGGGAA        CC      383.089073
CGTGGGAA        TA      243.455285
CGTGGGAA        C       631.194970
CGTGGGAA        CT      318.330615
CGTGGGAA        AC      211.895150
CGTGGGAA                840.522056
CGTGGGAA        AG      194.045824
CGTGGGAA        AA      193.686006
CGTGGGAA        TC      282.153144
CGTGGGAA        GC      207.303981
CGTGGGAA        CG      225.282407
CGTGGGAA        TG      220.369882
CGTGGGAATGTGGGAA        TTTC    298.320734329.953276
TGTGGGAA        AG      203.847257
TGTGGGAA        GA      242.392699
TGTGGGAA        GT      211.894931
TGTGGGAA        AA      199.040909
TGTGGGAA        TT      228.433316
TGTGGGAA        TG      236.023833
TGTGGGAA        AT      320.913155
TGTGGGAA        CG      252.373388
TGTGGGAA        GC      257.858672
TGTGGGAA        TA      224.919676
TGTGGGAA        GG      176.379573
TGTGGGAA        CA      211.450761
TGTGGGAA        AC      315.362784
TGTGGGAA                666.500440
TGTGGGAACGTGAGAA        CCAG    187.171859233.376637

The expected output should be TGTGGGAA and its associated data forms on the next line.

Body:
OK easy answer right now is that you need to emit a newline at the end of each iteration of the loop.

By default I think the $() command capture discards the last newline, and that is what then causes the lines to overlap.

Adding && echo '' may be good enough:

while IFS= read -r line
do
  OutputA1+=$(grep -o -P "$line" "$namePBM" && echo '') #Shows Target Site
  OutputA2+=$(grep -o -P ".{0,2}$line" "$namePBM" | sed 's/........$//' && echo '') #5' Flank
  OutputA3+=$(awk -v pat="$line" '$1~pat {print $2}' "$namePBM" && echo '') #Intensity Values
done < "$input1"

OutputA4=$(paste <(echo "$OutputA1") <(echo "$OutputA2") <(echo "$OutputA3"))

echo "$OutputA4"

In fact, no, $() discards all trailing lines (says @Gordon), so we are left with

while IFS= read -r line
do
  OutputA1+=$(grep -o -P "$line" "$namePBM") #Shows Target Site
  OutputA1+=$'\n'
  OutputA2+=$(grep -o -P ".{0,2}$line" "$namePBM" | sed 's/........$//') #5' Flank
  OutputA2+=$'\n'
  OutputA3+=$(awk -v pat="$line" '$1~pat {print $2}' "$namePBM") #Intensity Values
done < "$input1"
  OutputA3+=$'\n'

OutputA4=$(paste <(echo "$OutputA1") <(echo "$OutputA2") <(echo "$OutputA3"))

echo "$OutputA4"

For debugging purposes it may be useful to also print the line number in namePBM where the match was found using the grep -n argument.

To do this in a single sed is backtick hell:

while IFS= read -r line
do
  sed -n 's/^\(\([^ ]\{0,2\}\)\|[^ ]*\([^ ]\{2,2\}\)\)\('"$line"'\)[^ ]*[ ]*\( [^ ]*\).*$/\4 \2\3 \5/p' $namePBM
done

That is:

-n don't print non-matching lines

's substitute with everything escaped

/ capture pattern:

(\([^ ]\{0,2\}\)\|[^ ]*\([^ ]\{2,2\}\)\)   up to 2 characters in the first word, or any characters plus the 2 we want

\('"$line"'\)   Unescape and capture the phrase we want

[^ ]*   discard the rest of that word

[ ]*    discard any extra spaces until the next word

( [^ ]*) capture the space before and the second word completely

.*$      discard until the end of the line

/\4 \2\3 \5  replace with: the test phrase, up to 2 characters or exactly 2 characters before, the second word

/p'  print it (because of -n)

Oh, and you can use \S instead of [^ ] and \s instead of [ ]!

Another way would be to build up all the words we want into one variable and then sed just once, but this would unduplicate any lines that contain 2 or more of the patterns:

Building the string I leave as an exercise, but to show it works:

lines="CGTGGGAA""\|""TGTGGGAA""\|""CGTGAGAA"
sed -n 's/^\(\([^ ]\{0,2\}\)\|[^ ]*\([^ ]\{2,2\}\)\)\('"$lines"'\)[^ ]*[ ]*\( [^ ]*\).*$/\4 \2\3 \5/p' $namePBM


问:
Character Encoding UTF8 Issue when using mb_detect_encoding() with PHP
I am reading an rss feed http://beersandbeans.com/feed/

The feeds says it is UTF8 format, and I am using simplepie rss to import the content When i grab the content and store it in $content I perform the following:

```<code><?php
header ('Content-type: text/html; charset=utf-8');
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head><body>
<?php
echo $content;
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
echo $content = mb_convert_encoding($content, "UTF-8", $enc);
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
?>
</body></html>
</code>```

This then produces:

```<code>..... Camping:     2,000isk/day for 5 days) = $89 .....
ISO-8859-1
..... Camping: Â  Â           2,000isk/day for 5 days) = $89 .....
UTF-8
</code>```

Why is it outputting the Â ?

答:
Set strict-mode to true in mb_detect_encoding(), see http://www.php.net/manual/de/function.mb-detect-encoding.php#102510

Also try http://www.php.net/manual/de/function.mb-convert-encoding.php instead of iconv()

Body:
I am reading an rss feed http://beersandbeans.com/feed/

The feeds says it is UTF8 format, and I am using simplepie rss to import the content When i grab the content and store it in $content I perform the following:

<?php
header ('Content-type: text/html; charset=utf-8');
?>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<?php
echo $content;
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
echo $content = mb_convert_encoding($content, "UTF-8", $enc);
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
?>

This then produces:

..... Camping:     2,000isk/day for 5 days) = $89 .....
ISO-8859-1
..... Camping: Â  Â           2,000isk/day for 5 days) = $89 .....
UTF-8

Why is it outputting the Â ?


问:
displaying current date in a text box - javascript
I am having great difficulty getting the current date to be inputted into a text box within a form i am creating as a default value. at the moment i have the following code, which i believe creates the current date, followed by the text box code which i am unsure on how to modify in order for the date to be displayed inside.

```<code>function getDate(){
 var todaydate = new Date();
 var day = todaydate.getDate();
 var month = todaydate.getMonth() + 1;
 var year = todaydate.getFullYear();
 var datestring = day + "/" + month + "/" + year;
 document.getElementById("frmDate").value = datestring();
}
<input type="text" name="frmDateReg" required id="frmDate"  value="getDate()">
</code>```

if anyone could suggest how to create todays date and input it into the textbox as default it would be greatly appreciated. (Please excuse any format issues as i am new to stack overflow) Thanks

答:
```

Result in your text box is:

5/28/2019 Time: 3:03:01 pm

Body:
I am having great difficulty getting the current date to be inputted into a text box within a form i am creating as a default value. at the moment i have the following code, which i believe creates the current date, followed by the text box code which i am unsure on how to modify in order for the date to be displayed inside.

function getDate(){
 var todaydate = new Date();
 var day = todaydate.getDate();
 var month = todaydate.getMonth() + 1;
 var year = todaydate.getFullYear();
 var datestring = day + "/" + month + "/" + year;
 document.getElementById("frmDate").value = datestring();
}
<input type="text" name="frmDateReg" required id="frmDate"  value="getDate()">

if anyone could suggest how to create todays date and input it into the textbox as default it would be greatly appreciated. (Please excuse any format issues as i am new to stack overflow) Thanks

Body:
<script TYPE="text/javascript" LANGUAGE=JAVASCRIPT>
var currentDate = new Date();
var date1 = currentDate.getMonth()+1;
var mon = currentDate.getDate();
if (mon<10)
    mon="0"+mon
var year = currentDate.getYear();
var hour = currentDate.getHours();
var dn="pm"
if (hour<12)
    dn="am"
if (hour>12)
    hour=hour-12
if (hour==0)
    hour=12
var minute = currentDate.getMinutes();
if (minute < 10){
    minute = "0" + minute
}
var second = currentDate.getSeconds();
if (second < 10){
    second = "0" + second
}
var today = date1+"/"+mon+"/"+year+" Time: "+hour+":"+minute+":"+second+" "+dn
var filePath = "\\\\servername\\maindirectory\\somedirectory\\filenametopostto.xlsx";
function setDate()
{
    f1.tDate.value=today;
}
</script>

Result in your text box is:

5/28/2019 Time: 3:03:01 pm


问:
Button is glitching and I have to click twice to reveal information, and the photos are not aligning properly, why is this?
I am trying to create a button that hides information and reveals information. All of the content is in the  tag. There are two issues with this code.

```<code>1. You have to click the button twice to reveal information.
2. When information is revealed the pictures don't align like it should.. it gets moved to the middle then the right.
</code>```

How can I fix these issues..?

$(document).ready(function() {
     $("#toggle").click(function() {
    var elem = $("#toggle").text();
    if (elem == "More News >") {
      //Stuff to do when btn is in the read more state
      $("#toggle").text("Read Less");
      $("#text").slideDown();
     } else {
      //Stuff to do when btn is in the read less state
      $("#toggle").text("More News >");
      $("#text").slideUp();
     }
    });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#text{
       display:none;
        }

    .btn-container{
      margin: auto;
      height:44px;
      width:166.23px;

       }

        button{
        user-select:none;
       -webkit-user-select:none;
        -moz-user-select:none;
        -ms-user-select:none;
       cursor:pointer;
        border: solid 1px;
         padding:8px;
        font-size:1em;
       background: transparent;
       color:black;
        box-sizing:border-box;
     }</code>```

 All Stories

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

        <button id="toggle"> More News > </button>

```

Expected: Button should reveal information smoothly with one click, and images should align to the right.

Actual: There is a glitch and you have to click twice to reveal information, and images get aligned to the right after they go to the centre of the page first.

答:
The reason why your first click isn't registering is probably because the exact text in your html <button id="toggle"> More News > </button> is different then your jquery code $("#toggle").text("More News >"); Therefore the first time when you click, the else statement is triggered assigning "More News >" to the button, then it toggles there after.

To fix this, you might want to add an attribute to your toggler button

```<code><button id="toggle" toggle="expand">More News ></button>
</code>```

and then use the following:

```<code>if($("#toggle").attr("toggle") === "expand") {
  $("#text").css("display", "inline");
  $("#toggle").attr("toggle", "shrink");
}
</code>```

Body:
I am trying to create a button that hides information and reveals information. All of the content is in the  tag. There are two issues with this code.

1. You have to click the button twice to reveal information.
2. When information is revealed the pictures don't align like it should.. it gets moved to the middle then the right.

How can I fix these issues..?

$(document).ready(function() {
     $("#toggle").click(function() {
    var elem = $("#toggle").text();
    if (elem == "More News >") {
      //Stuff to do when btn is in the read more state
      $("#toggle").text("Read Less");
      $("#text").slideDown();
     } else {
      //Stuff to do when btn is in the read less state
      $("#toggle").text("More News >");
      $("#text").slideUp();
     }
    });
    });

#text{
       display:none;
        }

    .btn-container{
      margin: auto;
      height:44px;
      width:166.23px;

       }

        button{
        user-select:none;
       -webkit-user-select:none;
        -moz-user-select:none;
        -ms-user-select:none;
       cursor:pointer;
        border: solid 1px;
         padding:8px;
        font-size:1em;
       background: transparent;
       color:black;
        box-sizing:border-box;
     }

 All Stories

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

Jan, 01, 2019

           Title of the news article will be diplayed under the photo.

        <button id="toggle"> More News > </button>

Expected: Button should reveal information smoothly with one click, and images should align to the right.

Actual: There is a glitch and you have to click twice to reveal information, and images get aligned to the right after they go to the centre of the page first.

Body:
The reason why your first click isn't registering is probably because the exact text in your html <button id="toggle"> More News > </button> is different then your jquery code $("#toggle").text("More News >"); Therefore the first time when you click, the else statement is triggered assigning "More News >" to the button, then it toggles there after.

To fix this, you might want to add an attribute to your toggler button

<button id="toggle" toggle="expand">More News ></button>

and then use the following:

if($("#toggle").attr("toggle") === "expand") {
  $("#text").css("display", "inline");
  $("#toggle").attr("toggle", "shrink");
}


问:
Documents directory in objective C
In Xcode, the Resources folder links to the NSDocumentsFolder of the app? Or what else?

Is there a way to see the files in NSDocumentFolder without write code?

答: No the resource folder in Xcode does not link to the document directory, it is just imaginary folder for organization in xcode. However there you could see the content of your document directory by browsing to the folder in the simulator.</p>

Title: Documents directory in objective C


问:
removing string=number from a file
I'm trying to understand some printouts of the alsa mixer and to compare with other values. I have the printout of alsa mixer:

```<code>numid=1,iface=MIXER,name='codec_out1 mix 0 codec_in0 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=2,iface=MIXER,name='codec_out1 mix 0 codec_in1 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=3,iface=MIXER,name='codec_out1 mix 0 sprot_loop_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=4,iface=MIXER,name='codec_out1 mix 0 media_loop1_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=5,iface=MIXER,name='codec_out1 mix 0 media_loop2_in Switch'
</code>```

I want to remove the numid=X, i.e. I want the following output:

```<code>iface=MIXER,name='codec_out1 mix 0 codec_in0 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 codec_in1 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 sprot_loop_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 media_loop1_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 media_loop2_in Switch'
</code>```

答:
This sed should do:

```<code>sed 's/numid=[0-9][0-9]*,//g' file
</code>```

Removes numid=any number

Title: removing string=number from a file

Body:
I'm trying to understand some printouts of the alsa mixer and to compare with other values. I have the printout of alsa mixer:

numid=1,iface=MIXER,name='codec_out1 mix 0 codec_in0 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=2,iface=MIXER,name='codec_out1 mix 0 codec_in1 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=3,iface=MIXER,name='codec_out1 mix 0 sprot_loop_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=4,iface=MIXER,name='codec_out1 mix 0 media_loop1_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
numid=5,iface=MIXER,name='codec_out1 mix 0 media_loop2_in Switch'

I want to remove the numid=X, i.e. I want the following output:

iface=MIXER,name='codec_out1 mix 0 codec_in0 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 codec_in1 Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 sprot_loop_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 media_loop1_in Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=off
iface=MIXER,name='codec_out1 mix 0 media_loop2_in Switch'

Body:
This sed should do:

sed 's/numid=[0-9][0-9]*,//g' file

Removes numid=any number


问:
JavaScript variable before and after declaration?
```<code>function a(){
   console.log(typeof b); // function
   function b() {
     var c = 52;
     console.log(c);
   }
   var b = 88;
   console.log(typeof b); // number
}
</code>```

Could anyone answer, how javaScript compiles or handles this particular case ? I know javaScript gives preference to function declaration when it comes to hoisting. But how a same identifier b holds two different values under same block or in same lexical scoping?

Someone could say like, okay, I'm going to use b as a function before it's declaration and as number after assigning it a number.

答:
In this case, the hoisting happens as follows:

declare var b, without initialization

declare function b, which overrides the var declaration

assign value 88 to variable b

So the function actually gets converted to the "logical equivalent" of:

function a(){
   var b; // hoisted
   b = function b(){ // hoisted
     var c = 52;
     console.log(c);
   }
   console.log(typeof b); // function
   b = 88;
   console.log(typeof b); // number
}
```

Note: Only declarations are hoisted, not initializations

Body:
function a(){
   console.log(typeof b); // function
   function b() {
     var c = 52;
     console.log(c);
   }
   var b = 88;
   console.log(typeof b); // number
}

Could anyone answer, how javaScript compiles or handles this particular case ? I know javaScript gives preference to function declaration when it comes to hoisting. But how a same identifier b holds two different values under same block or in same lexical scoping?

Someone could say like, okay, I'm going to use b as a function before it's declaration and as number after assigning it a number.

Body:
In this case, the hoisting happens as follows:

declare var b, without initialization

declare function b, which overrides the var declaration

assign value 88 to variable b

So the function actually gets converted to the "logical equivalent" of:

function a(){
   var b; // hoisted
   b = function b(){ // hoisted
     var c = 52;
     console.log(c);
   }
   console.log(typeof b); // function
   b = 88;
   console.log(typeof b); // number
}

Note: Only declarations are hoisted, not initializations


问:
Opening app from email link in NativeScript vue iOS
Edit For more explanation on how to use this plugin with vue, please see NativeScript vue, vuex and urlhandler

I'm trying to make it so that a link in an email can open an app I'm building (its a test app I'm building to learn NativeScript). I am using https://www.npmjs.com/package/nativescript-urlhandler with NativeScript vue on iOS.

In platforms/ios/######/app/App_Resources/iOS/Info.plist I have added

```<code><key>CFBundleURLTypes</key>
<array>
   <dict>
       <key>CFBundleURLName</key>
       <string>com.#######.######</string>
   </dict>
   <dict>
       <key>CFBundleURLSchemes</key>
       <array>
           <string>mycustomappfoobar</string>
       </array>
   </dict>
</array>
</code>```

And within app.js, I have added:

```<code>const handleOpenURL = require("nativescript-urlhandler").handleOpenURL;

handleOpenURL(function(appURL) {
    console.log('Got the following appURL', appURL);
  });
</code>```

When tapping on mycustomappfoobar://test (link in email) nothing happens...

I looked at the Angular example, and handleOpenURL is being called on initialisation... So I tried putting handleOpenURL within vues mounted hook - but this doesn't work either. Really stumped...

```<code>new Vue({
    mounted() {
      handleOpenURL(function(appURL) {
        console.log('Got the following appURL', appURL);
      });
    },
    render: h => h("frame", [h(Home)]),
    store: Store
}).$start();
</code>```

答:
You are calling handleOpenURL too late. This should be called prior to your Vue context being created so that the UIAppDelegate can be properly augmented behind the scenes.

From https://github.com/hypery2k/nativescript-urlhandler/blob/cd6939119910b6345e444055ad17716a7c0ad1d6/demo/app/app.ts

import { handleOpenURL, AppURL } from 'nativescript-urlhandler';

import './app.scss';
import './bundle-config';
import * as app from 'application';

handleOpenURL((appURL: AppURL) => {
    console.log('handleOpenURL', appURL);
});

app.start({ moduleName: 'main-page' });
```

Body:
Edit For more explanation on how to use this plugin with vue, please see NativeScript vue, vuex and urlhandler

I'm trying to make it so that a link in an email can open an app I'm building (its a test app I'm building to learn NativeScript). I am using https://www.npmjs.com/package/nativescript-urlhandler with NativeScript vue on iOS.

In platforms/ios/######/app/App_Resources/iOS/Info.plist I have added

<key>CFBundleURLTypes</key>
<array>
   <dict>
       <key>CFBundleURLName</key>
       <string>com.#######.######</string>
   </dict>
   <dict>
       <key>CFBundleURLSchemes</key>
       <array>
           <string>mycustomappfoobar</string>
       </array>
   </dict>
</array>

And within app.js, I have added:

const handleOpenURL = require("nativescript-urlhandler").handleOpenURL;

handleOpenURL(function(appURL) {
    console.log('Got the following appURL', appURL);
  });

When tapping on mycustomappfoobar://test (link in email) nothing happens...

I looked at the Angular example, and handleOpenURL is being called on initialisation... So I tried putting handleOpenURL within vues mounted hook - but this doesn't work either. Really stumped...

new Vue({
    mounted() {
      handleOpenURL(function(appURL) {
        console.log('Got the following appURL', appURL);
      });
    },
    render: h => h("frame", [h(Home)]),
    store: Store
}).$start();


问:
Scope problem - Nested $mdDialog within class based controller
I am moving my AngularJS controllers over to a class based model in order to support a few newer ideas that have come up lately. This has brought up an issue using AngularJS Materials $mdDialog service that I'm having trouble with.

I have a setup where a parent dialog is opened, and another performs a confirmation step when a user wants to undo any changes they've made.

Parent dialog Code:

```<code>// Expand item data
expandItem(data, ev){
  this._mdDialog.show({
    controller: 'expandCtrl',
    controllerAs: 'ec',
    templateUrl: 'path/to/template',
    parent: angular.element( document.body ),
    targetEvent: ev,
    clickOutsideToClose: true,
    locals: {
      data: {
        asset: data,
        table: this.selectTable
      }}
  }).then(rowData => {
  }, function(){});
}
</code>```

Nested dialog Code:

```<code>(function () {
'use strict';
class expandCtrl {

  constructor($mdDialog, data) {
    this.itemData = data;
    this.itemStateCapture = angular.copy(this.itemData);
    this._mdDialog = $mdDialog;
  }

  // Cancel edits and revert item back to its previous state
  cancelEdits(ev) {

    let cancelConfirm = this._mdDialog.confirm()
    .multiple(true)
    .title('Are you sure?')
    .textContent('Really cancel all edits and revert this item back to its original state?')
    .ariaLabel('Edit cancel confirmation')
    .targetEvent(ev)
    .ok('Cancel Edits!')
    .cancel('Go Back');

    this._mdDialog.show(cancelConfirm).then(function() {

      //**************************//
      //**** The Problem Line ****//
      //**************************//
      this.itemData = this.itemStateCapture;

    }, function() {});
  }
}
// Init Controller
angular.module('dbProject').controller('expandCtrl', expandCtrl);

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

I need to have the top level this.itemData variable be rewritten inside of the this._mdDialog.show() line. There appears to be a scoping problem though, and nothing I've tried successfully accesses that variable. I have tried injecting $scope, redirecting to an outside function, even accessing the data through angular.element().controller(), but I haven't made any headway.

What am I doing wrong?

答:
I ended up converting my controller to a hybrid sort of approach, and including $scope. $mdDialog seems to not function well without it (Though I would love to be proven wrong).

See below:

```<code>(function () {
'use strict';
  angular
    .module('myProject')
    .controller('expandCtrl', expandCtrl);

    expandCtrl.$inject = [
      '$mdDialog',
      '$timeout',
      '$scope',
      'data',
      'uaService',
      'dataService'
    ];

    function expandCtrl($mdDialog, $timeout, $scope, data, uaService, dataService){
      // Submit edits functionality
      this.submitEdits = function(table, access, data, ev){
        let confirmSubmit = $mdDialog.confirm()
        .multiple(true)
        .title('Are you sure?')
        .textContent('Really submit these changes?')
        .ariaLabel('Submit confirmation')
        .targetEvent(ev)
        .ok('Submit!')
        .cancel('Go Back');

        $mdDialog.show(confirmSubmit).then(function() {

            let editData = {
                table: $scope.table,
                data: $scope.itemData,
                prevData: $scope.itemStateCapture
            }

            dataService.submitEdits(editData)
            .then(res =>{
                console.log(res);
            }).catch(e =>{console.error(e)})

        }, function() {});
    }
  }
})();
</code>```

Body:
I am moving my AngularJS controllers over to a class based model in order to support a few newer ideas that have come up lately. This has brought up an issue using AngularJS Materials $mdDialog service that I'm having trouble with.

I have a setup where a parent dialog is opened, and another performs a confirmation step when a user wants to undo any changes they've made.

Parent dialog Code:

// Expand item data
expandItem(data, ev){
  this._mdDialog.show({
    controller: 'expandCtrl',
    controllerAs: 'ec',
    templateUrl: 'path/to/template',
    parent: angular.element( document.body ),
    targetEvent: ev,
    clickOutsideToClose: true,
    locals: {
      data: {
        asset: data,
        table: this.selectTable
      }}
  }).then(rowData => {
  }, function(){});
}

Nested dialog Code:

(function () {
'use strict';
class expandCtrl {

  constructor($mdDialog, data) {
    this.itemData = data;
    this.itemStateCapture = angular.copy(this.itemData);
    this._mdDialog = $mdDialog;
  }

  // Cancel edits and revert item back to its previous state
  cancelEdits(ev) {

    let cancelConfirm = this._mdDialog.confirm()
    .multiple(true)
    .title('Are you sure?')
    .textContent('Really cancel all edits and revert this item back to its original state?')
    .ariaLabel('Edit cancel confirmation')
    .targetEvent(ev)
    .ok('Cancel Edits!')
    .cancel('Go Back');

    this._mdDialog.show(cancelConfirm).then(function() {

      //**************************//
      //**** The Problem Line ****//
      //**************************//
      this.itemData = this.itemStateCapture;

    }, function() {});
  }
}
// Init Controller
angular.module('dbProject').controller('expandCtrl', expandCtrl);

})();

I need to have the top level this.itemData variable be rewritten inside of the this._mdDialog.show() line. There appears to be a scoping problem though, and nothing I've tried successfully accesses that variable. I have tried injecting $scope, redirecting to an outside function, even accessing the data through angular.element().controller(), but I haven't made any headway.

What am I doing wrong?

Body:
I ended up converting my controller to a hybrid sort of approach, and including $scope. $mdDialog seems to not function well without it (Though I would love to be proven wrong).

See below:

(function () {
'use strict';
  angular
    .module('myProject')
    .controller('expandCtrl', expandCtrl);

    expandCtrl.$inject = [
      '$mdDialog',
      '$timeout',
      '$scope',
      'data',
      'uaService',
      'dataService'
    ];

    function expandCtrl($mdDialog, $timeout, $scope, data, uaService, dataService){
      // Submit edits functionality
      this.submitEdits = function(table, access, data, ev){
        let confirmSubmit = $mdDialog.confirm()
        .multiple(true)
        .title('Are you sure?')
        .textContent('Really submit these changes?')
        .ariaLabel('Submit confirmation')
        .targetEvent(ev)
        .ok('Submit!')
        .cancel('Go Back');

        $mdDialog.show(confirmSubmit).then(function() {

            let editData = {
                table: $scope.table,
                data: $scope.itemData,
                prevData: $scope.itemStateCapture
            }

            dataService.submitEdits(editData)
            .then(res =>{
                console.log(res);
            }).catch(e =>{console.error(e)})

        }, function() {});
    }
  }
})();


问:
java persistance query language limit resultset
Suppose I have following rows in a table "mytable"
id

1

2

3

...
...

500

and my query is like select m from mytable m where m.id < 300
how can I get following output in the same order?

201

202

...
...
...

299

I am using setMaxResult(100) but it returns me output like this

1

2

...
...

100

any advice?

答:
If you are taking about JPA, you can use order by.

Either directly in your JPA query:

```<code>select m from mytable m where m.id < 300 order by m.id
</code>```

Or using criteria:

```<code>CriteriaQuery<MyTable> q = cb.createQuery(MyTable.class);
Root<MyTable> c = q.from(MyTable.class);
q.select(c);
q.orderBy(cb.asc(c.get("id")));
</code>```

Body:
If you are taking about JPA, you can use order by.

Either directly in your JPA query:

select m from mytable m where m.id < 300 order by m.id

Or using criteria:

CriteriaQuery<MyTable> q = cb.createQuery(MyTable.class);
Root<MyTable> c = q.from(MyTable.class);
q.select(c);
q.orderBy(cb.asc(c.get("id")));


问:
Is this good practice to change build files directly in angular?
I have some scenario to modify build files after deployment. Is this good practice to change manually?</p>

答: Not really, I would make build again and then deploy it. In your case if you do not have time to do all of this and you are sure your changes won't break it then go ahead. </p>


问:
2 list with the recycler view getItemcount method while showing ads?
I want to show ads in Recycler view but I have two list and I am  getting error while am using the 2 list;
I have ** List serverList ** and ** List recycleItems **and I want to show ads but not able to get the view when I use getItemCount() method of recycler view.

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.get(ArrayList.java:308)
        at com.mydata.adapter.ServerAdpter.onBindViewHolder(ServerAdpter.java:123)

```<code>public int getItemCount() {
    Log.e("Serv+re", String.valueOf(recycleItems.size() + serverList.size()));
    return recycleItems.size() + serverList.size();
}

public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

    int viewType = getItemViewType(position);

    switch (viewType) {
        case ITEM_data:
            Server server = serverList.get(position);
            ServerViewHolder v = (ServerViewHolder) holder;

            v.bind(position, listener);

        case ITEM_BANNER_AD:

        default:
            AdViewHolder bannerHolder = (AdViewHolder) holder;
            AdView adView = (AdView) recycleItems.get(position); //show error in this line
            ViewGroup adCardView = (ViewGroup) bannerHolder.itemView;
            if (adCardView.getChildCount() > 0) {
                adCardView.removeAllViews();
            }
            if (adView.getParent() != null) {
                ((ViewGroup) adView.getParent()).removeView(adView);
            }
            adCardView.addView(adView);

    }

}
</code>```

答:
You can't use recycler view with two lists, it's incorrect.
You can make interface DisplayItem(for example) to store all your items in one list and implement this interface in your classes.

```<code>public interface DisplayItem

public class Ad implements DisplayItem {

   // Ad properties

}

public class Info implements DisplayItem {

   // Info properties

}

class YourAdapter extends RecyclerView.Adapter {

   private List<DisplayItem> items;

   // Your adapter code
}
</code>```

And you work in adapter inly with this list.
In onBindViewHolder method you will cast this DisplayItem to desired class for viewHolder

Body:
I want to show ads in Recycler view but I have two list and I am  getting error while am using the 2 list;
I have ** List serverList ** and ** List recycleItems **and I want to show ads but not able to get the view when I use getItemCount() method of recycler view.

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.get(ArrayList.java:308)
        at com.mydata.adapter.ServerAdpter.onBindViewHolder(ServerAdpter.java:123)

public int getItemCount() {
    Log.e("Serv+re", String.valueOf(recycleItems.size() + serverList.size()));
    return recycleItems.size() + serverList.size();
}

public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

    int viewType = getItemViewType(position);

    switch (viewType) {
        case ITEM_data:
            Server server = serverList.get(position);
            ServerViewHolder v = (ServerViewHolder) holder;

            v.bind(position, listener);

        case ITEM_BANNER_AD:

        default:
            AdViewHolder bannerHolder = (AdViewHolder) holder;
            AdView adView = (AdView) recycleItems.get(position); //show error in this line
            ViewGroup adCardView = (ViewGroup) bannerHolder.itemView;
            if (adCardView.getChildCount() > 0) {
                adCardView.removeAllViews();
            }
            if (adView.getParent() != null) {
                ((ViewGroup) adView.getParent()).removeView(adView);
            }
            adCardView.addView(adView);

    }

}

Body:
You can't use recycler view with two lists, it's incorrect.
You can make interface DisplayItem(for example) to store all your items in one list and implement this interface in your classes.

public interface DisplayItem

public class Ad implements DisplayItem {

   // Ad properties

}

public class Info implements DisplayItem {

   // Info properties

}

class YourAdapter extends RecyclerView.Adapter {

   private List<DisplayItem> items;

   // Your adapter code
}

And you work in adapter inly with this list.
In onBindViewHolder method you will cast this DisplayItem to desired class for viewHolder


问:
Single plot multiple lines passing an array of colors?
Plotting two lines with a single plot command should not be easy?

```<code>import matplotlib.pyplot as plt
plt.plot([[1,2],[5,6]], c=['k','g'])

ValueError: Invalid RGBA argument
</code>```

I just need two lines, one is black and the other green. What is going on here?

答:
If you want that very much...

You can control the colors that will be cycled through using cycler.

```<code>from matplotlib import pyplot as plt
from cycler import cycler

ax = plt.subplot(111)
ax.set_prop_cycle(cycler('color', ['black', 'green']))

ax.plot([[1,2],[5,6]])
</code>```

Body:
Plotting two lines with a single plot command should not be easy?

import matplotlib.pyplot as plt
plt.plot([[1,2],[5,6]], c=['k','g'])

ValueError: Invalid RGBA argument

I just need two lines, one is black and the other green. What is going on here?

Body:
If you want that very much...

You can control the colors that will be cycled through using cycler.

from matplotlib import pyplot as plt
from cycler import cycler

ax = plt.subplot(111)
ax.set_prop_cycle(cycler('color', ['black', 'green']))

ax.plot([[1,2],[5,6]])


问:
Run task when a new branch was created
im new to the ci/cd topic. We are decided to move to  Jira, Bitbucket and Bamboo.

I think I didn't fully understand concept of bamboo.

We're using the following branches

develop as our development branch,

master for our regular releases. (e.g. 4.2, 4.5, 5, 5.1) => Major.Minor

release/ for hotfixes and security fixes for older major version (if the major version is already at 5 und we have to fix a bug in 4.xx

feature/

On a push our development instance will be updated automatically.
We also already have a script for cloning, creating the instance, setup apache etc...

Now I want that a the script will run every time a new feature/was created, but I didn't found a solution for that.

It's possible to run a task in bamboo on branch creation?

答:
If you haven't already created a plan, you need to do that as step one. Plans can run every time you create a branch or make a commit.
Under plan configuration -> Branches tab -> Create plan branch section, you can specify; "When new branch in repository is created and matches expression" and use e.g. "feature/.+" as expression.
Next add a stage. Stages can have one or more tasks. There is a dedicated script task that can run both Unix and Windows commands depending on what build agent you are using.
To sum it all up; a plan can have one or more stages, which can have one or more tasks.

It's also possible to make webhooks from bitbucket that can trigger on different parameters, like branch update and pull requests etc.

Title: Run task when a new branch was created


问:
POST request with the REST Client extension for Visual Studio Code
I'm using the "REST Client" extension for Visual Studio Code https://marketplace.visualstudio.com/items?itemName=humao.rest-client.

I'm able to make a GET request with this code:

```<code>GET https://some.domain.com/search/someuser/somekey?foo=5&bar=1
</code>```

and it works.

Now, I need to make a POST request and pass the foo and bar values as form fields.

I tried with:

```<code>POST https://some.domain.com/search/
Authorization: Basic someuser somekey
Content-Type: application/x-www-form-urlencoded

'foo'='5'
'bar'='1'
</code>```

but I'm getting back an error "Missing required parameter foo in the post body"

What is the correct syntax for a POST request with REST Client?

Thanks.

答:
It works like this:

```<code>POST https://some.domain.com/search/
Authorization: Basic someuser somekey
Content-Type: application/x-www-form-urlencoded

foo='5'&bar='1'

</code>```

parameters need to be concatenated with &

parameter names should
not be put in between quotes

Body:
I'm using the "REST Client" extension for Visual Studio Code https://marketplace.visualstudio.com/items?itemName=humao.rest-client.

I'm able to make a GET request with this code:

GET https://some.domain.com/search/someuser/somekey?foo=5&bar=1

and it works.

Now, I need to make a POST request and pass the foo and bar values as form fields.

I tried with:

POST https://some.domain.com/search/
Authorization: Basic someuser somekey
Content-Type: application/x-www-form-urlencoded

'foo'='5'
'bar'='1'

but I'm getting back an error "Missing required parameter foo in the post body"

What is the correct syntax for a POST request with REST Client?

Thanks.

Body:
It works like this:

POST https://some.domain.com/search/
Authorization: Basic someuser somekey
Content-Type: application/x-www-form-urlencoded

foo='5'&bar='1'

parameters need to be concatenated with &

parameter names should
not be put in between quotes


问:
pandas.DataFrame.plot gives matplotlib import error
I have a regression code which I've done all steps but at the end when I want to show predictions in graph, it gives a weird import error!

Here is the code:

```<code>import math
import numpy as np,datetime
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib
import pandas as pd
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from pandas.plotting import _converter
import datetime

df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

</code>```

That is not entire code but the parts that I think are related to the error.
 when I run it , I face this error:

```<code>line 54, in <module>
    df['Adj. Close'].plot()
ImportError: matplotlib is required for plotting.
</code>```

I found this  question but it didn't help me. I uninstalled the libraries and installed them again but nothing changed.

Edit: When I run import matplot lib in shell I also face this error:

ImportError: DLL load failed: The specified module could not be found

答:
Try</p>

```<code>plt.plot(df['Adj. Close'].tolist())
</code>```

Body:
I have a regression code which I've done all steps but at the end when I want to show predictions in graph, it gives a weird import error!

Here is the code:

import math
import numpy as np,datetime
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib
import pandas as pd
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from pandas.plotting import _converter
import datetime

df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

That is not entire code but the parts that I think are related to the error.
 when I run it , I face this error:

line 54, in <module>
    df['Adj. Close'].plot()
ImportError: matplotlib is required for plotting.

I found this  question but it didn't help me. I uninstalled the libraries and installed them again but nothing changed.

Edit: When I run import matplot lib in shell I also face this error:

ImportError: DLL load failed: The specified module could not be found

Body:
Try

plt.plot(df['Adj. Close'].tolist())


问:
Javascript dot function with event handlers

Question

How do I create a custom javascript dot function that does the same thing as the following code in jQuery:

```<code>$(document).on("click touchstart", ".someClass", function() {
   // code goes here
});
</code>```

I'd like to declare it like this:

```<code>$(".someClass").onClick(function () {
   // code goes here
});
</code>```

It needs to:

work with dynamically created elements (hence jQuery .on() instead of .click())

work with computer clicks as well as touch taps

ideally, but not mandatorily, it would be written in pure javascript (no jQuery in the prototype itself, but can still be accessed through jQuery)

What I've Tried

```<code>Object.prototype.onClick = function() {
   $(document).on('click touchstart', this, arguments);
};
</code>```

But I receive the following error in chrome console:

Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function

I think I'm declaring it incorrectly, and perhaps that this is also not the correct way to access events in javascript.

答:
You are looking for Event Delegation this allows you too dynamically add elements and still have them respond to click.

const getDiv = (name) => {
  if (Array.isArray(name) === false) name = [name];
  let div2 = document.createElement('div');
  name.forEach(n => div2.classList.add(n));
  div2.innerText = `${name}`;
  return div2;
};

const makeDivs = () => {
  const div = document.querySelector('#main');

  const {
    dataset: {
      count: x
    }
  } = div;

  for (let i = 0; i < x; i++) {
    div.appendChild(getDiv('div2'));
    div.appendChild(getDiv('div3'));
    div.appendChild(getDiv(['div2', 'div3']));
  }
};

document.addEventListener('click', ({
  target
}) => {
  if (target.matches('.div2')) console.log('You clicked a DIV2');

  if (target.matches('.div3')) console.log('You clicked a DIV3 !!')

  if (target.matches('button')) makeDivs();

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  border: 1px solid red;
  margin: 5px;
}</code>```

<button>Click Me!!!</button>```
</div>
</div>
</p>

<p>Wrapping this up into a custom function.</p>

<p>NOTE: I changed <code>selector</code> param to be an array, this allows you to pass complex selectors e.g. <code>div.myClass li:hover</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const getDiv = (name) => {
  if (Array.isArray(name) === false) name = [name];
  let div2 = document.createElement('div');
  name.forEach(n => div2.classList.add(n));
  div2.innerText = `${name}`;
  return div2;
};

const makeDivs = () => {
  const div = document.querySelector('#main');

  const {
    dataset: {
      count: x
    }
  } = div;

  for (let i = 0; i < x; i++) {
    div.appendChild(getDiv('div2'));
    div.appendChild(getDiv('div3'));
    div.appendChild(getDiv(['div2', 'div3']));
  }
};

document.on = (eventType, selector, callback) => {
  const events = eventType.split(' ');
  const selectors = (Array.isArray(selector)) ? selector : [selector];
  events.forEach(event => { document.addEventListener(event, (e) => {
      if(selectors.some(s => e.target.matches(s))) callback(e);
    });
  });
};

// Convenience method.
document.onClick = (selector, callback) => document.on('click', selector, callback);

// Simple
document.on('click', 'button', () => makeDivs());
document.on('click', '.div2', ({target}) => console.log('You clicked a DIV2'));

// Multi Event
document.on('click touchstart', '.div3', () => console.log('You clicked a DIV3'));

// Multi selectors
document.on('click', ['.div2', '.div3'], ({target}) => console.log('You clicked. !!'));

document.onClick('div', ({target}) => console.log('A Click Event!!'));</code>```

div {
  border: 1px solid red;
  margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='main' data-count="10">

</div>
<button>Click Me!!!</button></code>```

Body:
Question

How do I create a custom javascript dot function that does the same thing as the following code in jQuery:

$(document).on("click touchstart", ".someClass", function() {
   // code goes here
});

I'd like to declare it like this:

$(".someClass").onClick(function () {
   // code goes here
});

It needs to:

work with dynamically created elements (hence jQuery .on() instead of .click())

work with computer clicks as well as touch taps

ideally, but not mandatorily, it would be written in pure javascript (no jQuery in the prototype itself, but can still be accessed through jQuery)

What I've Tried

Object.prototype.onClick = function() {
   $(document).on('click touchstart', this, arguments);
};

But I receive the following error in chrome console:

Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function

I think I'm declaring it incorrectly, and perhaps that this is also not the correct way to access events in javascript.

Body:
You are looking for Event Delegation this allows you too dynamically add elements and still have them respond to click.

const getDiv = (name) => {
  if (Array.isArray(name) === false) name = [name];
  let div2 = document.createElement('div');
  name.forEach(n => div2.classList.add(n));
  div2.innerText = `${name}`;
  return div2;
};

const makeDivs = () => {
  const div = document.querySelector('#main');

  const {
    dataset: {
      count: x
    }
  } = div;

  for (let i = 0; i < x; i++) {
    div.appendChild(getDiv('div2'));
    div.appendChild(getDiv('div3'));
    div.appendChild(getDiv(['div2', 'div3']));
  }
};

document.addEventListener('click', ({
  target
}) => {
  if (target.matches('.div2')) console.log('You clicked a DIV2');

  if (target.matches('.div3')) console.log('You clicked a DIV3 !!')

  if (target.matches('button')) makeDivs();

});

div {
  border: 1px solid red;
  margin: 5px;
}

<div id='main' data-count="10">

</div>
<button>Click Me!!!</button>

Wrapping this up into a custom function.

NOTE: I changed selector param to be an array, this allows you to pass complex selectors e.g. div.myClass li:hover

const getDiv = (name) => {
  if (Array.isArray(name) === false) name = [name];
  let div2 = document.createElement('div');
  name.forEach(n => div2.classList.add(n));
  div2.innerText = `${name}`;
  return div2;
};

const makeDivs = () => {
  const div = document.querySelector('#main');

  const {
    dataset: {
      count: x
    }
  } = div;

  for (let i = 0; i < x; i++) {
    div.appendChild(getDiv('div2'));
    div.appendChild(getDiv('div3'));
    div.appendChild(getDiv(['div2', 'div3']));
  }
};

document.on = (eventType, selector, callback) => {
  const events = eventType.split(' ');
  const selectors = (Array.isArray(selector)) ? selector : [selector];
  events.forEach(event => { document.addEventListener(event, (e) => {
      if(selectors.some(s => e.target.matches(s))) callback(e);
    });
  });
};

// Convenience method.
document.onClick = (selector, callback) => document.on('click', selector, callback);

// Simple
document.on('click', 'button', () => makeDivs());
document.on('click', '.div2', ({target}) => console.log('You clicked a DIV2'));

// Multi Event
document.on('click touchstart', '.div3', () => console.log('You clicked a DIV3'));

// Multi selectors
document.on('click', ['.div2', '.div3'], ({target}) => console.log('You clicked. !!'));

document.onClick('div', ({target}) => console.log('A Click Event!!'));

div {
  border: 1px solid red;
  margin: 5px;
}

<div id='main' data-count="10">

</div>
<button>Click Me!!!</button>


问:
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") not returning VersionString
I have the following powershell script that we run on many servers to retrieve the SQL VersionString:

```<code>[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" "."
$srv.VersionString
</code>```

It works for all servers except one, which returns the a blank line.

Running just:

```<code>[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
New-Object "Microsoft.SqlServer.Management.Smo.Server" "."
</code>```

Returns:

```<code>AuditLevel                  :
BackupDirectory             :
BrowserServiceAccount       :
BrowserStartMode            :
BuildClrVersionString       :
BuildNumber                 :
ClusterName                 :
ClusterQuorumState          :
ClusterQuorumType           :
Collation                   :
CollationID                 :
ComparisonStyle             :
ComputerNamePhysicalNetBIOS :
DefaultFile                 :
DefaultLog                  :
Edition                     :
ErrorLogPath                :
FilestreamLevel             :
FilestreamShareName         :
HadrManagerStatus           :
InstallDataDirectory        :
InstallSharedDirectory      :
InstanceName                :
IsCaseSensitive             :
IsClustered                 :
IsFullTextInstalled         :
IsHadrEnabled               :
IsSingleUser                :
Language                    :
LoginMode                   :
MailProfile                 :
MasterDBLogPath             :
MasterDBPath                :
MaxPrecision                :
NamedPipesEnabled           :
NetName                     :
NumberOfLogFiles            :
OSVersion                   :
PerfMonMode                 :
PhysicalMemory              :
PhysicalMemoryUsageInKB     :
Platform                    :
Processors                  :
ProcessorUsage              :
Product                     :
ProductLevel                :
ResourceLastUpdateDateTime  :
ResourceVersionString       :
RootDirectory               :
ServerType                  :
ServiceAccount              :
ServiceInstanceId           :
ServiceName                 :
ServiceStartMode            :
SqlCharSet                  :
SqlCharSetName              :
SqlDomainGroup              :
SqlSortOrder                :
SqlSortOrderName            :
Status                      :
TapeLoadWaitTime            :
TcpEnabled                  :
VersionMajor                :
VersionMinor                :
VersionString               :
Name                        : SERVERDR
Version                     :
EngineEdition               :
ResourceVersion             :
BuildClrVersion             :
DefaultTextMode             : True
Configuration               : Microsoft.SqlServer.Management.Smo.Configuration
AffinityInfo                :
ProxyAccount                :
Mail                        :
Databases                   :
Endpoints                   :
Languages                   :
SystemMessages              :
UserDefinedMessages         :
Credentials                 :
CryptographicProviders      :
Logins                      :
Roles                       :
LinkedServers               :
SystemDataTypes             :
JobServer                   :
ResourceGovernor            :
ServiceMasterKey            :
Settings                    : Microsoft.SqlServer.Management.Smo.Settings
Information                 : Microsoft.SqlServer.Management.Smo.Information
UserOptions                 : Microsoft.SqlServer.Management.Smo.UserOptions
BackupDevices               :
FullTextService             :
ActiveDirectory             :
Triggers                    :
Audits                      :
ServerAuditSpecifications   :
AvailabilityGroups          :
ConnectionContext           : Data Source=.;Integrated Security=True;MultipleActiveResultSets=False;Application Name="SQL Management"
Events                      : Microsoft.SqlServer.Management.Smo.ServerEvents
OleDbProviderSettings       :
Urn                         :
Properties                  :
UserData                    :
State                       : Existing
IsDesignMode                : False
DomainName                  : SMO
DomainInstanceName          :
</code>```

So the question is, why is it not returning information about SQL that is installed on this server?

Server Details:
Windows 2008 R2
Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
Powershell Version 5.1

答:
Apparently, for SQL Server 2008, you need to load a secondary assembly aswell:

```<code>[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
#Need SmoExtended for smo.backup
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
</code>```

At least, you need that when you want to do a SQL Server restore in SQL Server, so perhaps it is also needed for your purposes.

I found that info here

I can't test this myself though..

Body:
I have the following powershell script that we run on many servers to retrieve the SQL VersionString:

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" "."
$srv.VersionString

It works for all servers except one, which returns the a blank line.

Running just:

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
New-Object "Microsoft.SqlServer.Management.Smo.Server" "."

Returns:

AuditLevel                  :
BackupDirectory             :
BrowserServiceAccount       :
BrowserStartMode            :
BuildClrVersionString       :
BuildNumber                 :
ClusterName                 :
ClusterQuorumState          :
ClusterQuorumType           :
Collation                   :
CollationID                 :
ComparisonStyle             :
ComputerNamePhysicalNetBIOS :
DefaultFile                 :
DefaultLog                  :
Edition                     :
ErrorLogPath                :
FilestreamLevel             :
FilestreamShareName         :
HadrManagerStatus           :
InstallDataDirectory        :
InstallSharedDirectory      :
InstanceName                :
IsCaseSensitive             :
IsClustered                 :
IsFullTextInstalled         :
IsHadrEnabled               :
IsSingleUser                :
Language                    :
LoginMode                   :
MailProfile                 :
MasterDBLogPath             :
MasterDBPath                :
MaxPrecision                :
NamedPipesEnabled           :
NetName                     :
NumberOfLogFiles            :
OSVersion                   :
PerfMonMode                 :
PhysicalMemory              :
PhysicalMemoryUsageInKB     :
Platform                    :
Processors                  :
ProcessorUsage              :
Product                     :
ProductLevel                :
ResourceLastUpdateDateTime  :
ResourceVersionString       :
RootDirectory               :
ServerType                  :
ServiceAccount              :
ServiceInstanceId           :
ServiceName                 :
ServiceStartMode            :
SqlCharSet                  :
SqlCharSetName              :
SqlDomainGroup              :
SqlSortOrder                :
SqlSortOrderName            :
Status                      :
TapeLoadWaitTime            :
TcpEnabled                  :
VersionMajor                :
VersionMinor                :
VersionString               :
Name                        : SERVERDR
Version                     :
EngineEdition               :
ResourceVersion             :
BuildClrVersion             :
DefaultTextMode             : True
Configuration               : Microsoft.SqlServer.Management.Smo.Configuration
AffinityInfo                :
ProxyAccount                :
Mail                        :
Databases                   :
Endpoints                   :
Languages                   :
SystemMessages              :
UserDefinedMessages         :
Credentials                 :
CryptographicProviders      :
Logins                      :
Roles                       :
LinkedServers               :
SystemDataTypes             :
JobServer                   :
ResourceGovernor            :
ServiceMasterKey            :
Settings                    : Microsoft.SqlServer.Management.Smo.Settings
Information                 : Microsoft.SqlServer.Management.Smo.Information
UserOptions                 : Microsoft.SqlServer.Management.Smo.UserOptions
BackupDevices               :
FullTextService             :
ActiveDirectory             :
Triggers                    :
Audits                      :
ServerAuditSpecifications   :
AvailabilityGroups          :
ConnectionContext           : Data Source=.;Integrated Security=True;MultipleActiveResultSets=False;Application Name="SQL Management"
Events                      : Microsoft.SqlServer.Management.Smo.ServerEvents
OleDbProviderSettings       :
Urn                         :
Properties                  :
UserData                    :
State                       : Existing
IsDesignMode                : False
DomainName                  : SMO
DomainInstanceName          :

So the question is, why is it not returning information about SQL that is installed on this server?

Server Details:
Windows 2008 R2
Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
Powershell Version 5.1

Body:
Apparently, for SQL Server 2008, you need to load a secondary assembly aswell:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
#Need SmoExtended for smo.backup
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null

At least, you need that when you want to do a SQL Server restore in SQL Server, so perhaps it is also needed for your purposes.

I found that info here

I can't test this myself though..