问:
Deploy Angular Application in Cloud Foundry
I am trying to deploy my Angular application in Cloud Foundry.

After testing locally with ng serve I confirmed my application is running well.

Here are the steps I did to deploy in CF:

In app directory executed ng build --prod which created dist folder"

Copied the dist folder into other directory and created manifest.yml file with following contents: (yml file and dist folder is on the same directory)

```<code>applications:

name: deploy-ng4

memory: 128M

  buildpack: https://github.com/cloudfoundry/staticfile-buildpack.git

  path: dist
</code>```

Executed

```<code>cf push deploy-ng4 -m 128M -b https://github.com/cloudfoundry/staticfile-buildpack.git
</code>```

CF logs shows deployed service is running, I haven't seen any errors.

When I tried browsing the URL which listed in cf apps for this deployed application, it's showing 403 - Forbidden.

答:
Probably already solved, but for people facing similar issue: Check outputPath property in  angular.json file. For this case it has to be:

```<code>"outputPath": "dist"
</code>```

I faced similar issue with PCF deployment. I generated my Angular application with IntelliJ Idea and it has appended the name of project to outputPath. Then I got exactly 403 - Forbidden accessing URL provided by PCF for the service, since correct URL was with /projectname appendix.

Body:
I am trying to deploy my Angular application in Cloud Foundry.

After testing locally with ng serve I confirmed my application is running well.

Here are the steps I did to deploy in CF:

In app directory executed ng build --prod which created dist folder"

Copied the dist folder into other directory and created manifest.yml file with following contents: (yml file and dist folder is on the same directory)

applications:

name: deploy-ng4

memory: 128M

  buildpack: https://github.com/cloudfoundry/staticfile-buildpack.git

  path: dist

Executed

cf push deploy-ng4 -m 128M -b https://github.com/cloudfoundry/staticfile-buildpack.git

CF logs shows deployed service is running, I haven't seen any errors.

When I tried browsing the URL which listed in cf apps for this deployed application, it's showing 403 - Forbidden.

Body:
Probably already solved, but for people facing similar issue: Check outputPath property in  angular.json file. For this case it has to be:

"outputPath": "dist"

I faced similar issue with PCF deployment. I generated my Angular application with IntelliJ Idea and it has appended the name of project to outputPath. Then I got exactly 403 - Forbidden accessing URL provided by PCF for the service, since correct URL was with /projectname appendix.


来源: stackexchange

问:
Listing information about all database files in SQL Server
Is it possible to list information about the files (MDF/LDF) of all databases on an SQL Server?

I'd like to get a list showing which database is using what files on the local disk.

What I tried:

exec sp_databases all databases

select * from sys.databases shows a lot of information about each database - but unfortunately it doesn't show the files used by each database.

select * from sys.database_files shows the mdf/ldf files of the master database - but not the other databases

答:
Below script can be used to get following information:
 1. DB Size Info
 2. FileSpaceInfo
 3. AutoGrowth
 4. Recovery Model
 5. Log_reuse_backup information</p>

```<code>CREATE TABLE #tempFileInformation
(
DBNAME          NVARCHAR(256),
[FILENAME]      NVARCHAR(256),
[TYPE]          NVARCHAR(120),
FILEGROUPNAME   NVARCHAR(120),
FILE_LOCATION   NVARCHAR(500),
FILESIZE_MB     DECIMAL(10,2),
USEDSPACE_MB    DECIMAL(10,2),
FREESPACE_MB    DECIMAL(10,2),
AUTOGROW_STATUS NVARCHAR(100)
)
GO

DECLARE @SQL VARCHAR(2000)

SELECT @SQL = '
 USE [?]
            INSERT INTO #tempFileInformation
            SELECT
                DBNAME          =DB_NAME(),
                [FILENAME]      =A.NAME,
                [TYPE]          = A.TYPE_DESC,
                FILEGROUPNAME   = fg.name,
                FILE_LOCATION   =a.PHYSICAL_NAME,
                FILESIZE_MB     = CONVERT(DECIMAL(10,2),A.SIZE/128.0),
                USEDSPACE_MB    = CONVERT(DECIMAL(10,2),(A.SIZE/128.0 - ((A.SIZE - CAST(FILEPROPERTY(A.NAME,''SPACEUSED'') AS INT))/128.0))),
                FREESPACE_MB    = CONVERT(DECIMAL(10,2),(A.SIZE/128.0 -  CAST(FILEPROPERTY(A.NAME,''SPACEUSED'') AS INT)/128.0)),
                AUTOGROW_STATUS = ''BY '' +CASE is_percent_growth when 0 then cast (growth/128 as varchar(10))+ '' MB - ''
                                                                  when 1 then cast (growth as varchar(10)) + ''% - '' ELSE '''' END
                                                                  + CASE MAX_SIZE WHEN 0 THEN '' DISABLED ''
                                                                                WHEN -1 THEN '' UNRESTRICTED''
                                                                                ELSE '' RESTRICTED TO '' + CAST(MAX_SIZE/(128*1024) AS VARCHAR(10)) + '' GB '' END
                                                                + CASE IS_PERCENT_GROWTH WHEn 1 then '' [autogrowth by percent]'' else '''' end
    from sys.database_files A
    left join sys.filegroups fg on a.data_space_id = fg.data_space_id
    order by A.type desc,A.name
    ;
    '

    --print @sql

    EXEC sp_MSforeachdb @SQL
    go

    SELECT dbSize.*,fg.*,d.log_reuse_wait_desc,d.recovery_model_desc
    FROM #tempFileInformation fg
    LEFT JOIN sys.databases d on fg.DBNAME = d.name
    CROSS APPLY
    (
        select dbname,
                sum(FILESIZE_MB) as [totalDBSize_MB],
                sum(FREESPACE_MB) as [DB_Free_Space_Size_MB],
                sum(USEDSPACE_MB) as [DB_Used_Space_Size_MB]
            from #tempFileInformation
            where  dbname = fg.dbname
            group by dbname
    )dbSize

go
DROP TABLE #tempFileInformation
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Below script can be used to get following information:
 1. DB Size Info
 2. FileSpaceInfo
 3. AutoGrowth
 4. Recovery Model
 5. Log_reuse_backup information

CREATE TABLE #tempFileInformation
(
DBNAME          NVARCHAR(256),
[FILENAME]      NVARCHAR(256),
[TYPE]          NVARCHAR(120),
FILEGROUPNAME   NVARCHAR(120),
FILE_LOCATION   NVARCHAR(500),
FILESIZE_MB     DECIMAL(10,2),
USEDSPACE_MB    DECIMAL(10,2),
FREESPACE_MB    DECIMAL(10,2),
AUTOGROW_STATUS NVARCHAR(100)
)
GO

DECLARE @SQL VARCHAR(2000)

SELECT @SQL = '
 USE [?]
            INSERT INTO #tempFileInformation
            SELECT
                DBNAME          =DB_NAME(),
                [FILENAME]      =A.NAME,
                [TYPE]          = A.TYPE_DESC,
                FILEGROUPNAME   = fg.name,
                FILE_LOCATION   =a.PHYSICAL_NAME,
                FILESIZE_MB     = CONVERT(DECIMAL(10,2),A.SIZE/128.0),
                USEDSPACE_MB    = CONVERT(DECIMAL(10,2),(A.SIZE/128.0 - ((A.SIZE - CAST(FILEPROPERTY(A.NAME,''SPACEUSED'') AS INT))/128.0))),
                FREESPACE_MB    = CONVERT(DECIMAL(10,2),(A.SIZE/128.0 -  CAST(FILEPROPERTY(A.NAME,''SPACEUSED'') AS INT)/128.0)),
                AUTOGROW_STATUS = ''BY '' +CASE is_percent_growth when 0 then cast (growth/128 as varchar(10))+ '' MB - ''
                                                                  when 1 then cast (growth as varchar(10)) + ''% - '' ELSE '''' END
                                                                  + CASE MAX_SIZE WHEN 0 THEN '' DISABLED ''
                                                                                WHEN -1 THEN '' UNRESTRICTED''
                                                                                ELSE '' RESTRICTED TO '' + CAST(MAX_SIZE/(128*1024) AS VARCHAR(10)) + '' GB '' END
                                                                + CASE IS_PERCENT_GROWTH WHEn 1 then '' [autogrowth by percent]'' else '''' end
    from sys.database_files A
    left join sys.filegroups fg on a.data_space_id = fg.data_space_id
    order by A.type desc,A.name
    ;
    '

    --print @sql

    EXEC sp_MSforeachdb @SQL
    go

    SELECT dbSize.*,fg.*,d.log_reuse_wait_desc,d.recovery_model_desc
    FROM #tempFileInformation fg
    LEFT JOIN sys.databases d on fg.DBNAME = d.name
    CROSS APPLY
    (
        select dbname,
                sum(FILESIZE_MB) as [totalDBSize_MB],
                sum(FREESPACE_MB) as [DB_Free_Space_Size_MB],
                sum(USEDSPACE_MB) as [DB_Used_Space_Size_MB]
            from #tempFileInformation
            where  dbname = fg.dbname
            group by dbname
    )dbSize

go
DROP TABLE #tempFileInformation

ContentLicense: CC BY-SA 4.0


问:
What is the difference between Jest-vue and Vue-jest?
I am studying unit testing for quasar framework now.
But I have not clear about vue-jest and jest-vue.
Please help me what the difference is? thank you.</p>

答:
These packages are from the same author. jest-vue was deprecated in favour of vue-jest.

As the description states,

DEPRECATED

this package has been renamed to vue-jest

Since it's older, jest-vue may not have all features of vue-jest.


问:
How to take a few values in column of a CSV file and export it to an python array
I have an CSV file something like:

```<code>Total Energy                 Pump        Diswasher      Freezer
2015-04-15T13:00:00+0200     70          50             80
2015-04-15T14:00:00+0400     80          40             80
2015-04-15T15:00:00+0300     30          90             80
2015-04-15T16:00:00+0600     40          80             80
2015-04-15T17:00:00+0700     50          70             80
</code>```

I want to take only the first 3 values of each column and export to different Python arrays. But for the total energy, I want to take only the value after "+" sign only.

```<code>The result is expected something like:
Total_energy = [200, 400, 300]
Pump = [70, 80, 30]
Diswasher = [50, 40, 90]
Freezer = [80, 80, 80]
</code>```

I have two issue:
1. Only take the first three values in each column and I do not want to take the whole column.
2. First column(Total Energy) I only need the value after "+" sign

```<code>import pandas
colnames = ['Total_energy', 'Pump', 'Diswasher',]
data = pandas.read_csv('Data_60min.csv', names=colnames)
names = data.name.tolist()
Total_energy = data.Total_energy.tolist()
Pump = data.Pump.tolist()
Diswasher = data.Diswasher.tolist()
</code>```

I can do something like above but it takes for the whole column and also I do not know how to take the value after the "+" sign only.enter image description here

答:
First filter top 3 rows by DataFrame.head or DataFrame.iloc:

```<code>data = data.head(3)
</code>```

Or:

```<code>data = data.iloc[:3]
</code>```

then seelct values after + by Series.str.split or by Series.str.extract:

```<code>data['Total_energy'] = data['Total_energy'].str.split('+').str[1].astype(int)

data['Total_energy'] = data['Total_energy'].str.extract('\+(.+)', expand=False).astype(int)
</code>```

Last is possible create dictionary and select by keys for lists:

```<code>d = data.to_dict('list')
print (d)
{'Total_energy': [200, 400, 300],
 'Pump': [70, 80, 30],
 'Diswasher': [50, 40, 90],
  'Freezer': [80, 80, 80]}

print (d['Total_energy'])
[200, 400, 300]

print (d['Pump'])
[70, 80, 30]
</code>```

Also working select each column separately like in your solution:

```<code>names = data.name.tolist()
Total_energy = data.Total_energy.tolist()
Pump = data.Pump.tolist()
Diswasher = data.Diswasher.tolist()
</code>```

EDIT:

If need filter columns in read_csv by names is use parameter usecols, not names:

```<code>colnames = ['cet_cest_timestamp', 'DE_KN_residential2_circulation_pump', 'DE_KN_residential2_dishwasher']
data = pd.read_csv('household_data_60min_singleindex.csv', usecols=colnames)
print (data.head())

         cet_cest_timestamp  DE_KN_residential2_circulation_pump  \
0  2015-04-15T13:00:00+0200                               19.776
1  2015-04-15T14:00:00+0200                               19.780
2  2015-04-15T15:00:00+0200                               19.784
3  2015-04-15T16:00:00+0200                               19.788
4  2015-04-15T17:00:00+0200                               19.854

   DE_KN_residential2_dishwasher
0                          2.765
1                          2.765
2                          2.765
3                          2.765
4                          2.765
</code>```

Body:
I have an CSV file something like:

Total Energy                 Pump        Diswasher      Freezer
2015-04-15T13:00:00+0200     70          50             80
2015-04-15T14:00:00+0400     80          40             80
2015-04-15T15:00:00+0300     30          90             80
2015-04-15T16:00:00+0600     40          80             80
2015-04-15T17:00:00+0700     50          70             80

I want to take only the first 3 values of each column and export to different Python arrays. But for the total energy, I want to take only the value after "+" sign only.

The result is expected something like:
Total_energy = [200, 400, 300]
Pump = [70, 80, 30]
Diswasher = [50, 40, 90]
Freezer = [80, 80, 80]

I have two issue:
1. Only take the first three values in each column and I do not want to take the whole column.
2. First column(Total Energy) I only need the value after "+" sign

import pandas
colnames = ['Total_energy', 'Pump', 'Diswasher',]
data = pandas.read_csv('Data_60min.csv', names=colnames)
names = data.name.tolist()
Total_energy = data.Total_energy.tolist()
Pump = data.Pump.tolist()
Diswasher = data.Diswasher.tolist()

I can do something like above but it takes for the whole column and also I do not know how to take the value after the "+" sign only.enter image description here

Body:
First filter top 3 rows by DataFrame.head or DataFrame.iloc:

data = data.head(3)

Or:

data = data.iloc[:3]

then seelct values after + by Series.str.split or by Series.str.extract:

data['Total_energy'] = data['Total_energy'].str.split('+').str[1].astype(int)

data['Total_energy'] = data['Total_energy'].str.extract('\+(.+)', expand=False).astype(int)

Last is possible create dictionary and select by keys for lists:

d = data.to_dict('list')
print (d)
{'Total_energy': [200, 400, 300],
 'Pump': [70, 80, 30],
 'Diswasher': [50, 40, 90],
  'Freezer': [80, 80, 80]}

print (d['Total_energy'])
[200, 400, 300]

print (d['Pump'])
[70, 80, 30]

Also working select each column separately like in your solution:

names = data.name.tolist()
Total_energy = data.Total_energy.tolist()
Pump = data.Pump.tolist()
Diswasher = data.Diswasher.tolist()

EDIT:

If need filter columns in read_csv by names is use parameter usecols, not names:

colnames = ['cet_cest_timestamp', 'DE_KN_residential2_circulation_pump', 'DE_KN_residential2_dishwasher']
data = pd.read_csv('household_data_60min_singleindex.csv', usecols=colnames)
print (data.head())

         cet_cest_timestamp  DE_KN_residential2_circulation_pump  \
0  2015-04-15T13:00:00+0200                               19.776
1  2015-04-15T14:00:00+0200                               19.780
2  2015-04-15T15:00:00+0200                               19.784
3  2015-04-15T16:00:00+0200                               19.788
4  2015-04-15T17:00:00+0200                               19.854

   DE_KN_residential2_dishwasher
0                          2.765
1                          2.765
2                          2.765
3                          2.765
4                          2.765


问:
JMX MBeans not visible after deploy
ENVIRONMENT NetBeans 6.9.1, GlassFish 3.1, METRO 2.1

I want to make a list of available web services, so I'm querying JMX MBeanServer for *:type=WSEndpoint,*. The problem is, there are only ~56 Mbeans after deploy, and WSEndpoint beans are not registered. If I connect with JMXterm, the MBean count jumps up to ~380, and all WSEndpoint beans are visible. From JConsole, I don't see any folder, but after running JMXterm I do.

Even if I call the web service, the MBeans stay unregistered. METRO monitoring is enabled by default, and I left it like that; after deploy a console message INFO: Metro monitoring rootname successfully set to: amx:pp=/mon/server-mon[server],type=WSEndpoint,name=... is shown.

What does JMXterm do so that all MBeans are visible? Does it do any method calls to MBeanServer? Is there any solution, so that I can access WSEndpoint beans right after deploy?

答: You can trigger the registration of all AMX MBeans with by executing the JMX operation bootAMX on the MBean amx-support:type=boot-amx.

Title: JMX MBeans not visible after deploy


问:
React component not re-rendering on state change using setState
I have a HomeScreen component which has button. I am trying to popup a modelview(Seperate component ie PopUpView) on the button click. In PopUpView i am sending its visibility as prop (isVisible).On the click of the button i am trying to change the state value popUpIsVisible from false to true. Hoping that this would re-render and popup my model view(Note this is working fine if i explicitly pass true). However with the state change it look like the render function is not being called and the popUp is not being displayed. Thanks for your help in advance

```<code>import React from 'react';
import { View, StyleSheet, Text, Button, TouchableHighlight, Alert, Dimensions} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import PopUpView from './src/PopUpView';

class HomeScreen extends React.Component {

  constructor(props) {
      super(props);
      this.state = {
        popUpIsVisible: false,
      };
    }

  setPopUpIsVisible(isVisible){
    this.setState({popUpIsVisible: isVisible });
  }

  render() {
    this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"blue" }}>
        <Text>Home Screen</Text>
          <PopUpView isVisible={this.state.popUpIsVisible}/>
          <Button onPress={() => {this.setPopUpIsVisible(true)}}  title="Open PopUp Screen"/>
      </View>
    );
  }
}

const RootStack = createStackNavigator(
  {
    Home: HomeScreen
  },
  {
    initialRouteName: 'Home',
  }
);

const AppContainer = createAppContainer(RootStack);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}
</code>```

PopUpView.js

```<code>import React from 'react';
import { View, Modal,StyleSheet, Text, TouchableOpacity, Dimensions} from 'react-native';
import { TabView, TabBar,SceneMap } from 'react-native-tab-view';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

const FirstRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#ff4081' }} />
);
const SecondRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
const ThirdRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);

export default class PopUpView extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
          modalVisible:this.props.isVisible,
          index: 0,
          routes: [
            { key: 'first', title: 'HIGHLIGHTS' },
            { key: 'second', title: 'AMENITIES' },
            { key: 'third', title: 'FACILITIES' },
          ],
        };
    }
    setModalVisible(visible) {
      this.setState({modalVisible: visible});
    }

renderHeader = props => <TabBar
    {...props}
    indicatorStyle={{backgroundColor: 'red'}}
    tabStyle={styles.bubble}
    labelStyle={styles.noLabel}
/>;

  render() {
      return (
      <Modal
          animationType="slide"
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>
          <View style={styles.container}>
            <View style={styles.navBar}>
              <Text style={styles.navBarTitle}>Test</Text>
              <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                }}>
              <Icon style={styles.closeButton} name="close" size={35} color="grey" />
              </TouchableOpacity>
            </View>
            <TabView
              navigationState={this.state}
              renderScene={SceneMap({
                first: FirstRoute,
                second: SecondRoute,
                third: ThirdRoute,
                })}
              onIndexChange={index => this.setState({ index })}
              initialLayout={{ width: Dimensions.get('window').width }}
              renderTabBar={props =>
                      <TabBar
                          {...props}
                          style={{ backgroundColor: 'white' }}
                          indicatorStyle={{backgroundColor: 'black'}}
                          tabStyle={styles.bubble}
                          labelStyle={styles.label}
                      />
                  }
              />
          </View>
        </Modal>
      );
    }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    margin: 50,
    marginLeft: 20,
    marginRight: 20,
    marginBottom: 20,
    backgroundColor: "white",
    borderWidth: 1,
    borderColor: "grey",
    flexDirection: 'column'
  },
  navBar:{
    height:70,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    borderBottomColor: 'lightgrey',
    borderBottomWidth: 1,
  },
  navBarTitle:{
    fontSize: 25,
    fontFamily: 'Optima',
    paddingLeft:15,
  },
  closeButton:{
    paddingRight:12,
  },
  label: {
        color: 'black'
    }
})
</code>```

答:
Add below line into constructor after state defining</p>

```<code>this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
</code>```

Body:
I have a HomeScreen component which has button. I am trying to popup a modelview(Seperate component ie PopUpView) on the button click. In PopUpView i am sending its visibility as prop (isVisible).On the click of the button i am trying to change the state value popUpIsVisible from false to true. Hoping that this would re-render and popup my model view(Note this is working fine if i explicitly pass true). However with the state change it look like the render function is not being called and the popUp is not being displayed. Thanks for your help in advance

import React from 'react';
import { View, StyleSheet, Text, Button, TouchableHighlight, Alert, Dimensions} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import PopUpView from './src/PopUpView';

class HomeScreen extends React.Component {

  constructor(props) {
      super(props);
      this.state = {
        popUpIsVisible: false,
      };
    }

  setPopUpIsVisible(isVisible){
    this.setState({popUpIsVisible: isVisible });
  }

  render() {
    this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"blue" }}>
        <Text>Home Screen</Text>
          <PopUpView isVisible={this.state.popUpIsVisible}/>
          <Button onPress={() => {this.setPopUpIsVisible(true)}}  title="Open PopUp Screen"/>
      </View>
    );
  }
}

const RootStack = createStackNavigator(
  {
    Home: HomeScreen
  },
  {
    initialRouteName: 'Home',
  }
);

const AppContainer = createAppContainer(RootStack);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}

PopUpView.js

import React from 'react';
import { View, Modal,StyleSheet, Text, TouchableOpacity, Dimensions} from 'react-native';
import { TabView, TabBar,SceneMap } from 'react-native-tab-view';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

const FirstRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#ff4081' }} />
);
const SecondRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
const ThirdRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);

export default class PopUpView extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
          modalVisible:this.props.isVisible,
          index: 0,
          routes: [
            { key: 'first', title: 'HIGHLIGHTS' },
            { key: 'second', title: 'AMENITIES' },
            { key: 'third', title: 'FACILITIES' },
          ],
        };
    }
    setModalVisible(visible) {
      this.setState({modalVisible: visible});
    }

renderHeader = props => <TabBar
    {...props}
    indicatorStyle={{backgroundColor: 'red'}}
    tabStyle={styles.bubble}
    labelStyle={styles.noLabel}
/>;

  render() {
      return (
      <Modal
          animationType="slide"
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>
          <View style={styles.container}>
            <View style={styles.navBar}>
              <Text style={styles.navBarTitle}>Test</Text>
              <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                }}>
              <Icon style={styles.closeButton} name="close" size={35} color="grey" />
              </TouchableOpacity>
            </View>
            <TabView
              navigationState={this.state}
              renderScene={SceneMap({
                first: FirstRoute,
                second: SecondRoute,
                third: ThirdRoute,
                })}
              onIndexChange={index => this.setState({ index })}
              initialLayout={{ width: Dimensions.get('window').width }}
              renderTabBar={props =>
                      <TabBar
                          {...props}
                          style={{ backgroundColor: 'white' }}
                          indicatorStyle={{backgroundColor: 'black'}}
                          tabStyle={styles.bubble}
                          labelStyle={styles.label}
                      />
                  }
              />
          </View>
        </Modal>
      );
    }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    margin: 50,
    marginLeft: 20,
    marginRight: 20,
    marginBottom: 20,
    backgroundColor: "white",
    borderWidth: 1,
    borderColor: "grey",
    flexDirection: 'column'
  },
  navBar:{
    height:70,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    borderBottomColor: 'lightgrey',
    borderBottomWidth: 1,
  },
  navBarTitle:{
    fontSize: 25,
    fontFamily: 'Optima',
    paddingLeft:15,
  },
  closeButton:{
    paddingRight:12,
  },
  label: {
        color: 'black'
    }
})

Body:
Add below line into constructor after state defining

this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);


问:
How do i control listview item details?
I have 2 pages with their own listviews. I need all the details of the first listview item to be added to the other listview when it is selected. Thank you for any help on my vague question.

```<code>public async void OnTapped(object sender, ItemTappedEventArgs e)
{
    await Navigation.PushAsync(new TeamPage());
}
</code>```

So, when an item is tapped it switches to the other page but want the selected item to be added to the TeamPage listview. All the details of the items are bound to an IList.

答:
According to your description, you want to tap ListView Item, then navigate to another page, display the tapped item in this page listview, am I right? If yes, I do one sample that you can take a look:

Page 1:

```<code>   <StackLayout>
        <ListView ItemsSource="{Binding model3s}" ItemTapped="ListView_ItemTapped">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding Id}" />
                            <Label Text="{Binding FirstName}" />
                            <Label Text="{Binding LastName}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

public partial class Page11 : ContentPage
{

    public ObservableCollection<model3> model3s { get; set; }
    public Page11 ()
    {
        InitializeComponent ();
        model3s = new ObservableCollection<model3>()
        {
            new model3(){Id=1,FirstName="Cherry",LastName="Bu",Description="Age is 28, class is A"},
            new model3(){Id=2,FirstName="Barry",LastName="Bu",Description="Age is 32, class is B"},
            new model3(){Id=3,FirstName="Wendy",LastName="Bu",Description="Age is 25, class is C"},
            new model3(){Id=4,FirstName="Stnfan",LastName="Bu",Description="Age is 27, class is A"},
            new model3(){Id=5,FirstName="Annie",LastName="Bu",Description="Age is 28, class is B"},
            new model3(){Id=6,FirstName="Mattew",LastName="Bu",Description="Age is 25, class is C"},
            new model3(){Id=7,FirstName="Amy",LastName="Bu",Description="Age is 29, class is A"},
            new model3(){Id=8,FirstName="Elvis",LastName="Bu",Description="Age is 32, class is B"},
        };
        this.BindingContext = this;
    }

    private async void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        var content = e.Item as model3;
        await Navigation.PushModalAsync(new Page12(content));
    }
}

public class model3
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string Description { get; set; }
}
</code>```

Page2:

```<code><StackLayout>
        <ListView x:Name="listview1" ItemsSource="{Binding collection}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding FirstName}" />
                            <Label Text="{Binding LastName}" />
                            <Label Text="{Binding Description}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

public partial class Page12 : ContentPage
{
   public ObservableCollection<model3> collection { get; set; }

    public Page12 (model3 content)
    {

        InitializeComponent ();
        collection = new ObservableCollection<model3>();
        collection.Add(content);

        this.BindingContext = this;
    }
}
</code>```

Title: How do i control listview item details?

Body:
I have 2 pages with their own listviews. I need all the details of the first listview item to be added to the other listview when it is selected. Thank you for any help on my vague question.

public async void OnTapped(object sender, ItemTappedEventArgs e)
{
    await Navigation.PushAsync(new TeamPage());
}

So, when an item is tapped it switches to the other page but want the selected item to be added to the TeamPage listview. All the details of the items are bound to an IList.

Body:
According to your description, you want to tap ListView Item, then navigate to another page, display the tapped item in this page listview, am I right? If yes, I do one sample that you can take a look:

Page 1:

   <StackLayout>
        <ListView ItemsSource="{Binding model3s}" ItemTapped="ListView_ItemTapped">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding Id}" />
                            <Label Text="{Binding FirstName}" />
                            <Label Text="{Binding LastName}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

public partial class Page11 : ContentPage
{

    public ObservableCollection<model3> model3s { get; set; }
    public Page11 ()
    {
        InitializeComponent ();
        model3s = new ObservableCollection<model3>()
        {
            new model3(){Id=1,FirstName="Cherry",LastName="Bu",Description="Age is 28, class is A"},
            new model3(){Id=2,FirstName="Barry",LastName="Bu",Description="Age is 32, class is B"},
            new model3(){Id=3,FirstName="Wendy",LastName="Bu",Description="Age is 25, class is C"},
            new model3(){Id=4,FirstName="Stnfan",LastName="Bu",Description="Age is 27, class is A"},
            new model3(){Id=5,FirstName="Annie",LastName="Bu",Description="Age is 28, class is B"},
            new model3(){Id=6,FirstName="Mattew",LastName="Bu",Description="Age is 25, class is C"},
            new model3(){Id=7,FirstName="Amy",LastName="Bu",Description="Age is 29, class is A"},
            new model3(){Id=8,FirstName="Elvis",LastName="Bu",Description="Age is 32, class is B"},
        };
        this.BindingContext = this;
    }

    private async void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        var content = e.Item as model3;
        await Navigation.PushModalAsync(new Page12(content));
    }
}

public class model3
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string Description { get; set; }
}

Page2:

<StackLayout>
        <ListView x:Name="listview1" ItemsSource="{Binding collection}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding FirstName}" />
                            <Label Text="{Binding LastName}" />
                            <Label Text="{Binding Description}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

public partial class Page12 : ContentPage
{
   public ObservableCollection<model3> collection { get; set; }

    public Page12 (model3 content)
    {

        InitializeComponent ();
        collection = new ObservableCollection<model3>();
        collection.Add(content);

        this.BindingContext = this;
    }
}


问:
mktemp on macOS random file generation fails: file exists
When I create a random file on macOS with mktemp I get:

```<code>mktemp /tmp/test.XXXXXXX.json
mktemp: mkstemp failed on /tmp/test.XXXXXXX.json: File exists
</code>```

It does not replace XXXXXXX with random string. Works fine on Linux but not on macOS.

答: Turns out, for whatever reason, macOS version of mktemp supports only trailing XXXXXX for random string, in other words mktemp /tmp/test.XXXX will work but not /tmp/test.XXXX.json

Body:
When I create a random file on macOS with mktemp I get:

mktemp /tmp/test.XXXXXXX.json
mktemp: mkstemp failed on /tmp/test.XXXXXXX.json: File exists

It does not replace XXXXXXX with random string. Works fine on Linux but not on macOS.


问:
How to get Age in Months using BirthDate column by MySQL query?
First I asked this question to do this and accepted answer helped me. But Now the problem is that I have to calculate age in months.

Question:

I have a BirthDate column in MySQL database table to store user's date of birth. Now I have form in html/php with two fields(1. Age From 2. Age To).

If user want to get all users where their ages are between 400 months and 600 months, Is it possible to do this with MySQL query using BirthDate column.

Thanks

答:
```<code>SELECT * FROM that_table
WHERE CURRENT_TIMESTAMP BETWEEN (BirthDate + INTERVAL 400 MONTH) AND (BirthDate + INTERVAL 600 MONTH)
</code>```


问:
upgradesstables not working in dse cassandra upgrade
I am upgrading DSE cassndra from 4.8.16 to 5.0.15 , but when i execute nodetool upgradesstables I am getting below error:

```<code>error: commitlog directory '/var/lib/cassandra/commitlog' or, if it does not already exist, an existing parent directory of it, is not readable and writable for the DSE. Check file system and configuration.
-- StackTrace --
org.apache.cassandra.exceptions.ConfigurationException: commitlog directory '/var/lib/cassandra/commitlog' or, if it does not already exist, an existing parent directory of it, is not readable and writable for the DSE. Check file system and configuration.
        at org.apache.cassandra.config.DatabaseDescriptor.resolveAndCheckDirectory(DatabaseDescriptor.java:798)
        at org.apache.cassandra.config.DatabaseDescriptor.applyConfig(DatabaseDescriptor.java:535)
        at org.apache.cassandra.config.DatabaseDescriptor.<clinit>(DatabaseDescriptor.java:131)
        at org.apache.cassandra.tools.NodeProbe.checkJobs(NodeProbe.java:274)
        at org.apache.cassandra.tools.NodeProbe.upgradeSSTables(NodeProbe.java:328)
        at org.apache.cassandra.tools.nodetool.UpgradeSSTable.execute(UpgradeSSTable.java:54)
        at org.apache.cassandra.tools.NodeTool$NodeToolCmd.run(NodeTool.java:253)
        at org.apache.cassandra.tools.NodeTool.main(NodeTool.java:167)
</code>```

答:
Commit logs from the previous version incompatible with the new version.
To flush the commit log of the old installation use

```<code>nodetool -h hostname drain
</code>```

also check commit log directory path in cassandra.yml.

Body:
I am upgrading DSE cassndra from 4.8.16 to 5.0.15 , but when i execute nodetool upgradesstables I am getting below error:

error: commitlog directory '/var/lib/cassandra/commitlog' or, if it does not already exist, an existing parent directory of it, is not readable and writable for the DSE. Check file system and configuration.
-- StackTrace --
org.apache.cassandra.exceptions.ConfigurationException: commitlog directory '/var/lib/cassandra/commitlog' or, if it does not already exist, an existing parent directory of it, is not readable and writable for the DSE. Check file system and configuration.
        at org.apache.cassandra.config.DatabaseDescriptor.resolveAndCheckDirectory(DatabaseDescriptor.java:798)
        at org.apache.cassandra.config.DatabaseDescriptor.applyConfig(DatabaseDescriptor.java:535)
        at org.apache.cassandra.config.DatabaseDescriptor.<clinit>(DatabaseDescriptor.java:131)
        at org.apache.cassandra.tools.NodeProbe.checkJobs(NodeProbe.java:274)
        at org.apache.cassandra.tools.NodeProbe.upgradeSSTables(NodeProbe.java:328)
        at org.apache.cassandra.tools.nodetool.UpgradeSSTable.execute(UpgradeSSTable.java:54)
        at org.apache.cassandra.tools.NodeTool$NodeToolCmd.run(NodeTool.java:253)
        at org.apache.cassandra.tools.NodeTool.main(NodeTool.java:167)

Body:
Commit logs from the previous version incompatible with the new version.
To flush the commit log of the old installation use

nodetool -h hostname drain

also check commit log directory path in cassandra.yml.


问:
how to clear data of a table before each ajax call
Table data is not cleared after each ajax call. New data is appended below the previous data

$('#show_data').remove();
I have tried this but its not working

View

```<code><table id="example2" class="table table-bordered table-hover">
                        <thead>
                        <tr>
                            <th>Title</th>
                            <th>Description</th>
                            <th>Date</th>
                            <th>Time</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                        <tbody id="show_data">

                        </tbody>
                    </table>
</code>```

Script

```<code><script>
    $(document).ready(function () {

        //Date picker
        $('#datepicker').datepicker({
            autoclose: true,
            format: 'yyyy-mm-dd',
        });

        $("#datepicker").attr("autocomplete", "off");

    $(document).on('submit','#myform',function(){
        event.preventDefault();
        var date = $('#datepicker').val();
        console.log(date);
        $('#show_data').remove();
        $.ajax({
            type:"POST",
            url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
            data:{date:date},
            dataType: "json",
            success:function(data) {
                console.log(data[0].blog_id);
                let i;

                for(i=0;i<data.length;i++){

                    $('#show_data').append('<tr><td>' + data[i].article_name + '</td>' +
                        '<td>' + data[i].description + '</td>' +
                        '<td>' + data[i].date + '</td>' +
                        '<td>' + data[i].time + '</td>' +
                        '</tr>');
                }
            },
            error: function() {
                alert("oops...");
            },

        });
    });
 });

</script>
</code>```

Present Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 1
         Data 2
         Data 3

Expected Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 3

答:
You can try change code

```<code>$('#show_data').remove();
</code>```

to

```<code>$('#show_data').empty();
</code>```

empty() function will clear content of the element. Docs is here https://api.jquery.com/empty/

Body:
Table data is not cleared after each ajax call. New data is appended below the previous data

$('#show_data').remove();
I have tried this but its not working

View

                            Title
                            Description
                            Date
                            Time
                            Action

Script

Present Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 1
         Data 2
         Data 3

Expected Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 3

Body:
You can try change code

$('#show_data').remove();

to

$('#show_data').empty();

empty() function will clear content of the element. Docs is here https://api.jquery.com/empty/


问:
How to handle errors in Kafka Consumer
I have the following Kafka Configuration class:

```<code>@Configuration
@AllArgsConstructor(access = AccessLevel.PROTECTED)

public class KafkaConfiguration {
private final KafkaConfigurationProperties kafkaConfigurationProperties;

@Bean
public ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> debtCollectorConsumerContainerFactory() {
     ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfiguration()));
    factory.setConcurrency(kafkaConfigurationProperties.getDebtCollectorConsumerThreads());
    factory.setStatefulRetry(true);
    factory.setErrorHandler(new SeekToCurrentErrorHandler((record, exception) -> {
        if (exception instanceof SomeCustomException) {
            // here I want to mannually Acknowledge the consuming of the record
        }
    }, 10));

    ContainerProperties containerProperties = factory.getContainerProperties();
    containerProperties.setAckOnError(false);
    containerProperties.setAckMode(ContainerProperties.AckMode.RECORD);
    return factory;
}

@Bean
@Qualifier(KAFKA_LOAN_REPAYMENT_PRODUCER)
public Producer<String, RepaymentEvent> loanRepaymentProducer() {
    return new KafkaProducer<>(producerConfiguration());
}

@Bean
@Qualifier(KAFKA_DEBT_COLLECTOR_PRODUCER)
public Producer<String, RepaymentEvent> debtCollectorProducer() {
    return new KafkaProducer<>(producerConfiguration());
}

private Map<String, Object> consumerConfiguration() {
    Map<String, Object> properties = new HashMap<>();
    properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfigurationProperties.getBootstrapServers());
    properties.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfigurationProperties.getDebtCollectorConsumerGroupId());
    properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class);
    properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, kafkaConfigurationProperties.getDebtCollectorConsumerAutoOffsetReset());
    properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, kafkaConfigurationProperties.getDebtCollectorConsumerMaxPollRecords());
    properties.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, Boolean.TRUE);
    properties.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, kafkaConfigurationProperties.getConfluentEndpoint());
    properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Boolean.FALSE);
    return properties;
}

private Map<String, Object> producerConfiguration() {
    Map<String, Object> properties = new HashMap<>();
    properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfigurationProperties.getBootstrapServers());
    properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
    properties.put(KafkaAvroSerializerConfig.SCHEMA_REGISTRY_URL_CONFIG, kafkaConfigurationProperties.getConfluentEndpoint());
    return properties;
}
}
</code>```

and the following KafkaListener:

```<code>@Slf4j
@Component
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class DebtCollectorIncomingClient {

private final RepaymentTransferProcessService repaymentTransferProcessService;

@KafkaListener(
        topics = "${kafka.debtCollectorIncomingTopic}",
        groupId = "${kafka.debtCollectorConsumerAutoOffsetReset}",
        containerFactory = "debtCollectorConsumerContainerFactory")
public void submitMoneyTransferCommand(@Payload RepaymentEvent repaymentEvent) {
    log.info("Receiving command: {}", repaymentEvent);
    if (repaymentEvent.getPayload() instanceof RepaymentRequestTransfer) {
        RepaymentTransfer repaymentTransfer = aRepaymentTransfer(repaymentEvent);
        repaymentTransferProcessService.startRepaymentTransferProcess(repaymentTransfer);
    }
}

private RepaymentTransfer aRepaymentTransfer(RepaymentEvent repaymentEvent) {
    RepaymentRequestTransfer repaymentRequestTransfer = (RepaymentRequestTransfer) repaymentEvent.getPayload();
    return RepaymentTransfer.builder()
            .clientId(repaymentRequestTransfer.getClientId())
            .contractId(repaymentRequestTransfer.getContractId())
            .amount(BigDecimal.valueOf(repaymentRequestTransfer.getAmount()))
            .currency(Currency.getInstance(repaymentRequestTransfer.getCurrency().name()))
            .debtCollectorExternalId(repaymentEvent.getCorrelationId())
            .debtType(repaymentRequestTransfer.getDebtType())
            .build();
}
}
</code>```

I want to use SeekToCurrentErrorHandler for error handling and I want something specific like here, but currently I'm using springBootVersion=2.0.4.RELEASE, springKafkaVersion=2.1.4.RELEASE, kafkaVersion=2.0.1 and confluentVersion=3.3.1. Can you help me to set up the dependencies and the configuration in order to handle errors in Kafka consumer?

Regards!

答:
After some days and reading Gary answers at some other posts, I finally found the solution for my problem. Maybe the question is not very descriptive, but this answer is describing the behavior that I want.

in a @Configuration I'm creating the following Spring bean:

```<code>@Bean
    public ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> debtCollectorConsumerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfiguration()));
        factory.setConcurrency(kafkaConfigurationProperties.getDebtCollectorConsumerThreads());
        factory.setErrorHandler(new BlockingSeekToCurrentErrorHandler());

        ContainerProperties containerProperties = factory.getContainerProperties();
        containerProperties.setAckOnError(false);
        containerProperties.setAckMode(ContainerProperties.AckMode.RECORD);

        factory.setRetryTemplate(retryTemplate());
        return factory;
    }

private RetryTemplate retryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setBackOffPolicy(backOffPolicy());
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(kafkaConfigurationProperties.getDebtCollectorConsumerRetryAttempts()));
    return retryTemplate;
}
</code>```

And BlockingSeekToCurrentErrorHandler class:

```<code>public class BlockingSeekToCurrentErrorHandler extends SeekToCurrentErrorHandler {

    private static final int MAX_RETRY_ATTEMPTS = Integer.MAX_VALUE;

    BlockingSeekToCurrentErrorHandler() {
        super(MAX_RETRY_ATTEMPTS);
    }

    @Override
    public void handle(Exception exception, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, MessageListenerContainer container) {
        try {
            if (!records.isEmpty()) {
                log.warn("Exception: {} occurred with message: {}", exception, exception.getMessage());
                MetricFactory.handleDebtCollectorIncomingBlockingError(records.get(0), exception);
                super.handle(exception, records, consumer, container);
            }
        } catch (SerializationException e) {
            log.warn("Exception: {} occurred with message: {}", e, e.getMessage());
            MetricFactory.handleDebtCollectorIncomingDeserializationError(records, e);
        }
    }
}
</code>```

Title: How to handle errors in Kafka Consumer

Body:
I have the following Kafka Configuration class:

@Configuration
@AllArgsConstructor(access = AccessLevel.PROTECTED)

public class KafkaConfiguration {
private final KafkaConfigurationProperties kafkaConfigurationProperties;

@Bean
public ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> debtCollectorConsumerContainerFactory() {
     ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfiguration()));
    factory.setConcurrency(kafkaConfigurationProperties.getDebtCollectorConsumerThreads());
    factory.setStatefulRetry(true);
    factory.setErrorHandler(new SeekToCurrentErrorHandler((record, exception) -> {
        if (exception instanceof SomeCustomException) {
            // here I want to mannually Acknowledge the consuming of the record
        }
    }, 10));

    ContainerProperties containerProperties = factory.getContainerProperties();
    containerProperties.setAckOnError(false);
    containerProperties.setAckMode(ContainerProperties.AckMode.RECORD);
    return factory;
}

@Bean
@Qualifier(KAFKA_LOAN_REPAYMENT_PRODUCER)
public Producer<String, RepaymentEvent> loanRepaymentProducer() {
    return new KafkaProducer<>(producerConfiguration());
}

@Bean
@Qualifier(KAFKA_DEBT_COLLECTOR_PRODUCER)
public Producer<String, RepaymentEvent> debtCollectorProducer() {
    return new KafkaProducer<>(producerConfiguration());
}

private Map<String, Object> consumerConfiguration() {
    Map<String, Object> properties = new HashMap<>();
    properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfigurationProperties.getBootstrapServers());
    properties.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfigurationProperties.getDebtCollectorConsumerGroupId());
    properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class);
    properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, kafkaConfigurationProperties.getDebtCollectorConsumerAutoOffsetReset());
    properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, kafkaConfigurationProperties.getDebtCollectorConsumerMaxPollRecords());
    properties.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, Boolean.TRUE);
    properties.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, kafkaConfigurationProperties.getConfluentEndpoint());
    properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Boolean.FALSE);
    return properties;
}

private Map<String, Object> producerConfiguration() {
    Map<String, Object> properties = new HashMap<>();
    properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfigurationProperties.getBootstrapServers());
    properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
    properties.put(KafkaAvroSerializerConfig.SCHEMA_REGISTRY_URL_CONFIG, kafkaConfigurationProperties.getConfluentEndpoint());
    return properties;
}
}

and the following KafkaListener:

@Slf4j
@Component
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class DebtCollectorIncomingClient {

private final RepaymentTransferProcessService repaymentTransferProcessService;

@KafkaListener(
        topics = "${kafka.debtCollectorIncomingTopic}",
        groupId = "${kafka.debtCollectorConsumerAutoOffsetReset}",
        containerFactory = "debtCollectorConsumerContainerFactory")
public void submitMoneyTransferCommand(@Payload RepaymentEvent repaymentEvent) {
    log.info("Receiving command: {}", repaymentEvent);
    if (repaymentEvent.getPayload() instanceof RepaymentRequestTransfer) {
        RepaymentTransfer repaymentTransfer = aRepaymentTransfer(repaymentEvent);
        repaymentTransferProcessService.startRepaymentTransferProcess(repaymentTransfer);
    }
}

private RepaymentTransfer aRepaymentTransfer(RepaymentEvent repaymentEvent) {
    RepaymentRequestTransfer repaymentRequestTransfer = (RepaymentRequestTransfer) repaymentEvent.getPayload();
    return RepaymentTransfer.builder()
            .clientId(repaymentRequestTransfer.getClientId())
            .contractId(repaymentRequestTransfer.getContractId())
            .amount(BigDecimal.valueOf(repaymentRequestTransfer.getAmount()))
            .currency(Currency.getInstance(repaymentRequestTransfer.getCurrency().name()))
            .debtCollectorExternalId(repaymentEvent.getCorrelationId())
            .debtType(repaymentRequestTransfer.getDebtType())
            .build();
}
}

I want to use SeekToCurrentErrorHandler for error handling and I want something specific like here, but currently I'm using springBootVersion=2.0.4.RELEASE, springKafkaVersion=2.1.4.RELEASE, kafkaVersion=2.0.1 and confluentVersion=3.3.1. Can you help me to set up the dependencies and the configuration in order to handle errors in Kafka consumer?

Regards!

Body:
After some days and reading Gary answers at some other posts, I finally found the solution for my problem. Maybe the question is not very descriptive, but this answer is describing the behavior that I want.

in a @Configuration I'm creating the following Spring bean:

@Bean
    public ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> debtCollectorConsumerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, RepaymentEvent> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfiguration()));
        factory.setConcurrency(kafkaConfigurationProperties.getDebtCollectorConsumerThreads());
        factory.setErrorHandler(new BlockingSeekToCurrentErrorHandler());

        ContainerProperties containerProperties = factory.getContainerProperties();
        containerProperties.setAckOnError(false);
        containerProperties.setAckMode(ContainerProperties.AckMode.RECORD);

        factory.setRetryTemplate(retryTemplate());
        return factory;
    }

private RetryTemplate retryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setBackOffPolicy(backOffPolicy());
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(kafkaConfigurationProperties.getDebtCollectorConsumerRetryAttempts()));
    return retryTemplate;
}

And BlockingSeekToCurrentErrorHandler class:

public class BlockingSeekToCurrentErrorHandler extends SeekToCurrentErrorHandler {

    private static final int MAX_RETRY_ATTEMPTS = Integer.MAX_VALUE;

    BlockingSeekToCurrentErrorHandler() {
        super(MAX_RETRY_ATTEMPTS);
    }

    @Override
    public void handle(Exception exception, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, MessageListenerContainer container) {
        try {
            if (!records.isEmpty()) {
                log.warn("Exception: {} occurred with message: {}", exception, exception.getMessage());
                MetricFactory.handleDebtCollectorIncomingBlockingError(records.get(0), exception);
                super.handle(exception, records, consumer, container);
            }
        } catch (SerializationException e) {
            log.warn("Exception: {} occurred with message: {}", e, e.getMessage());
            MetricFactory.handleDebtCollectorIncomingDeserializationError(records, e);
        }
    }
}


问:
How to lock running some block of code within specific thread in Gevent?
Simplified code looks like

```<code>import gevent
from requests import get
from gevent.monkey import patch_all; patch_all()

def f1():
    print("Thread 1 start")
    x = get('https://www.google.com')
    print("Thread 1 end")

def f2():
    print("Thread 2")

gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2)
])
</code>```

And the output is expected:

Thread 1 start

  Thread 2

  Thread 1 end

I need to lock calling of the get request. So, I need to get the following output:

Thread 1 start

  Thread 1 end

  Thread 2

How achieve such get request locking?

答:
you should do like this:</p>

```<code>import gevent
from requests import get
from gevent.monkey import patch_all; patch_all()

from gevent.lock import Semaphore

sem = Semaphore()

def f1():
    sem.acquire()
    print("Thread 1 start")
    gevent.sleep(0.1)
    print("Thread 1 end")
    sem.release()

def f2():
    with sem:
        print("Thread 2")

gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2)
])
</code>```

Body:
Simplified code looks like

import gevent
from requests import get
from gevent.monkey import patch_all; patch_all()

def f1():
    print("Thread 1 start")
    x = get('https://www.google.com')
    print("Thread 1 end")

def f2():
    print("Thread 2")

gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2)
])

And the output is expected:

Thread 1 start

  Thread 2

  Thread 1 end

I need to lock calling of the get request. So, I need to get the following output:

Thread 1 start

  Thread 1 end

  Thread 2

How achieve such get request locking?

Body:
you should do like this:

import gevent
from requests import get
from gevent.monkey import patch_all; patch_all()

from gevent.lock import Semaphore

sem = Semaphore()

def f1():
    sem.acquire()
    print("Thread 1 start")
    gevent.sleep(0.1)
    print("Thread 1 end")
    sem.release()

def f2():
    with sem:
        print("Thread 2")

gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2)
])


问:
Datagrid rowbackground color
I'm trying to change a background color of a row datagrid in codebehing I'm using a binding property
in code behing I see the color changes but when displayed the background color doesn't change.
When  I play with the scroll I some of the </p>

答:
Header Color change:

```<code>With datagrid1
 .ColumnHeadersDefaultCellStyle.Font = New Font("Arial", 12.0F, FontStyle.Bold, GraphicsUnit.Pixel)
 .ColumnHeadersDefaultCellStyle.BackColor = Color.GreenYellow
 .EnableHeadersVisualStyles = False
End With
</code>```

Row and Background Color Change

```<code>With datagrid1
 .RowsDefaultCellStyle.BackColor = Color.Beige
 .AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(224, 255, 179)
 .DefaultCellStyle.Font = New Font("Arial", 12.0F, FontStyle.Regular, GraphicsUnit.Pixel)
End With
</code>```

change like that. i hope its help to you

Title: Datagrid rowbackground color

Body:
Header Color change:

With datagrid1
 .ColumnHeadersDefaultCellStyle.Font = New Font("Arial", 12.0F, FontStyle.Bold, GraphicsUnit.Pixel)
 .ColumnHeadersDefaultCellStyle.BackColor = Color.GreenYellow
 .EnableHeadersVisualStyles = False
End With

Row and Background Color Change

With datagrid1
 .RowsDefaultCellStyle.BackColor = Color.Beige
 .AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(224, 255, 179)
 .DefaultCellStyle.Font = New Font("Arial", 12.0F, FontStyle.Regular, GraphicsUnit.Pixel)
End With

change like that. i hope its help to you


问:
How to override template/view of SilverStripe's User Defined Form
I am developing a simple SilverStripe project for learning purpose. I am using SilverStripe User Defined Form module to create form pages.

The way the user defined form module renders the form in the template/ view is using the $UserDefinedForm variable in the content field. Now, I need to do some customization to the built-in User Defined Form template. So I decided to override the controller and page.

This is my EventPage

```<code><?php

namespace {

    use SilverStripe\UserForms\Model\UserDefinedForm;

    class EventPage extends UserDefinedForm
    {

    }
}
</code>```

This is my EventPageController

```<code><?php

namespace {

    use SilverStripe\UserForms\Control\UserDefinedFormController;

    class EventPageController extends UserDefinedFormController
    {

    }
}
</code>```

This is my EventPage.ss

```<code><h1>Event Page</h1>

$UserDefinedForm
</code>```

This page is overridden, but the form is not rendered. How can I render the form?

答:
A complete answer might help.
ContactPage.php

namespace InsiteApps\CMS\Model {

```<code>use SilverStripe\UserForms\Control\UserDefinedFormController;
use SilverStripe\UserForms\Model\UserDefinedForm;

class ContactPage extends UserDefinedForm
{
    private static $table_name = 'ContactPage';

}

class ContactPageController extends UserDefinedFormController
{

}
</code>```

}

In your theme, templates folder (the folder structure is dependant on your namespace)

templates/InsiteApps/CMS/Model/Layout/ContactPage.ss

    $Form

Body:
I am developing a simple SilverStripe project for learning purpose. I am using SilverStripe User Defined Form module to create form pages.

The way the user defined form module renders the form in the template/ view is using the $UserDefinedForm variable in the content field. Now, I need to do some customization to the built-in User Defined Form template. So I decided to override the controller and page.

This is my EventPage

<?php

namespace {

    use SilverStripe\UserForms\Model\UserDefinedForm;

    class EventPage extends UserDefinedForm
    {

    }
}

This is my EventPageController

<?php

namespace {

    use SilverStripe\UserForms\Control\UserDefinedFormController;

    class EventPageController extends UserDefinedFormController
    {

    }
}

This is my EventPage.ss

Event Page

$UserDefinedForm

This page is overridden, but the form is not rendered. How can I render the form?

Body:
A complete answer might help.
ContactPage.php

namespace InsiteApps\CMS\Model {

use SilverStripe\UserForms\Control\UserDefinedFormController;
use SilverStripe\UserForms\Model\UserDefinedForm;

class ContactPage extends UserDefinedForm
{
    private static $table_name = 'ContactPage';

}

class ContactPageController extends UserDefinedFormController
{

}

}

In your theme, templates folder (the folder structure is dependant on your namespace)

templates/InsiteApps/CMS/Model/Layout/ContactPage.ss

<div class="contact-page-form">
    $Form
</div>


问:
how to color second p tag in html without using any style and class?
I have 3 p tags,

```<code><p> hi </p>
<p>hello</P>
<p>bye</P>
</code>```

I want to color the 2nd p tag into red by only using pure css(not using any javascript).
without using any inline style and class how can i achieve this?

```<code><p> hi </p>
<p>hello</P>
<p>bye</P>
</code>```

答:
In addition to Jack BashFords answer , if you want to style only even/odd numbered children you can use

```<code>.p:nth-child(even/odd) {
  margin-right: 0;
}
</code>```

If you want more control you can use this formula an+b

You can read more here

“a” is an integer value

“n” is the literal letter “n”

“+” is an operator and may be either “+” or “-”

“b” is an integer and is required if an operator is included in the
  formula

For example 4n , targets only multiples of 4.

```<code>.p:nth-child(4n) {
      margin-right: 0;
    }
</code>```

Body:
I have 3 p tags,

 hi

hello

bye

I want to color the 2nd p tag into red by only using pure css(not using any javascript).
without using any inline style and class how can i achieve this?

 hi

hello

bye

Body:
In addition to Jack BashFords answer , if you want to style only even/odd numbered children you can use

.p:nth-child(even/odd) {
  margin-right: 0;
}

If you want more control you can use this formula an+b

You can read more here

“a” is an integer value

“n” is the literal letter “n”

“+” is an operator and may be either “+” or “-”

“b” is an integer and is required if an operator is included in the
  formula

For example 4n , targets only multiples of 4.

.p:nth-child(4n) {
      margin-right: 0;
    }


问:
Complete IPv4 Address Space Output
I am trying to run a .py file that will output a .txt file that contains all of the IP addresses from 0.0.0.0 to 255.255.255.255, but it is throwing an error in the Sublime Text Console. This is my .py file:

```<code>def ipRange(start_ip, end_ip):
   start = list(map(int, start_ip.split(".")))
   end = list(map(int, end_ip.split(".")))
   temp = start
   ip_range = []

   ip_range.append(start_ip)
   while temp != end:
      start[3] += 1
      for i in (3, 2, 1):
         if temp[i] == 256:
            temp[i] = 0
            temp[i-1] += 1
      ip_range.append(".".join(map(str, temp)))

   return ip_range

output = []
# sample usage
ip_range = ipRange("0.0.0.0", "255.255.255.255")
for ip in ip_range:
    output.append(ip)
fo = open("output.txt", "rw+")
line = fo.writelines(output)
fo.close()
</code>```

This is my console output:

```<code>tput: No value for $TERM and no -T specified
]0;LeoLaneseltdKernel Information:
Darwin 18.5.0 x86_64
</code>```

答:
I have modified by some logging print to debug the flow of the code in the following way:-

```<code>   def ipRange(start_ip, end_ip):
       start = list(map(int, start_ip.split(".")))
       end = list(map(int, end_ip.split(".")))
       print('start', start)
       print('end', end)
       temp = start
       ip_range = []

       ip_range.append(start_ip)
       print('IP ADDRESS IS', ip_range)
       while temp != end:
          print('while ')
          start[3] += 1
          for i in (3, 2, 1):
             if temp[i] == 256:
                temp[i] = 0
                temp[i-1] += 1
      ip_range.append(".".join(map(str, temp)))
      print('IP ADDRESS IS', ip_range)
      return ip_range

print("Executing the python script")
output = []
# sample usage
ip_range = ipRange("0.0.0.0", "0.0.0.10")
for ip in ip_range:
    print(ip)
    output.append(ip)
fo = open("output.txt", "w+")
line = fo.writelines(output)
fo.close()
</code>```

Please find the following output(I have only print 10 ip addresses):-

```<code>[nikhilesh@pgadmin ~]$ python 2.py
starting the python
('start', [0, 0, 0, 0])
('end', [0, 0, 0, 10])
('IP ADDRESS IS', ['0.0.0.0'])
while
while
while
while
while
while
while
while
while
while
('IP ADDRESS IS', ['0.0.0.0', '0.0.0.1', '0.0.0.2', '0.0.0.3', '0.0.0.4', '0.0.0.5', '0.0.0.6', '0.0.0.7', '0.0.0.8', '0.0.0.9', '0.0.0.10'])
0.0.0.0
0.0.0.1
0.0.0.2
0.0.0.3
0.0.0.4
0.0.0.5
0.0.0.6
0.0.0.7
0.0.0.8
0.0.0.9
0.0.0.10
[nikhilesh@pgadmin ~]$ cat output.txt

0.0.0.00.0.0.10.0.0.20.0.0.30.0.0.40.0.0.50.0.0.60.0.0.70.0.0.80.0.0.90.0.0.10
</code>```

I am using python version 2.7.5

Title: Complete IPv4 Address Space Output

Body:
I am trying to run a .py file that will output a .txt file that contains all of the IP addresses from 0.0.0.0 to 255.255.255.255, but it is throwing an error in the Sublime Text Console. This is my .py file:

def ipRange(start_ip, end_ip):
   start = list(map(int, start_ip.split(".")))
   end = list(map(int, end_ip.split(".")))
   temp = start
   ip_range = []

   ip_range.append(start_ip)
   while temp != end:
      start[3] += 1
      for i in (3, 2, 1):
         if temp[i] == 256:
            temp[i] = 0
            temp[i-1] += 1
      ip_range.append(".".join(map(str, temp)))

   return ip_range

output = []
# sample usage
ip_range = ipRange("0.0.0.0", "255.255.255.255")
for ip in ip_range:
    output.append(ip)
fo = open("output.txt", "rw+")
line = fo.writelines(output)
fo.close()

This is my console output:

tput: No value for $TERM and no -T specified
]0;LeoLaneseltdKernel Information:
Darwin 18.5.0 x86_64

Body:
I have modified by some logging print to debug the flow of the code in the following way:-

   def ipRange(start_ip, end_ip):
       start = list(map(int, start_ip.split(".")))
       end = list(map(int, end_ip.split(".")))
       print('start', start)
       print('end', end)
       temp = start
       ip_range = []

       ip_range.append(start_ip)
       print('IP ADDRESS IS', ip_range)
       while temp != end:
          print('while ')
          start[3] += 1
          for i in (3, 2, 1):
             if temp[i] == 256:
                temp[i] = 0
                temp[i-1] += 1
      ip_range.append(".".join(map(str, temp)))
      print('IP ADDRESS IS', ip_range)
      return ip_range

print("Executing the python script")
output = []
# sample usage
ip_range = ipRange("0.0.0.0", "0.0.0.10")
for ip in ip_range:
    print(ip)
    output.append(ip)
fo = open("output.txt", "w+")
line = fo.writelines(output)
fo.close()

Please find the following output(I have only print 10 ip addresses):-

[nikhilesh@pgadmin ~]$ python 2.py
starting the python
('start', [0, 0, 0, 0])
('end', [0, 0, 0, 10])
('IP ADDRESS IS', ['0.0.0.0'])
while
while
while
while
while
while
while
while
while
while
('IP ADDRESS IS', ['0.0.0.0', '0.0.0.1', '0.0.0.2', '0.0.0.3', '0.0.0.4', '0.0.0.5', '0.0.0.6', '0.0.0.7', '0.0.0.8', '0.0.0.9', '0.0.0.10'])
0.0.0.0
0.0.0.1
0.0.0.2
0.0.0.3
0.0.0.4
0.0.0.5
0.0.0.6
0.0.0.7
0.0.0.8
0.0.0.9
0.0.0.10
[nikhilesh@pgadmin ~]$ cat output.txt

0.0.0.00.0.0.10.0.0.20.0.0.30.0.0.40.0.0.50.0.0.60.0.0.70.0.0.80.0.0.90.0.0.10

I am using python version 2.7.5


问:
Mysql Switch case returning incorrect results
Consider the following row in my mysql table:

```<code>id   Url   Urls
6433       ["https://do.foo/", "https://do.foo/2"]
</code>```

I need to populate url with the first url from the urls column wherever it is empty. So I ran this query:

```<code>select coalesce(url, '') = '' as `is_true` ,
convert(JSON_EXTRACT(urls, '$[0]'), CHAR) as `extracted`,
case url
    when coalesce(url, '') = '' then convert(JSON_EXTRACT(urls, '$[0]'), CHAR)
    else '3'
end as `valid_url`
from table_name where id = 6433 ;
</code>```

The result was:

```<code>is_true      extracted          valid_url
1            "https://do.foo/"  3
</code>```

Is there any reason the extracted url to not show up in the valid url column?

答:
Your CASE expression is incorrect. When you write CASE column WHEN expression as you have done, the value in column is compared against the expression, so in your case you are comparing url (which is NULL) against '', which fails. Either change your CASE expression to the CASE WHEN expression form, or change url to COALESCE(url, '') and the expression to ''. For example:

```<code>select coalesce(url, '') = '' as `is_true` ,
convert(JSON_EXTRACT(urls, '$[0]'), CHAR) as `extracted`,
case
    when coalesce(url, '') = '' then convert(JSON_EXTRACT(urls, '$[0]'), CHAR)
    else '3'
end as `valid_url`
from table_name where id = 6433
</code>```

or

```<code>select coalesce(url, '') = '' as `is_true` ,
convert(JSON_EXTRACT(urls, '$[0]'), CHAR) as `extracted`,
case coalesce(url, '')
    when '' then convert(JSON_EXTRACT(urls, '$[0]'), CHAR)
    else '3'
end as `valid_url`
from table_name where id = 6433
</code>```

In both cases the output is:

```<code>is_true     extracted           valid_url
1           "https://do.foo/"   "https://do.foo/"
</code>```

Demo on dbfiddle

Body:
Consider the following row in my mysql table:

id   Url   Urls
6433       ["https://do.foo/", "https://do.foo/2"]

I need to populate url with the first url from the urls column wherever it is empty. So I ran this query:

select coalesce(url, '') = '' as `is_true` ,
convert(JSON_EXTRACT(urls, '$[0]'), CHAR) as `extracted`,
case url
    when coalesce(url, '') = '' then convert(JSON_EXTRACT(urls, '$[0]'), CHAR)
    else '3'
end as `valid_url`
from table_name where id = 6433 ;

The result was:

is_true      extracted          valid_url
1            "https://do.foo/"  3

Is there any reason the extracted url to not show up in the valid url column?

Body:
Your CASE expression is incorrect. When you write CASE column WHEN expression as you have done, the value in column is compared against the expression, so in your case you are comparing url (which is NULL) against '', which fails. Either change your CASE expression to the CASE WHEN expression form, or change url to COALESCE(url, '') and the expression to ''. For example:

select coalesce(url, '') = '' as `is_true` ,
convert(JSON_EXTRACT(urls, '$[0]'), CHAR) as `extracted`,
case
    when coalesce(url, '') = '' then convert(JSON_EXTRACT(urls, '$[0]'), CHAR)
    else '3'
end as `valid_url`
from table_name where id = 6433

or

select coalesce(url, '') = '' as `is_true` ,
convert(JSON_EXTRACT(urls, '$[0]'), CHAR) as `extracted`,
case coalesce(url, '')
    when '' then convert(JSON_EXTRACT(urls, '$[0]'), CHAR)
    else '3'
end as `valid_url`
from table_name where id = 6433

In both cases the output is:

is_true     extracted           valid_url
1           "https://do.foo/"   "https://do.foo/"

Demo on dbfiddle


问:
iPhone: Reading a string from a file is returning the wrong results
What I'm doing:

I am reading some data off a file several times while my app runs. I use the following code to do so:

```<code>NSString *dataPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data.txt"];
NSString *data = [NSString stringWithContentsOfFile:dataPath encoding:NSStringEncodingConversionExternalRepresentation error:NULL];
NSArray *components = [data componentsSeparatedByString:@"|||||"];
</code>```

The first time this is called, it works as expected - I get an array of length 5, each section containing a relevant string.

What goes wrong:

This file is never modified. Yet, when I call the same procedure a second time (or third, fourth etc) I don't get the same result. Instead, an array of length 1 is returned, containing only part of the necessary data.

Why? I can't see any reason for this to go wrong... any help is much appreciated!

答:
Since the file is in you AppBundle this means that you can't modify this file at all.
Are you sure that, where ever this code is called, the autorelease object are retained correctly?

If you call this block of code every time you want this data, it might be an idea to save the results of the first time and use that every time. This will speed things up a bit.

Body:
What I'm doing:

I am reading some data off a file several times while my app runs. I use the following code to do so:

NSString *dataPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data.txt"];
NSString *data = [NSString stringWithContentsOfFile:dataPath encoding:NSStringEncodingConversionExternalRepresentation error:NULL];
NSArray *components = [data componentsSeparatedByString:@"|||||"];

The first time this is called, it works as expected - I get an array of length 5, each section containing a relevant string.

What goes wrong:

This file is never modified. Yet, when I call the same procedure a second time (or third, fourth etc) I don't get the same result. Instead, an array of length 1 is returned, containing only part of the necessary data.

Why? I can't see any reason for this to go wrong... any help is much appreciated!


问:
Selenium with Java: Elements in a pop-up are not recognized
In www.jobserve.com, when you click "Apply" (apply to any of the job postings), you will get "Job Application " pop up.

How can I tell Selenium to read elements from this pop up? Currently none of the elements in the pop up is recognised by Selenium.

Lets say I want to Upload my CV, then how do I do it?

I have tried Switch to a frame, but it appears the pop up is not a frame so it didn't work.

答:
To Switch between iFrames we have to use the driver’s switchTo().frame command. We can use the switchTo().frame() in three ways:

switchTo.frame(int frameNumber): Pass the frame index and driver will switch to that frame.

switchTo.frame(string frameNameOrId): Pass the frame element Name or ID and driver will switch to that frame.

switchTo.frame(WebElement frameElement): Pass the frame web element and driver will switch to that frame.

```<code>    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.jobserve.com");

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(),'Job Search')]")));
    element.click();

    driver.findElement(By.xpath("/html/body/form/div[8]/div[1]/a/span")).click();

    driver.findElement(By.xpath("//*[@id=\"searchtogglelink\"]")).click();

    WebDriverWait wait1 = new WebDriverWait(driver, 10);
    WebElement element1 = wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"td_apply_btn\"]")));
    element1.click();
    Thread.sleep(2000);
    JavascriptExecutor exe = (JavascriptExecutor) driver;
    Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
    System.out.println("Number of iframes on the page are " + numberOfFrames);

    driver.switchTo().frame(0);

    WebElement Upload_File = driver.findElement(By.xpath("//input[@id='filCV']"));
    Upload_File.sendKeys("Path of file");
</code>```

Using switchTo().frame() you can switch to that frame and perform all actions on that opened frame.

There are two ways to find total number of iFrames in a web page. First by executing a JavaScript and second is by finding total number of web elements with a tag name of iFrame. Here is the code using both these methods:

```<code>//By executing a java script
JavascriptExecutor exe = (JavascriptExecutor) driver;
Integer numberOfFrames = Integer.parseInt(exe.executeScript("return
window.length").toString());
System.out.println("Number of iframes on the page are " + numberOfFrames);

//By finding all the web elements using iframe tag
List<WebElement> iframeElements = driver.findElements(By.tagName("iframe"));
System.out.println("The total number of iframes are " +
iframeElements.size());
</code>```

i)Switch to Frames by Index-
Index of an iFrame is the position at which it occurs in the HTML page.On this page only one frame is present.to switch to 0th iframe we can simple write driver.switchTo().frame(0).

```<code>//Switch by Index
 driver.switchTo().frame(0);
</code>```

ii)Switch to Frames by Name-
Name attribute has a value iframe1. We can switch to the iFrame using the name by using the command driver.switchTo().frame(“iframe1”).

```<code> //Switch by frame name
 driver.switchTo().frame("iframe1");
</code>```

iii)Switch to Frame by ID-
 iFrame tag we also have the ID attribute. We can use that also to switch to the frame. All we have to do is pass the id to the switchTo command like this driver.SwitchTo().frame(“IF1”).

```<code>//Switch by frame ID
driver.switchTo().frame("IF1");
</code>```

iv)Switch to Frame by WebElement-

Now we can switch to an iFrame by simply passing the iFrame WebElement to the driver.switchTo().frame() command. First find the iFrame element using any of the locator strategies and then passing it to switchTo command.

```<code>//First find the element using any of locator stratedgy
WebElement iframeElement = driver.findElement(By.id("IF1"));

//now use the switch command
driver.switchTo().frame(iframeElement);
</code>```

For more information go through this link.

Body:
To Switch between iFrames we have to use the driver’s switchTo().frame command. We can use the switchTo().frame() in three ways:

switchTo.frame(int frameNumber): Pass the frame index and driver will switch to that frame.

switchTo.frame(string frameNameOrId): Pass the frame element Name or ID and driver will switch to that frame.

switchTo.frame(WebElement frameElement): Pass the frame web element and driver will switch to that frame.

    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.jobserve.com");

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(),'Job Search')]")));
    element.click();

    driver.findElement(By.xpath("/html/body/form/div[8]/div[1]/a/span")).click();

    driver.findElement(By.xpath("//*[@id=\"searchtogglelink\"]")).click();

    WebDriverWait wait1 = new WebDriverWait(driver, 10);
    WebElement element1 = wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"td_apply_btn\"]")));
    element1.click();
    Thread.sleep(2000);
    JavascriptExecutor exe = (JavascriptExecutor) driver;
    Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
    System.out.println("Number of iframes on the page are " + numberOfFrames);

    driver.switchTo().frame(0);

    WebElement Upload_File = driver.findElement(By.xpath("//input[@id='filCV']"));
    Upload_File.sendKeys("Path of file");

Using switchTo().frame() you can switch to that frame and perform all actions on that opened frame.

There are two ways to find total number of iFrames in a web page. First by executing a JavaScript and second is by finding total number of web elements with a tag name of iFrame. Here is the code using both these methods:

//By executing a java script
JavascriptExecutor exe = (JavascriptExecutor) driver;
Integer numberOfFrames = Integer.parseInt(exe.executeScript("return
window.length").toString());
System.out.println("Number of iframes on the page are " + numberOfFrames);

//By finding all the web elements using iframe tag
List<WebElement> iframeElements = driver.findElements(By.tagName("iframe"));
System.out.println("The total number of iframes are " +
iframeElements.size());

i)Switch to Frames by Index-
Index of an iFrame is the position at which it occurs in the HTML page.On this page only one frame is present.to switch to 0th iframe we can simple write driver.switchTo().frame(0).

//Switch by Index
 driver.switchTo().frame(0);

ii)Switch to Frames by Name-
Name attribute has a value iframe1. We can switch to the iFrame using the name by using the command driver.switchTo().frame(“iframe1”).

 //Switch by frame name
 driver.switchTo().frame("iframe1");

iii)Switch to Frame by ID-
 iFrame tag we also have the ID attribute. We can use that also to switch to the frame. All we have to do is pass the id to the switchTo command like this driver.SwitchTo().frame(“IF1”).

//Switch by frame ID
driver.switchTo().frame("IF1");

iv)Switch to Frame by WebElement-

Now we can switch to an iFrame by simply passing the iFrame WebElement to the driver.switchTo().frame() command. First find the iFrame element using any of the locator strategies and then passing it to switchTo command.

//First find the element using any of locator stratedgy
WebElement iframeElement = driver.findElement(By.id("IF1"));

//now use the switch command
driver.switchTo().frame(iframeElement);

For more information go through this link.


问:
React WYSWYG like github comment
What is the easiest way to implement WYSWYG  in  react that can support formatting as what we have here on stackoverflow that we can easily format code blocks or even better as what we can see on medium site?</p>

答:
You can try Draft.js

Draft.js is a framework for building rich text editors in React, powered by an immutable model and abstracting over cross-browser differences.

Draft.js makes it easy to build any type of rich text input, whether you're just looking to support a few inline text styles or building a complex text editor for composing long-form articles.

Title: React WYSWYG like github comment


问:
i want to write looping dataframe to excel
1.I am new to python.this task for mainly read the excel files in directory and filter the data in excel. After filtering write into excel.When iam trying to write to excel its storing only last iteration values.Please give advise to write all data to excel . I want to write df_filter and df_filter1 to excel which is for loop .Please help me  i need to write these dataframe to excell

```<code>import os
import xlrd
import pandas as pd
import xlwt
from openpyxl import load_workbook
import xlsxwriter
from pyexcelerate import Workbook
import numpy as np
from pandas import ExcelWriter
from tempfile import TemporaryFile
ALL_SHEETS = []
sheet_list = ""
file_path = os.path.join(input("enter Dir path"))
config_path = os.path.join(input("enter your config file path here"))
output_path = os.path.join(input("Dude where you want store outputfile"))

output1 = pd.ExcelWriter(output_path, engine='xlsxwriter')

ALL_SHEETS = [os.path.join(file_path, f) for f in os.listdir(file_path)
              if os.path.isfile(os.path.join(file_path, f))
              and f.endswith('.xlsx')]

i = 0
data1 = []
data = []
Packet_size = []
Trail_numbers = []
Though_put = []
Latency = []
Jitter = []

df_filter  = pd.DataFrame(columns=['packetsize',  'throughput', 'latency (us)', 'jitter (us)'])
df_filter1  = pd.DataFrame(columns=['packetsize', 'throughput', 'latency (us)', 'jitter (us)'])
#df_sheet = pd.DataFrame(columns=['zsheet'])
merged_inner=pd.DataFrame([])

def sheets(val):

    s = wb.worksheets[val]
    df_sheet = pd.DataFrame( data=['%s' % str(s) + '\n'])
    #Name_sheet(s)

    HeaderList = pd.read_csv(config_path)

    column_list = []
    for col in HeaderList:
        col = col.lstrip("'")
        col = col.rstrip("'")
        column_list.append(col)

    df1 = xl.parse(sheet_list[val], skiprows=i)
    df1 = df1.filter(column_list)

    df2 = df1[(df1['Result'] != 'Failed') & (df1['Frame Size Type'] == 'iMIX')]

    if df2.empty:
        pass
    else:
        final3= df2.groupby(['Trial Number', 'iMIX Distribution'], sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])
        #df_filter['sheetaname']=df_sheet(lambda a:'%s' % a['sheetvise'],axis=1)
        final = final3.groupby(['iMIX Distribution'], sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])
        df_filter['packetsize'] = final.apply(lambda z: '%s' % (z['iMIX Distribution']), axis=1)

        df_filter['throughput'] = final.apply(lambda z: '%s' % (z['Throughput (%)']), axis=1)
        df_filter['latency (us)'] = final.apply(lambda x: '%s/%s/%s' % (x['Minimum Latency (us)'], x['Maximum Latency (us)'], x['Average Latency (us)']),axis=1)
        df_filter['jitter (us)'] = final.apply(lambda y: '%s/%s/%s' % (y['Minimum Jitter (us)'], y['Maximum Jitter (us)'], y['Average Jitter (us)']),axis=1)

        df_filter.to_excel(output1,sheet_name='mani')
        output1.save()
        df_filter.to_excel(output1, startrow=len(df_filter1)+len(df_filter)+2,sheet_name='mani')
        output1.save()

    df3 = df1[(df1['Result'] != 'Failed') & (df1['Frame Size Type'] == 'Fixed')]
    if df3.empty:
        pass
    else:
        final2 = df3.groupby(['Trial Number', 'Configured Frame Size'], sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])
        final1=final2.groupby(['Configured Frame Size'],sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])

        df_filter1['packetsize'] = final1.apply(lambda z: '%s' % (z['Configured Frame Size']), axis=1)

        df_filter1['throughput'] = final1.apply(lambda z: '%s' % (z['Throughput (%)']), axis=1)
        df_filter1['latency (us)'] = final1.apply(lambda x: '%s/%s/%s' % (x['Minimum Latency (us)'], x['Maximum Latency (us)'], x['Average Latency (us)']),axis=1)
        df_filter1['jitter (us)'] = final1.apply(lambda y: '%s/%s/%s' % (y['Minimum Jitter (us)'], y['Maximum Jitter (us)'], y['Average Jitter (us)']),axis=1)

        df_filter1.to_excel(output1, sheet_name='mani')

        df_filter1.to_excel(output1, startrow=len(df_filter1)+len(df_filter) + 2, sheet_name='mani')
        output1.save()
def sheet_every():

    for sheet in range(0, sheet_list_lenght):
        sheets(sheet)

for file in (ALL_SHEETS):

    df_file = pd.DataFrame(data=[file])

    workbook = xlrd.open_workbook(file)
    wb = load_workbook(file)

    xl = pd.ExcelFile(file)
    i = 0

    sheet_list = workbook.sheet_names()
    sheet_list_lenght = (len(sheet_list))
    for sheet in sheet_list:
        worksheet = workbook.sheet_by_name(sheet)

        for i in range(0, worksheet.nrows):
            row = worksheet.row_values(i)
            if 'Trial Number' in row:``

                break

    sheet_every()
</code>```

答:
If I get your question correctly, you have two data frames which you want to write to one excel file but you are only getting the last one.
You should write them to two different sheets instead, then you can retrieve them as per requirement, either individually or combined.
Follow the below links for more details and implementation :
https://xlsxwriter.readthedocs.io/example_pandas_multiple.html
https://campus.datacamp.com/courses/importing-managing-financial-data-in-python/importing-stock-listing-data-from-excel?ex=11

Also, you can instead write to a csv file, that is also excel compatible and easier to handle. Also I have observed that it is faster and more space efficient compared to writing to .xlsx file.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

Body:
1.I am new to python.this task for mainly read the excel files in directory and filter the data in excel. After filtering write into excel.When iam trying to write to excel its storing only last iteration values.Please give advise to write all data to excel . I want to write df_filter and df_filter1 to excel which is for loop .Please help me  i need to write these dataframe to excell

import os
import xlrd
import pandas as pd
import xlwt
from openpyxl import load_workbook
import xlsxwriter
from pyexcelerate import Workbook
import numpy as np
from pandas import ExcelWriter
from tempfile import TemporaryFile
ALL_SHEETS = []
sheet_list = ""
file_path = os.path.join(input("enter Dir path"))
config_path = os.path.join(input("enter your config file path here"))
output_path = os.path.join(input("Dude where you want store outputfile"))

output1 = pd.ExcelWriter(output_path, engine='xlsxwriter')

ALL_SHEETS = [os.path.join(file_path, f) for f in os.listdir(file_path)
              if os.path.isfile(os.path.join(file_path, f))
              and f.endswith('.xlsx')]

i = 0
data1 = []
data = []
Packet_size = []
Trail_numbers = []
Though_put = []
Latency = []
Jitter = []

df_filter  = pd.DataFrame(columns=['packetsize',  'throughput', 'latency (us)', 'jitter (us)'])
df_filter1  = pd.DataFrame(columns=['packetsize', 'throughput', 'latency (us)', 'jitter (us)'])
#df_sheet = pd.DataFrame(columns=['zsheet'])
merged_inner=pd.DataFrame([])

def sheets(val):

    s = wb.worksheets[val]
    df_sheet = pd.DataFrame( data=['%s' % str(s) + '\n'])
    #Name_sheet(s)

    HeaderList = pd.read_csv(config_path)

    column_list = []
    for col in HeaderList:
        col = col.lstrip("'")
        col = col.rstrip("'")
        column_list.append(col)

    df1 = xl.parse(sheet_list[val], skiprows=i)
    df1 = df1.filter(column_list)

    df2 = df1[(df1['Result'] != 'Failed') & (df1['Frame Size Type'] == 'iMIX')]

    if df2.empty:
        pass
    else:
        final3= df2.groupby(['Trial Number', 'iMIX Distribution'], sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])
        #df_filter['sheetaname']=df_sheet(lambda a:'%s' % a['sheetvise'],axis=1)
        final = final3.groupby(['iMIX Distribution'], sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])
        df_filter['packetsize'] = final.apply(lambda z: '%s' % (z['iMIX Distribution']), axis=1)

        df_filter['throughput'] = final.apply(lambda z: '%s' % (z['Throughput (%)']), axis=1)
        df_filter['latency (us)'] = final.apply(lambda x: '%s/%s/%s' % (x['Minimum Latency (us)'], x['Maximum Latency (us)'], x['Average Latency (us)']),axis=1)
        df_filter['jitter (us)'] = final.apply(lambda y: '%s/%s/%s' % (y['Minimum Jitter (us)'], y['Maximum Jitter (us)'], y['Average Jitter (us)']),axis=1)

        df_filter.to_excel(output1,sheet_name='mani')
        output1.save()
        df_filter.to_excel(output1, startrow=len(df_filter1)+len(df_filter)+2,sheet_name='mani')
        output1.save()

    df3 = df1[(df1['Result'] != 'Failed') & (df1['Frame Size Type'] == 'Fixed')]
    if df3.empty:
        pass
    else:
        final2 = df3.groupby(['Trial Number', 'Configured Frame Size'], sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])
        final1=final2.groupby(['Configured Frame Size'],sort=False).apply(lambda x: x.loc[x['Throughput (%)'].idxmax()])

        df_filter1['packetsize'] = final1.apply(lambda z: '%s' % (z['Configured Frame Size']), axis=1)

        df_filter1['throughput'] = final1.apply(lambda z: '%s' % (z['Throughput (%)']), axis=1)
        df_filter1['latency (us)'] = final1.apply(lambda x: '%s/%s/%s' % (x['Minimum Latency (us)'], x['Maximum Latency (us)'], x['Average Latency (us)']),axis=1)
        df_filter1['jitter (us)'] = final1.apply(lambda y: '%s/%s/%s' % (y['Minimum Jitter (us)'], y['Maximum Jitter (us)'], y['Average Jitter (us)']),axis=1)

        df_filter1.to_excel(output1, sheet_name='mani')

        df_filter1.to_excel(output1, startrow=len(df_filter1)+len(df_filter) + 2, sheet_name='mani')
        output1.save()
def sheet_every():

    for sheet in range(0, sheet_list_lenght):
        sheets(sheet)

for file in (ALL_SHEETS):

    df_file = pd.DataFrame(data=[file])

    workbook = xlrd.open_workbook(file)
    wb = load_workbook(file)

    xl = pd.ExcelFile(file)
    i = 0

    sheet_list = workbook.sheet_names()
    sheet_list_lenght = (len(sheet_list))
    for sheet in sheet_list:
        worksheet = workbook.sheet_by_name(sheet)

        for i in range(0, worksheet.nrows):
            row = worksheet.row_values(i)
            if 'Trial Number' in row:``

                break

    sheet_every()


问:
Google Play Games login fails
When I try to let the user sign in into Google+ via Google Game Services (using the GameHelper class), the login fails with this log-message:

```<code>05-16 17:34:44.620: ERROR/Volley(26441): [2299] il.a: Unexpected response code 400 for https://www.googleapis.com/games/v1whitelisted/applications?language=en_GB&platformType=ANDROID
05-16 17:34:44.620: ERROR/GameAgent(26441): Unable to retrieve 1P application xxxxxxxxxxxxxx.apps.googleusercontent.com from network
05-16 17:34:44.625: INFO/GameAgent(26441): {"code":400,"errors":[{"message":"Invalid applicationId with value xxxxxxxxxxxxxxxx.apps.googleusercontent.com","domain":"global","reason":"invalid"}]}
05-16 17:34:44.645: ERROR/CheckGameplayAcl(27604): Unable to load metadata for game
</code>```

I've added all the metadata etc. correctly to my app and to the developer console, so it should work.

答: in my case: enable in firebase Google authentification method., it's work for me</p>

Title: Google Play Games login fails

Body:
When I try to let the user sign in into Google+ via Google Game Services (using the GameHelper class), the login fails with this log-message:

05-16 17:34:44.620: ERROR/Volley(26441): [2299] il.a: Unexpected response code 400 for https://www.googleapis.com/games/v1whitelisted/applications?language=en_GB&platformType=ANDROID
05-16 17:34:44.620: ERROR/GameAgent(26441): Unable to retrieve 1P application xxxxxxxxxxxxxx.apps.googleusercontent.com from network
05-16 17:34:44.625: INFO/GameAgent(26441): {"code":400,"errors":[{"message":"Invalid applicationId with value xxxxxxxxxxxxxxxx.apps.googleusercontent.com","domain":"global","reason":"invalid"}]}
05-16 17:34:44.645: ERROR/CheckGameplayAcl(27604): Unable to load metadata for game

I've added all the metadata etc. correctly to my app and to the developer console, so it should work.