问:
JLabel clear text
I am in the process of writing a program which pings a server and returns a value.

I have been trying to overlay the ping to a JFrame, where a JLabel displays the ping in a transparent window.

However, every time I call the method DrawOverlay(), the JLabel simply redraws on top of the previously drawn label.

For context, DrawOverlay() is called from another class, PingTest.

```<code>void DrawOverlay(String ping)
{
    JLabel lbl_ping = new JLabel(ping);
    lbl_ping.removeAll();//attempts at clearing the previously drawn label
    lbl_ping.revalidate();
    lbl_ping.repaint();

    if (!frame.isUndecorated())
    {
        frame.setUndecorated(true);
    }

    frame.setFocusableWindowState(false);
    frame.setBackground(new Color(0, 0, 0, 0));
    frame.setAlwaysOnTop(true);
    frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", false);
    frame.getContentPane().setLayout(new java.awt.BorderLayout());
    lbl_ping.setFont(new Font("serif", Font.PLAIN, 48));
    lbl_ping.setForeground(Color.WHITE);
    lbl_ping.setText(ping);
    frame.add(lbl_ping);
    frame.setVisible(true);
    frame.pack();
}
</code>```

Is there any way to redraw a JFrame or JLabel to remove the previous data?

答:
Each time you call DrawOverlay you create a new JLabel:

```<code>JLabel lbl_ping = new JLabel(ping);
</code>```

After setting the properties you call frame.add(lbl_ping); which adds your new JLabel to your JFrame.

You're JLabel does not get overwritten or removed.

What you want to do is declare JLabel lbl_ping; as a private member in your class and then when creating your JFrame you want to also initialize your JLabel and set all those properties:

```<code>lbl_ping = new JLabel();

frame.setFocusableWindowState(false);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setAlwaysOnTop(true);
frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", false);
frame.getContentPane().setLayout(new java.awt.BorderLayout());
lbl_ping.setFont(new Font("serif", Font.PLAIN, 48));
lbl_ping.setForeground(Color.WHITE);
lbl_ping.setText(ping);
frame.add(lbl_ping);

// pack() first then setVisible()
frame.pack();
frame.setVisible(true);
</code>```

Have a look at this. It explains what pack() does.

Then in DrawOverlay you simply set the text value and update your JFrame:

```<code>void DrawOverlay(String ping)
{
    lbl_ping.setText(ping);
    frame.getContentPane().validate(); // You modified child component lbl_ping (changed its size by setting a new text) so you need to recalculate all the child components
    frame.getContentPane().repaint(); // Redraws the content pane and all of its children
}
</code>```

Title: JLabel clear text

Body:
I am in the process of writing a program which pings a server and returns a value.

I have been trying to overlay the ping to a JFrame, where a JLabel displays the ping in a transparent window.

However, every time I call the method DrawOverlay(), the JLabel simply redraws on top of the previously drawn label.

For context, DrawOverlay() is called from another class, PingTest.

void DrawOverlay(String ping)
{
    JLabel lbl_ping = new JLabel(ping);
    lbl_ping.removeAll();//attempts at clearing the previously drawn label
    lbl_ping.revalidate();
    lbl_ping.repaint();

    if (!frame.isUndecorated())
    {
        frame.setUndecorated(true);
    }

    frame.setFocusableWindowState(false);
    frame.setBackground(new Color(0, 0, 0, 0));
    frame.setAlwaysOnTop(true);
    frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", false);
    frame.getContentPane().setLayout(new java.awt.BorderLayout());
    lbl_ping.setFont(new Font("serif", Font.PLAIN, 48));
    lbl_ping.setForeground(Color.WHITE);
    lbl_ping.setText(ping);
    frame.add(lbl_ping);
    frame.setVisible(true);
    frame.pack();
}

Is there any way to redraw a JFrame or JLabel to remove the previous data?

Body:
Each time you call DrawOverlay you create a new JLabel:

JLabel lbl_ping = new JLabel(ping);

After setting the properties you call frame.add(lbl_ping); which adds your new JLabel to your JFrame.

You're JLabel does not get overwritten or removed.

What you want to do is declare JLabel lbl_ping; as a private member in your class and then when creating your JFrame you want to also initialize your JLabel and set all those properties:

lbl_ping = new JLabel();

frame.setFocusableWindowState(false);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setAlwaysOnTop(true);
frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", false);
frame.getContentPane().setLayout(new java.awt.BorderLayout());
lbl_ping.setFont(new Font("serif", Font.PLAIN, 48));
lbl_ping.setForeground(Color.WHITE);
lbl_ping.setText(ping);
frame.add(lbl_ping);

// pack() first then setVisible()
frame.pack();
frame.setVisible(true);

Have a look at this. It explains what pack() does.

Then in DrawOverlay you simply set the text value and update your JFrame:

void DrawOverlay(String ping)
{
    lbl_ping.setText(ping);
    frame.getContentPane().validate(); // You modified child component lbl_ping (changed its size by setting a new text) so you need to recalculate all the child components
    frame.getContentPane().repaint(); // Redraws the content pane and all of its children
}


来源: stackexchange

问:
PHP HTML table retrieve multiple data in one  tag
I'm trying to generate a list from database in a HTML table just like image below;

https://i.stack.imgur.com/61XLl.png

And here's what i did;

https://i.stack.imgur.com/lLsvF.png

And the code;

```<code>    <table cellpadding="3" border="1"  style="width:100%;margin-top:30px; margin-bottom:50px; font-size:12px">
    <thead>
        <tr>
            <th>KURSUS</th>
            <th rowspan="2">NAMA PENSYARAH</th>
            <th rowspan="2">NO. SIRI</th>
        </tr>
        <tr>
            <th>NAMA</th>
        </tr>
    </thead>
    <tbody align="center">
        <?php
            if($numrow>0)
            {
                while($row = $select->fetch_assoc()){

                    $code=explode("/",$row['po_code']);
                    $list=$connect->query("SELECT * FROM polist WHERE polist_poid='".$row['po_id']."' ORDER BY polist_bil ASC");
                    ?>

        <tr>
            <td><?php echo $row['po_name']; ?></td>
            <?php while($rowlist = $list->fetch_assoc()){

                    $name=$connect->query("SELECT * FROM user WHERE user_id='".$rowlist['polist_userid']."'");
                    $rowname=$name->fetch_array();?>
            <td><?php echo $rowname['user_name']; ?></td>
            <td><?php echo $code[0]."/PO/".$code[1]." - ".$rowlist['polist_bil']; ?></td>
            <?php } ?>
        </tr>

                    <?php
                }
            }
        ?>
    </tbody>
</table>
</code>```

Help me. Thank you in advance :)

答:
Use this code. Concat user names and code with "br" tags in the second while loop and display them in "tds" after while loop. </p>

```<code><tbody align="center">
        <?php
            if($numrow>0)
            {
                while($row = $select->fetch_assoc()){

                    $code=explode("/",$row['po_code']);
                    $list=$connect->query("SELECT * FROM polist WHERE polist_poid='".$row['po_id']."' ORDER BY polist_bil ASC");
                    ?>

        <tr>
            <td><?php echo $row['po_name']; ?></td>
            <?php
                $user_names = $codes = '';  // define empty variables
                while($rowlist = $list->fetch_assoc()){

                    $name=$connect->query("SELECT * FROM user WHERE user_id='".$rowlist['polist_userid']."'");
                    $rowname=$name->fetch_array();
                    $user_names .= $rowname['user_name']."<br/>"; //concat to a single string
                    $codes .= $code[0]."/PO/".$code[1]." - ".$rowlist['polist_bil']."<br/>"; //concat to a single string
            }?>
            <td><?php echo $user_names;?></td>
            <td><?php echo $codes;?></td>
        </tr>

                    <?php
                }
            }
        ?>
    </tbody>
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP HTML table retrieve multiple data in one <td> tag

Body:
I'm trying to generate a list from database in a HTML table just like image below;

https://i.stack.imgur.com/61XLl.png

And here's what i did;

https://i.stack.imgur.com/lLsvF.png

And the code;

            KURSUS
            NAMA PENSYARAH
            NO. SIRI

            NAMA

        <?php
            if($numrow>0)
            {
                while($row = $select->fetch_assoc()){

                    $code=explode("/",$row['po_code']);
                    $list=$connect->query("SELECT * FROM polist WHERE polist_poid='".$row['po_id']."' ORDER BY polist_bil ASC");
                    ?>

            <?php echo $row['po_name']; ?>
            <?php while($rowlist = $list->fetch_assoc()){

                    $name=$connect->query("SELECT * FROM user WHERE user_id='".$rowlist['polist_userid']."'");
                    $rowname=$name->fetch_array();?>
            <?php echo $rowname['user_name']; ?>
            <?php echo $code[0]."/PO/".$code[1]." - ".$rowlist['polist_bil']; ?>
            <?php } ?>

                    <?php
                }
            }
        ?>

Help me. Thank you in advance :)

Body:
Use this code. Concat user names and code with "br" tags in the second while loop and display them in "tds" after while loop.

<tbody align="center">
        <?php
            if($numrow>0)
            {
                while($row = $select->fetch_assoc()){

                    $code=explode("/",$row['po_code']);
                    $list=$connect->query("SELECT * FROM polist WHERE polist_poid='".$row['po_id']."' ORDER BY polist_bil ASC");
                    ?>

        <tr>
            <td><?php echo $row['po_name']; ?></td>
            <?php
                $user_names = $codes = '';  // define empty variables
                while($rowlist = $list->fetch_assoc()){

                    $name=$connect->query("SELECT * FROM user WHERE user_id='".$rowlist['polist_userid']."'");
                    $rowname=$name->fetch_array();
                    $user_names .= $rowname['user_name']."<br/>"; //concat to a single string
                    $codes .= $code[0]."/PO/".$code[1]." - ".$rowlist['polist_bil']."<br/>"; //concat to a single string
            }?>
            <td><?php echo $user_names;?></td>
            <td><?php echo $codes;?></td>
        </tr>

                    <?php
                }
            }
        ?>
    </tbody>


问:
Add disjunctive tag refinement in Algolia JS Helper
I'm trying to do a disjunctive filter by tags in Algolia but there's no documentation about it. This is what i'm doing actually:

```<code>helper.addTag('Shangai').search();
</code>```

That will filter all the documents that have the Shangai tag.
But i need to get also all the documents that have the Brooklyn tag.

```<code>helper.addTag('Brooklyn').search();
</code>```

After doing that i get 0 results because algolia is using the AND operator as default to search in tags, so is looking for documents that have Shangai AND Brooklyn. What i need Shangai OR Brooklyn.

Anyone knows how to do it?

答:
To achieve your goal you can use the setQueryParameter method.

```<code>helper.setQueryParameter('filters', 'Shangai OR Brooklyn').search();
</code>```

Also I would recommend you enclose your tag values between double quotes in case they contain spaces.

```<code>helper.setQueryParameter('filters', '"Shangai" OR "Brooklyn"').search();
</code>```

Note that setQueryParameter supports all documented Algolia search query parameters.

Body:
I'm trying to do a disjunctive filter by tags in Algolia but there's no documentation about it. This is what i'm doing actually:

helper.addTag('Shangai').search();

That will filter all the documents that have the Shangai tag.
But i need to get also all the documents that have the Brooklyn tag.

helper.addTag('Brooklyn').search();

After doing that i get 0 results because algolia is using the AND operator as default to search in tags, so is looking for documents that have Shangai AND Brooklyn. What i need Shangai OR Brooklyn.

Anyone knows how to do it?

Body:
To achieve your goal you can use the setQueryParameter method.

helper.setQueryParameter('filters', 'Shangai OR Brooklyn').search();

Also I would recommend you enclose your tag values between double quotes in case they contain spaces.

helper.setQueryParameter('filters', '"Shangai" OR "Brooklyn"').search();

Note that setQueryParameter supports all documented Algolia search query parameters.


问:
React Native initial database
I want to develop a React Native app, and I want to have locally stored some data of the format:

```<code>[
  {
    "id": 1,
    "text": "Lorem ipsum",
    "viewed": false
  },
  {
    "id": 2,
    "text": "Second lorem",
    "viewed": false
  },
  {
    "id": 3,
    "text": "Last lorem",
    "viewed": false
  }
]
</code>```

I want this data to be available when the user first downloads the app. Then based on the user's navigation, the corresponding data in the db will change the viewed flag to true. This has to be persistent when the app will be updated by the user on the next version.

Any tips/ideas on how to achieve this?

Currently I'm looking into Realm.io but I'm not sure if this is the right tool for me.

答:
If data is more than pouchDb is suggested option.

You can install it with

```<code>npm install pouchdb-react-native --save
</code>```

Simple Demo

```<code>import PouchDB from 'pouchdb-react-native'
const db = new PouchDB('mydb')

// use PouchDB
db.get('4711')
  .then(doc => console.log(doc))
</code>```

Advance Demo

```<code>'use strict'

import React from 'react'
import {
  AsyncStorage,
  ListView,
  Navigator,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View
} from 'react-native'

import ActionButton from 'react-native-action-button'
import PouchDB from 'pouchdb-react-native'

const localDB = new PouchDB('myDB')
console.log(localDB.adapter)

AsyncStorage.getAllKeys()
  .then(keys => AsyncStorage.multiGet(keys))
  .then(items => console.log('all pure Items', items))
  .catch(error => console.warn('error get all Items', error))

export default React.createClass({
  getInitialState () {
    const updateDocs = () => {
  localDB.allDocs({include_docs: true, limit: null})
    .then(result => {
      const items = result.rows.map(row => row.doc)
      const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id})
      this.setState({
        dataSource: ds.cloneWithRows(items),
        count: items.length
      })
    })
    .catch(error => console.warn('Could not load Documents', error, error.message))
}

localDB.changes({since: 'now', live: true})
  .on('change', () => updateDocs())

updateDocs()

return {
  dataSource: null,
  syncUrl: 'http://localhost:5984/test'
}
  },
  render () {
const renderScene = (route, navigator) => (
  <View style={{flex: 1, marginTop: 20, backgroundColor: '#FFFFFF'}}>
    {route.render()}
  </View>
)

const renderMain = () => {
  const insertAttachment = () => {
    const doc = {
      'title': 'with attachment',
      '_attachments': {
        'att.txt': {
          'content_type': 'text/plain',
          'data': 'TGVnZW5kYXJ5IGhlYXJ0cywgdGVhciB1cyBhbGwgYXBhcnQKTWFrZS' +
                  'BvdXIgZW1vdGlvbnMgYmxlZWQsIGNyeWluZyBvdXQgaW4gbmVlZA=='
        }
      }
    }

    localDB.post(doc)
      .then(result => console.log('save.attachment', result))
      .catch(error => console.warn('save.attachment.error', error, error.message, error.stack))
  }

  const insertRecords = count => {
    for (let index = 0; index < count; index++) {
      localDB.post({
        text: `Record ${index}/${count}`
      })
    }
  }

  const destroy = count => {
    localDB.destroy()
      .then(() => console.log('destroyed'))
      .catch(error => console.warn('destroyed', error))
  }

  const { dataSource } = this.state

  const renderSeparator = (sectionID, rowID) => (
    <View
      key={rowID}
      style={{borderColor: '#969A99', borderBottomWidth: StyleSheet.hairlineWidth}} />
  )

  const renderRow = (row) => {
    const updateItem = () => {
      const newRow = {...row}
      newRow.clickCount = newRow.clickCount ? newRow.clickCount + 1 : 1

      localDB.put(newRow)
        .then(result => console.log('Updated Item', result))
        .catch(error => console.warn('Error during update Item', error))
    }

    return (
      <TouchableHighlight onPress={updateItem}>
        <View key={row._id}>
          <Text style={{fontWeight: 'bold'}}>{row._id}</Text>
          <Text>{JSON.stringify(row, null, 4)}</Text>
        </View>
      </TouchableHighlight>
    )
  }

  const renderList = () => (
    <ListView
      dataSource={dataSource}
      renderRow={renderRow}
      renderSeparator={renderSeparator}
      enableEmptySections />
  )

  return (
    <View style={{flex: 1}}>
      <View>
        {!!this._sync && <Text style={{fontWeight: 'bold'}}>{this.state.syncUrl}</Text>}
        <Text style={{fontWeight: 'bold'}}>Count: {this.state.count}</Text>
      </View>
      <View
        style={{borderColor: '#969A99', borderBottomWidth: StyleSheet.hairlineWidth}} />
      {!dataSource
        ? (<Text>Loading...</Text>)
        : renderList()
      }
      <ActionButton buttonColor='#78B55E'>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Destroy Database'
          onPress={destroy}>
          <Text>destroy</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Insert Attachments'
          onPress={insertAttachment}>
          <Text>attach</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Insert 250 Records'
          onPress={() => insertRecords(250)}>
          <Text>insert</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Sync'
          onPress={() => this._navigator.push({name: 'Sync', render: renderSync})}>
          <Text>sync</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Add Item'
          onPress={() => this._navigator.push({name: 'AddItem', render: renderAddItem})}>
          <Text>+</Text>
        </ActionButton.Item>
      </ActionButton>
    </View>
  )
}

const renderButton = (text, onPress) => {
  return (
    <TouchableHighlight
      onPress={onPress}
      style={{
        flexDirection: 'column',
        paddingTop: 3,
        paddingBottom: 3,
        marginLeft: 10,
        marginRight: 10,
        backgroundColor: '#78B55E',
        borderRadius: 5
      }}>
      <Text
        style={{
          flex: 1,
          fontSize: 18,
          fontWeight: 'bold',
          color: '#FFFFFF',
          paddingLeft: 10,
          paddingRight: 10,
          paddingTop: 2,
          alignSelf: 'center'
        }}>
        {text}
      </Text>
    </TouchableHighlight>
  )
}

const renderSync = () => {
  const addSync = () => {
    if (this._sync) {
      this._sync.cancel()
      this._sync = null
    }

    if (this.state.syncUrl) {
      const remoteDb = new PouchDB(this.state.syncUrl, {ajax: {cache: false}})
      this._sync = PouchDB.sync(localDB, remoteDb, {live: true, retry: true})
        .on('error', error => console.error('Sync Error', error))
        .on('change', info => console.log('Sync change', info))
        .on('paused', info => console.log('Sync paused', info))
    }

    this._navigator.pop()
  }

  return (
    <View style={{flex: 1}}>
      <TextInput
        style={{
          height: 40,
          lineHeight: 40,
          fontSize: 16,
          paddingLeft: 10,
          paddingRight: 10
        }}
        autoFocus
        keyboardType='url'
        clearButtonMode='always'
        placeholder='enter URL'
        onChangeText={(text) => this.setState({syncUrl: text})}
        value={this.state.syncUrl} />
      {renderButton('Add Sync', addSync)}
    </View>
  )
}

const renderAddItem = () => {
  const addItem = () => {
    localDB.post(JSON.parse(this.state.newItem))
      .then(result => {
        this.setState({newItem: ''})
        this._navigator.pop()
      })
      .catch(error => console.error('Error during create Item', error, error.message))
  }

  return (
    <View style={{flex: 1}}>
      <TextInput
        style={{
          height: 340,
          lineHeight: 40,
          fontSize: 16,
          paddingLeft: 10,
          paddingRight: 10
        }}
        autoFocus
        clearButtonMode='always'
        multiline
        placeholder='JSON Object here'
        onChangeText={(text) => this.setState({newItem: text})}
        value={this.state.newItem} />
      {renderButton('Add Item', addItem)}
    </View>
  )
}

return (
  <View style={{flex: 1}}>
    <Navigator
      ref={navigator => { this._navigator = navigator }}
      renderScene={renderScene}
      initialRoute={{name: 'Main', render: renderMain}}
    />
  </View>
)
  }
})
</code>```

Title: React Native initial database

Body:
I want to develop a React Native app, and I want to have locally stored some data of the format:

[
  {
    "id": 1,
    "text": "Lorem ipsum",
    "viewed": false
  },
  {
    "id": 2,
    "text": "Second lorem",
    "viewed": false
  },
  {
    "id": 3,
    "text": "Last lorem",
    "viewed": false
  }
]

I want this data to be available when the user first downloads the app. Then based on the user's navigation, the corresponding data in the db will change the viewed flag to true. This has to be persistent when the app will be updated by the user on the next version.

Any tips/ideas on how to achieve this?

Currently I'm looking into Realm.io but I'm not sure if this is the right tool for me.

Body:
If data is more than pouchDb is suggested option.

You can install it with

npm install pouchdb-react-native --save

Simple Demo

import PouchDB from 'pouchdb-react-native'
const db = new PouchDB('mydb')

// use PouchDB
db.get('4711')
  .then(doc => console.log(doc))

Advance Demo

'use strict'

import React from 'react'
import {
  AsyncStorage,
  ListView,
  Navigator,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View
} from 'react-native'

import ActionButton from 'react-native-action-button'
import PouchDB from 'pouchdb-react-native'

const localDB = new PouchDB('myDB')
console.log(localDB.adapter)

AsyncStorage.getAllKeys()
  .then(keys => AsyncStorage.multiGet(keys))
  .then(items => console.log('all pure Items', items))
  .catch(error => console.warn('error get all Items', error))

export default React.createClass({
  getInitialState () {
    const updateDocs = () => {
  localDB.allDocs({include_docs: true, limit: null})
    .then(result => {
      const items = result.rows.map(row => row.doc)
      const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id})
      this.setState({
        dataSource: ds.cloneWithRows(items),
        count: items.length
      })
    })
    .catch(error => console.warn('Could not load Documents', error, error.message))
}

localDB.changes({since: 'now', live: true})
  .on('change', () => updateDocs())

updateDocs()

return {
  dataSource: null,
  syncUrl: 'http://localhost:5984/test'
}
  },
  render () {
const renderScene = (route, navigator) => (
  <View style={{flex: 1, marginTop: 20, backgroundColor: '#FFFFFF'}}>
    {route.render()}
  </View>
)

const renderMain = () => {
  const insertAttachment = () => {
    const doc = {
      'title': 'with attachment',
      '_attachments': {
        'att.txt': {
          'content_type': 'text/plain',
          'data': 'TGVnZW5kYXJ5IGhlYXJ0cywgdGVhciB1cyBhbGwgYXBhcnQKTWFrZS' +
                  'BvdXIgZW1vdGlvbnMgYmxlZWQsIGNyeWluZyBvdXQgaW4gbmVlZA=='
        }
      }
    }

    localDB.post(doc)
      .then(result => console.log('save.attachment', result))
      .catch(error => console.warn('save.attachment.error', error, error.message, error.stack))
  }

  const insertRecords = count => {
    for (let index = 0; index < count; index++) {
      localDB.post({
        text: `Record ${index}/${count}`
      })
    }
  }

  const destroy = count => {
    localDB.destroy()
      .then(() => console.log('destroyed'))
      .catch(error => console.warn('destroyed', error))
  }

  const { dataSource } = this.state

  const renderSeparator = (sectionID, rowID) => (
    <View
      key={rowID}
      style={{borderColor: '#969A99', borderBottomWidth: StyleSheet.hairlineWidth}} />
  )

  const renderRow = (row) => {
    const updateItem = () => {
      const newRow = {...row}
      newRow.clickCount = newRow.clickCount ? newRow.clickCount + 1 : 1

      localDB.put(newRow)
        .then(result => console.log('Updated Item', result))
        .catch(error => console.warn('Error during update Item', error))
    }

    return (
      <TouchableHighlight onPress={updateItem}>
        <View key={row._id}>
          <Text style={{fontWeight: 'bold'}}>{row._id}</Text>
          <Text>{JSON.stringify(row, null, 4)}</Text>
        </View>
      </TouchableHighlight>
    )
  }

  const renderList = () => (
    <ListView
      dataSource={dataSource}
      renderRow={renderRow}
      renderSeparator={renderSeparator}
      enableEmptySections />
  )

  return (
    <View style={{flex: 1}}>
      <View>
        {!!this._sync && <Text style={{fontWeight: 'bold'}}>{this.state.syncUrl}</Text>}
        <Text style={{fontWeight: 'bold'}}>Count: {this.state.count}</Text>
      </View>
      <View
        style={{borderColor: '#969A99', borderBottomWidth: StyleSheet.hairlineWidth}} />
      {!dataSource
        ? (<Text>Loading...</Text>)
        : renderList()
      }
      <ActionButton buttonColor='#78B55E'>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Destroy Database'
          onPress={destroy}>
          <Text>destroy</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Insert Attachments'
          onPress={insertAttachment}>
          <Text>attach</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Insert 250 Records'
          onPress={() => insertRecords(250)}>
          <Text>insert</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Sync'
          onPress={() => this._navigator.push({name: 'Sync', render: renderSync})}>
          <Text>sync</Text>
        </ActionButton.Item>
        <ActionButton.Item
          buttonColor='#005BFF'
          title='Add Item'
          onPress={() => this._navigator.push({name: 'AddItem', render: renderAddItem})}>
          <Text>+</Text>
        </ActionButton.Item>
      </ActionButton>
    </View>
  )
}

const renderButton = (text, onPress) => {
  return (
    <TouchableHighlight
      onPress={onPress}
      style={{
        flexDirection: 'column',
        paddingTop: 3,
        paddingBottom: 3,
        marginLeft: 10,
        marginRight: 10,
        backgroundColor: '#78B55E',
        borderRadius: 5
      }}>
      <Text
        style={{
          flex: 1,
          fontSize: 18,
          fontWeight: 'bold',
          color: '#FFFFFF',
          paddingLeft: 10,
          paddingRight: 10,
          paddingTop: 2,
          alignSelf: 'center'
        }}>
        {text}
      </Text>
    </TouchableHighlight>
  )
}

const renderSync = () => {
  const addSync = () => {
    if (this._sync) {
      this._sync.cancel()
      this._sync = null
    }

    if (this.state.syncUrl) {
      const remoteDb = new PouchDB(this.state.syncUrl, {ajax: {cache: false}})
      this._sync = PouchDB.sync(localDB, remoteDb, {live: true, retry: true})
        .on('error', error => console.error('Sync Error', error))
        .on('change', info => console.log('Sync change', info))
        .on('paused', info => console.log('Sync paused', info))
    }

    this._navigator.pop()
  }

  return (
    <View style={{flex: 1}}>
      <TextInput
        style={{
          height: 40,
          lineHeight: 40,
          fontSize: 16,
          paddingLeft: 10,
          paddingRight: 10
        }}
        autoFocus
        keyboardType='url'
        clearButtonMode='always'
        placeholder='enter URL'
        onChangeText={(text) => this.setState({syncUrl: text})}
        value={this.state.syncUrl} />
      {renderButton('Add Sync', addSync)}
    </View>
  )
}

const renderAddItem = () => {
  const addItem = () => {
    localDB.post(JSON.parse(this.state.newItem))
      .then(result => {
        this.setState({newItem: ''})
        this._navigator.pop()
      })
      .catch(error => console.error('Error during create Item', error, error.message))
  }

  return (
    <View style={{flex: 1}}>
      <TextInput
        style={{
          height: 340,
          lineHeight: 40,
          fontSize: 16,
          paddingLeft: 10,
          paddingRight: 10
        }}
        autoFocus
        clearButtonMode='always'
        multiline
        placeholder='JSON Object here'
        onChangeText={(text) => this.setState({newItem: text})}
        value={this.state.newItem} />
      {renderButton('Add Item', addItem)}
    </View>
  )
}

return (
  <View style={{flex: 1}}>
    <Navigator
      ref={navigator => { this._navigator = navigator }}
      renderScene={renderScene}
      initialRoute={{name: 'Main', render: renderMain}}
    />
  </View>
)
  }
})


问:
Restricting a Counter Collection in Python
I am currently extracting data from a web API and I am trying to filter some values based on the following condition: Count the number of times that a user appears between two given dates but only if he/she has bought items raspberry pi, banana pi and raspberry pi2 and not item raspberry pi3

The JSON object that I receive has the following structure:

```<code>[{
user_id : 0001
CreatedOn: "2017-02-16 15:54:48",
item: "raspbery pi",
VIP: "YES",
Vendor_CODE: "XYZ12345",
},
{
user_id : 0001
CreatedOn: "2017-02-15 13:49:16",
item: "raspbery pi2",
VIP: "YES",
Vendor_CODE: "XYZ67890",
},
{
user_id : 0001
CreatedOn: "2017-02-10 15:54:48",
item: "raspbery pi",
VIP: "YES",
Vendor_CODE: "RST171820",
},
{
user_id : 0001
CreatedOn: "2017-01-01 21:51:13",
item: "raspbery pi3",
VIP: "YES",
Vendor_CODE: "XOL002321",
},
{
user_id : 0005
CreatedOn: "2017-01-30 17:34:18",
item: "raspbery pi",
VIP: "YES",
Vendor_CODE: "RST171820",
},
{
user_id : 0005
CreatedOn: "2017-05-30 09:04:08",
item: "banana pi",
VIP: "YES",
Vendor_CODE: "ITI342027",
}]
</code>```

Currently I have the following code that counts the number of times a user appears given two dates.

```<code>from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from collections import Counter
from datetime import datetime, timedelta
import json, urllib.request, dateutil.parser, urllib.parse,

#Request a response to the Web API
def get_data(request, *args, **kwargs):
    # YYYY-MM-DD
    start_date = datetime.now() - timedelta(days=7)
    end_date = datetime.now() - timedelta(days=1)

    with urllib.request.urlopen("http://10.61.202.98:8081/T/ansdb/api/rows/dev/ect",timeout=15) as url:
    response_data = json.loads(url.read().decode())

    #count the number of times the user appears when he bought the 4 items in two given dates
    count_user_01 = Counter([k['user_id'] for k in response_data if
         start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week])
</code>```

My approach is to add some extra "condition" to count all items except the item raspberry pi3, something like:

```<code>count_user_01 = Counter([k['user_id'] for k in response_data if
     start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week] and k['item']!='raspberry pi3')
</code>```

but if I do this then I encounter the error bool object is not iterable and I assume I receive this error because the collection Counter does not allow me to do this.

My questions are:

How can I implement this extra condition into the list so I can count all the items except raspberry pi3 that were bought by one user?

Currently, I am counting the items that were bought for specific users but how could I count all the items that were bought by all the users?

All comments, answers and suggestions are welcome.

Update

For question 1 the solution was to fix the problem in brackets.

```<code>count_user_01 = Counter([k['user_id'] for k in response_data if
 start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week and k['item']!='raspberry pi3'])
</code>```

答:
I think you have a problem with your brackets. Try this:</p>

```<code>count_user_01 = Counter([k['user_id'] for k in response_data if
     start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week and k['item']!='raspberry pi3'])
</code>```

Body:
I am currently extracting data from a web API and I am trying to filter some values based on the following condition: Count the number of times that a user appears between two given dates but only if he/she has bought items raspberry pi, banana pi and raspberry pi2 and not item raspberry pi3

The JSON object that I receive has the following structure:

[{
user_id : 0001
CreatedOn: "2017-02-16 15:54:48",
item: "raspbery pi",
VIP: "YES",
Vendor_CODE: "XYZ12345",
},
{
user_id : 0001
CreatedOn: "2017-02-15 13:49:16",
item: "raspbery pi2",
VIP: "YES",
Vendor_CODE: "XYZ67890",
},
{
user_id : 0001
CreatedOn: "2017-02-10 15:54:48",
item: "raspbery pi",
VIP: "YES",
Vendor_CODE: "RST171820",
},
{
user_id : 0001
CreatedOn: "2017-01-01 21:51:13",
item: "raspbery pi3",
VIP: "YES",
Vendor_CODE: "XOL002321",
},
{
user_id : 0005
CreatedOn: "2017-01-30 17:34:18",
item: "raspbery pi",
VIP: "YES",
Vendor_CODE: "RST171820",
},
{
user_id : 0005
CreatedOn: "2017-05-30 09:04:08",
item: "banana pi",
VIP: "YES",
Vendor_CODE: "ITI342027",
}]

Currently I have the following code that counts the number of times a user appears given two dates.

from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from collections import Counter
from datetime import datetime, timedelta
import json, urllib.request, dateutil.parser, urllib.parse,

#Request a response to the Web API
def get_data(request, *args, **kwargs):
    # YYYY-MM-DD
    start_date = datetime.now() - timedelta(days=7)
    end_date = datetime.now() - timedelta(days=1)

    with urllib.request.urlopen("http://10.61.202.98:8081/T/ansdb/api/rows/dev/ect",timeout=15) as url:
    response_data = json.loads(url.read().decode())

    #count the number of times the user appears when he bought the 4 items in two given dates
    count_user_01 = Counter([k['user_id'] for k in response_data if
         start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week])

My approach is to add some extra "condition" to count all items except the item raspberry pi3, something like:

count_user_01 = Counter([k['user_id'] for k in response_data if
     start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week] and k['item']!='raspberry pi3')

but if I do this then I encounter the error bool object is not iterable and I assume I receive this error because the collection Counter does not allow me to do this.

My questions are:

How can I implement this extra condition into the list so I can count all the items except raspberry pi3 that were bought by one user?

Currently, I am counting the items that were bought for specific users but how could I count all the items that were bought by all the users?

All comments, answers and suggestions are welcome.

Update

For question 1 the solution was to fix the problem in brackets.

count_user_01 = Counter([k['user_id'] for k in response_data if
 start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week and k['item']!='raspberry pi3'])

Body:
I think you have a problem with your brackets. Try this:

count_user_01 = Counter([k['user_id'] for k in response_data if
     start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week and k['item']!='raspberry pi3'])


问:
H2 console and Spring Security - permitAll() not working
I'm creating rest api and implemented Spring Security - everything works fine but I want (for now, when I'm still developing) to be able for anyone without authorization to open localhost:8080/console.
My code:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    // allow everyone to register an account; /console is just for testing
    http.authorizeRequests().antMatchers("/register", "/console").permitAll();

    http.authorizeRequests().anyRequest().fullyAuthenticated();

    // making H2 console working
    http.headers().frameOptions().disable();

    /*
    https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection
    for non-browser APIs there is no need to use csrf protection
    */
    http.csrf().disable();
}
</code>```

And what is really strange - localhost:8080/register doesn't need any authentication but /console returns:

```<code>{
"timestamp": 1485876313847,
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/console"
}
</code>```

Anyone knows how to fix it?

答:
I solved my problem by:</p>

```<code>http.headers().frameOptions().disable();
</code>```

Body:
I'm creating rest api and implemented Spring Security - everything works fine but I want (for now, when I'm still developing) to be able for anyone without authorization to open localhost:8080/console.
My code:

@Override
protected void configure(HttpSecurity http) throws Exception {
    // allow everyone to register an account; /console is just for testing
    http.authorizeRequests().antMatchers("/register", "/console").permitAll();

    http.authorizeRequests().anyRequest().fullyAuthenticated();

    // making H2 console working
    http.headers().frameOptions().disable();

    /*
    https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection
    for non-browser APIs there is no need to use csrf protection
    */
    http.csrf().disable();
}

And what is really strange - localhost:8080/register doesn't need any authentication but /console returns:

{
"timestamp": 1485876313847,
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/console"
}

Anyone knows how to fix it?

Body:
I solved my problem by:

http.headers().frameOptions().disable();


问:
SQL Windowed functions Error - Looking for a code fix / suggestion
Updated question

I want to get the COUNTS and SUMS of LOT items numbers. The lots have different BATCH numbers, each BATCH can have different REVISION numbers. REVISION numbers have to be the MAX(Revision) number within each batch number for PROPOSALSTATUS that are "awarded" or "closed/cancelled". If the proposal status is "ROR Awarded" or "OAA Awarded" then all values me be counted.

THIS is what I'm trying to use. Because of my MAX(revision) over statements I keep receiving a Windowed Functions Error. I do not understand how to work around that. If someone could take one of these counts and one sum and show me how to work around it would be awesome.

```<code>SELECT
COUNT(PB.lot)AS SubmittedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END)AS DecidedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot, pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END) AS WonCount,

COUNT(CASE WHEN pb.ProposalStatus = 'Disapproved' THEN 1 ELSE NULL END) AS DisapprovedCount,

SUM(pb.materialvalue + pb.shippingValue)AS Total,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END)AS DecidedTotal,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS WonTotal,

SUM(CASE WHEN pb.proposalStatus = 'Disapproved' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS DisapprovedTotal

FROM  DB1 ps
INNER JOIN DB2 pb
ON ps.Title = pb.Lot

WHERE  (pb.ProposalSubmitted IS NOT NULL)  AND BATCH <> 6 AND (ps.Contract LIKE 'CLS')
GROUP BY pb.lot, pb.batch, pb.revision, pb.proposalstatus
ORDER BY pb.lot
</code>```

Realistically -  I want to be able to put this into a small table that looks like this:
Sample Input

Final Results

```<code>    declare @pb table
              (lot, proposalStatus, proposalSubmitted datetime,
               revision, materialValue, shippingValue, batch);

    insert into @pb
    values ('1', 'Awarded', '5/23/2016', '0', '200', '100', '2'),
           ('1', 'Awarded', '5/23/2016', '0', '200', '300', '4'),
           ('2', 'Pending', '  ', '1', '100', '400', '2'),
           ('3', 'Cancelled', '6/12/2016', '4', '200', '100', '4'),
           ('4', 'Awarded', '5/12/2016', '2', '300', '100', '3')

    declare @ps table
                   (title, contract);
    insert into ps
values ('1', 'CLS'),
       ('1', 'AFC'),
       ('2', 'CLS'),
       ('3', 'AFC'),
       ('4', 'CLS')
</code>```

My join is on pb.lot = ps.title

答:
In this line:

```<code>(SELECT COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled' OR pb.proposalstatus = 'Awarded' THEN 1 ELSE NULL END)))
</code>```

You are missing a comma after "pb.batch".

Body:
Updated question

I want to get the COUNTS and SUMS of LOT items numbers. The lots have different BATCH numbers, each BATCH can have different REVISION numbers. REVISION numbers have to be the MAX(Revision) number within each batch number for PROPOSALSTATUS that are "awarded" or "closed/cancelled". If the proposal status is "ROR Awarded" or "OAA Awarded" then all values me be counted.

THIS is what I'm trying to use. Because of my MAX(revision) over statements I keep receiving a Windowed Functions Error. I do not understand how to work around that. If someone could take one of these counts and one sum and show me how to work around it would be awesome.

SELECT
COUNT(PB.lot)AS SubmittedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END)AS DecidedCount,

COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot, pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN 1 ELSE NULL END))) +
COUNT(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN 1 ELSE NULL END) AS WonCount,

COUNT(CASE WHEN pb.ProposalStatus = 'Disapproved' THEN 1 ELSE NULL END) AS DisapprovedCount,

SUM(pb.materialvalue + pb.shippingValue)AS Total,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled'   OR pb.proposalstatus = 'Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.proposalstatus = 'ROR Awarded'  or pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END)AS DecidedTotal,

SUM(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch,(CASE WHEN pb.proposalstatus = 'OAA Partially Awarded' OR pb.ProposalStatus = 'ROR Partially Awarded'  OR pb.proposalstatus = 'OAA Proposal Submitted - Pending Award' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END))) +
SUM(CASE WHEN pb.ProposalStatus = 'Awarded' OR pb.ProposalStatus = 'ROR Awarded' OR pb.ProposalStatus = 'OAA Awarded' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS WonTotal,

SUM(CASE WHEN pb.proposalStatus = 'Disapproved' THEN pb.MaterialValue + Pb.ShippingValue ELSE NULL END) AS DisapprovedTotal

FROM  DB1 ps
INNER JOIN DB2 pb
ON ps.Title = pb.Lot

WHERE  (pb.ProposalSubmitted IS NOT NULL)  AND BATCH <> 6 AND (ps.Contract LIKE 'CLS')
GROUP BY pb.lot, pb.batch, pb.revision, pb.proposalstatus
ORDER BY pb.lot

Realistically -  I want to be able to put this into a small table that looks like this:
Sample Input

Final Results

    declare @pb table
              (lot, proposalStatus, proposalSubmitted datetime,
               revision, materialValue, shippingValue, batch);

    insert into @pb
    values ('1', 'Awarded', '5/23/2016', '0', '200', '100', '2'),
           ('1', 'Awarded', '5/23/2016', '0', '200', '300', '4'),
           ('2', 'Pending', '  ', '1', '100', '400', '2'),
           ('3', 'Cancelled', '6/12/2016', '4', '200', '100', '4'),
           ('4', 'Awarded', '5/12/2016', '2', '300', '100', '3')

    declare @ps table
                   (title, contract);
    insert into ps
values ('1', 'CLS'),
       ('1', 'AFC'),
       ('2', 'CLS'),
       ('3', 'AFC'),
       ('4', 'CLS')

My join is on pb.lot = ps.title

Body:
In this line:

(SELECT COUNT(DISTINCT MAX(pb.revision) OVER (PARTITION BY pb.lot,pb.batch(CASE WHEN pb.ProposalStatus = 'Closed/Cancelled' OR pb.proposalstatus = 'Awarded' THEN 1 ELSE NULL END)))

You are missing a comma after "pb.batch".


问:
How can I make a Python script a drop-in for a Windows executable?
I wrote a little Python script wrapcl.py script which wraps our compiler binary (cl.exe, the Microsoft Visual Studio C++ compiler). I then created a new batch file cl.bat which makes that Python script accessible so that I can run cl as before and it will silently call my wrapper script instead of the real program. For what it's worth, here is my cl.bat batch file:

```<code>@python %~dp0\wrapcl.py %*
</code>```

This works quite well - except in one case:

We have existing scripts which do something like

```<code>cl >NUL 2>&1 && GOTO CL
</code>```

to determine whether the Microsoft Visual Studio C++ compiler is available. This breaks if cl actually calls my cl.bat batch file since the call to cl.bat never returns. We'd have to use call cl >NUL ... for that.

Is there any way I can make my wrapcl.py Python script look just like cl.exe for callers so that I can avoid touching our existing scripts which expect cl && foo to work?

答:
One possibility is to compile your python code as an executable using py2exe.  Here's a link:
py2exe</p>

ContentLicense: CC BY-SA 2.5

Body:
I wrote a little Python script wrapcl.py script which wraps our compiler binary (cl.exe, the Microsoft Visual Studio C++ compiler). I then created a new batch file cl.bat which makes that Python script accessible so that I can run cl as before and it will silently call my wrapper script instead of the real program. For what it's worth, here is my cl.bat batch file:

@python %~dp0\wrapcl.py %*

This works quite well - except in one case:

We have existing scripts which do something like

cl >NUL 2>&1 && GOTO CL

to determine whether the Microsoft Visual Studio C++ compiler is available. This breaks if cl actually calls my cl.bat batch file since the call to cl.bat never returns. We'd have to use call cl >NUL ... for that.

Is there any way I can make my wrapcl.py Python script look just like cl.exe for callers so that I can avoid touching our existing scripts which expect cl && foo to work?


问:
Angular2 ng build not working properly
So i am using ng build in my angular2 project to create smaller folder size of my project called dist, but once i upload my project to my web host using file transfer protocol(Filezilla) it doesn't show my website. Is there some step i am still missing?</p>

答:
I will always follow steps to deploy my App

1) add script in the package.json

```<code>"Prod_build": "ng build --base-href /yourappName/ --target=production --aot",
</code>```

2) Run npm run Prod_build

3) copy your dist folder to your webhost.

Title: Angular2 ng build not working properly

Body:
I will always follow steps to deploy my App

1) add script in the package.json

"Prod_build": "ng build --base-href /yourappName/ --target=production --aot",

2) Run npm run Prod_build

3) copy your dist folder to your webhost.


问:
How to incorporate href to section with Html.ActionLink in MVC?
I am new to MVC and have encountered a problem. I have an HTML page that scrolls down to a section when that section's name is clicked from the navigation bar but now I have to change this HTML line of code to MVC:

```<code><li><a class="page-scroll" href="#services">Services</a></li>
</code>```

I have tried to use Html.ActionLink but have not had any success yet!

What I have so far:

```<code>@Html.ActionLink("Services", "Index", "Home", new { area = "#services" }, new { @class = "page-scroll" })
</code>```

答:
Create your own helper or use raw html

Link Text

OR

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "services", new { parameter = "example"}, null) %>

On your Index page:

Here is the content you want to make show when you click the link

When you click on 'Link Text' it will direct you to the services section of your Index page.

Body:
I am new to MVC and have encountered a problem. I have an HTML page that scrolls down to a section when that section's name is clicked from the navigation bar but now I have to change this HTML line of code to MVC:

Services

I have tried to use Html.ActionLink but have not had any success yet!

What I have so far:

@Html.ActionLink("Services", "Index", "Home", new { area = "#services" }, new { @class = "page-scroll" })

Body:
Create your own helper or use raw html

<li><a href="@Url.Action("Action", "Controller")#services">Link Text</a></li>

OR

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "services", new { parameter = "example"}, null) %>

On your Index page:

<div id="services">
    <p>Here is the content you want to make show when you click the link</p>
</div>

When you click on 'Link Text' it will direct you to the services section of your Index page.


问:
Look up of comma separated data in another table
I do have 2 tables where in the table data frame consist data with comma separated values.

Need to find out which category present in lookup data frame i.e. in Option 1 out of "Cat A, Cat B, Cat C" which category is present. if found, need to show the score against it.

incase multiple instance found, we need to show the score of first occurrence hence in first case Cat C and Cat Z both comes under Option 1 however we need to show the score for Cat C only which is 2.

Table

```<code>Option           | Cat
-----             ------
Option 1         | Cat A, Cat B, Cat C, Cat Z
Option 2         | Cat X, Cat Y, Cat Z, Cat B
Option 3         | Cat P, Cat Q, Cat R, Cat S, Cat T
Option 1         | Cat T
Option 3         | Cat E, Cat F
</code>```

Lookup

```<code>Cat   |   Option    |   Score

Cat A |   Option 2   |   8
Cat B |   Option 3   |   3
Cat C |   Option 1   |   2
Cat X |   Option 3   |   9
Cat Y |   Option 1   |   1
Cat Z |   Option 2   |   1
Cat P |   Option 3   |   2
Cat Q |   Option 2   |   9
Cat R |   Option 1   |   4
Cat S |   Option 4   |   0
Cat T |   Option 1   |   5
Cat E |   Option 4   |   1
Cat F |   Option 3   |   10
</code>```

Output

```<code> Option      |     Cat                                |     Found_cat    |     Score
 Option 1    |     Cat A, Cat B, Cat C                |     Cat C        |     2
 Option 2    |     Cat X, Cat Y, Cat Z, Cat B          |     Cat Z        |     1
 Option 3    |     Cat P, Cat Q, Cat R, Cat S, Cat T  |     Cat P        |     2
 Option 1    |     Cat T                              |     Cat T        |     5
 Option 3    |     Cat E, Cat F                       |     Cat F        |     10
</code>```

R Code for creating dataframe

```<code>Table <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                 Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y,Cat Z, Cat B", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"))

lookup <-data.frame(Cat = c("Cat A", "Cat B", "Cat C", "Cat X", "Cat Y", "Cat Z", "Cat P", "Cat Q", "Cat R", "Cat S", "Cat T", "Cat E", "Cat F"),
                    Options = c("Option 2", "Option 3", "Option 1", "Option 3", "Option 1", "Option 2", "Option 3", "Option 2", "Option 1", "Option 4", "Option 1", "Option 4", "Option 3"),
                    Score = c(8, 3, 2, 9, 1, 1, 2, 9, 4, 0, 5, 1, 10))

output <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                     Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y, Cat Z, Cat B,", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"),
                     Found_cat = c("Cat C", "Cat Z", "Cat P", "Cat T", "Cat F"),
                     Score = c(2, 1, 2, 5, 10))
</code>```

答:
Here is a tidyverse option,

```<code>library(tidyverse)

Table %>%
  unnest(Cat = strsplit(as.character(Cat), ', ')) %>%
  inner_join(lookup, by = c('Option', 'Cat')) %>%
  select(Cat, Score) %>%
  rename(Cat_Found = Cat) %>%
  bind_cols(Table, .)

#    Option                               Cat Cat_Found Score
#1 Option 1               Cat A, Cat B, Cat C     Cat C     2
#2 Option 2        Cat X, Cat Y, Cat Z, Cat B     Cat Z     1
#3 Option 3 Cat P, Cat Q, Cat R, Cat S, Cat T     Cat P     2
#4 Option 1                             Cat T     Cat T     5
#5 Option 3                      Cat E, Cat F     Cat F    10
</code>```

Body:
I do have 2 tables where in the table data frame consist data with comma separated values.

Need to find out which category present in lookup data frame i.e. in Option 1 out of "Cat A, Cat B, Cat C" which category is present. if found, need to show the score against it.

incase multiple instance found, we need to show the score of first occurrence hence in first case Cat C and Cat Z both comes under Option 1 however we need to show the score for Cat C only which is 2.

Table

Option           | Cat
-----             ------
Option 1         | Cat A, Cat B, Cat C, Cat Z
Option 2         | Cat X, Cat Y, Cat Z, Cat B
Option 3         | Cat P, Cat Q, Cat R, Cat S, Cat T
Option 1         | Cat T
Option 3         | Cat E, Cat F

Lookup

Cat   |   Option    |   Score

Cat A |   Option 2   |   8
Cat B |   Option 3   |   3
Cat C |   Option 1   |   2
Cat X |   Option 3   |   9
Cat Y |   Option 1   |   1
Cat Z |   Option 2   |   1
Cat P |   Option 3   |   2
Cat Q |   Option 2   |   9
Cat R |   Option 1   |   4
Cat S |   Option 4   |   0
Cat T |   Option 1   |   5
Cat E |   Option 4   |   1
Cat F |   Option 3   |   10

Output

 Option      |     Cat                                |     Found_cat    |     Score
 Option 1    |     Cat A, Cat B, Cat C                |     Cat C        |     2
 Option 2    |     Cat X, Cat Y, Cat Z, Cat B          |     Cat Z        |     1
 Option 3    |     Cat P, Cat Q, Cat R, Cat S, Cat T  |     Cat P        |     2
 Option 1    |     Cat T                              |     Cat T        |     5
 Option 3    |     Cat E, Cat F                       |     Cat F        |     10

R Code for creating dataframe

Table <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                 Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y,Cat Z, Cat B", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"))

lookup <-data.frame(Cat = c("Cat A", "Cat B", "Cat C", "Cat X", "Cat Y", "Cat Z", "Cat P", "Cat Q", "Cat R", "Cat S", "Cat T", "Cat E", "Cat F"),
                    Options = c("Option 2", "Option 3", "Option 1", "Option 3", "Option 1", "Option 2", "Option 3", "Option 2", "Option 1", "Option 4", "Option 1", "Option 4", "Option 3"),
                    Score = c(8, 3, 2, 9, 1, 1, 2, 9, 4, 0, 5, 1, 10))

output <- data.frame(Option = c("Option 1", "Option 2", "Option 3", "Option 1", "Option 3"),
                     Cat = c("Cat A, Cat B, Cat C", "Cat X, Cat Y, Cat Z, Cat B,", "Cat P, Cat Q, Cat R, Cat S, Cat T", "Cat T", "Cat E, Cat F"),
                     Found_cat = c("Cat C", "Cat Z", "Cat P", "Cat T", "Cat F"),
                     Score = c(2, 1, 2, 5, 10))

Body:
Here is a tidyverse option,

library(tidyverse)

Table %>%
  unnest(Cat = strsplit(as.character(Cat), ', ')) %>%
  inner_join(lookup, by = c('Option', 'Cat')) %>%
  select(Cat, Score) %>%
  rename(Cat_Found = Cat) %>%
  bind_cols(Table, .)

#    Option                               Cat Cat_Found Score
#1 Option 1               Cat A, Cat B, Cat C     Cat C     2
#2 Option 2        Cat X, Cat Y, Cat Z, Cat B     Cat Z     1
#3 Option 3 Cat P, Cat Q, Cat R, Cat S, Cat T     Cat P     2
#4 Option 1                             Cat T     Cat T     5
#5 Option 3                      Cat E, Cat F     Cat F    10


问:
JPEG corrupted after sending via HTTP
I'm trying to build a simple HTTP Java server from scratch.
Right now I am trying to get my browser to download a .jpg-file on my PC,
that's why
The foimage/jpeg is hardcoded into the method. The following is the method printing the HTTP-response to my browser. desiredFile a .jpg file called "Image.jpg" stored on my Computer.

Everything works great and my broser downloads the file, but I cannot open it. The Windows Image Program just tells me that it's "probably damaged". When I view the image's details I can see that it has the same byte-size, but details such as resolution are lost.  `

```<code>        byte[] bytes = Files.readAllBytes(desiredFile.toPath());

        System.out.println("Attempting to print to client|" + bytes.length

        output.write("HTTP/1.1 200 OK" + "\r\n"
                        + "Content-type: image/jpeg" + "\r\n"
                        + "Content-length: " + bytes.length + "\r\n"
                        + "Content-Disposition: attachment; filename=Imae.jpg" + "\r\n"
                        + "\r\n");

        for (byte currentByte : bytes)
            output.write(currentByte);

        output.flush();
        output.close();

        System.out.println("Printing finished.");
        `
</code>```

Is there something wrong with the way I am transmitting the bytes? Sending bytesas a whole array did not work, that is why I am sending every byte after the other.

Thanks!

答:
I'm not 100% sure, but you might be missing the header:</p>

```<code>Accept-Ranges: bytes
</code>```

Title: JPEG corrupted after sending via HTTP

Body:
I'm trying to build a simple HTTP Java server from scratch.
Right now I am trying to get my browser to download a .jpg-file on my PC,
that's why
The foimage/jpeg is hardcoded into the method. The following is the method printing the HTTP-response to my browser. desiredFile a .jpg file called "Image.jpg" stored on my Computer.

Everything works great and my broser downloads the file, but I cannot open it. The Windows Image Program just tells me that it's "probably damaged". When I view the image's details I can see that it has the same byte-size, but details such as resolution are lost.  `

        byte[] bytes = Files.readAllBytes(desiredFile.toPath());

        System.out.println("Attempting to print to client|" + bytes.length

        output.write("HTTP/1.1 200 OK" + "\r\n"
                        + "Content-type: image/jpeg" + "\r\n"
                        + "Content-length: " + bytes.length + "\r\n"
                        + "Content-Disposition: attachment; filename=Imae.jpg" + "\r\n"
                        + "\r\n");

        for (byte currentByte : bytes)
            output.write(currentByte);

        output.flush();
        output.close();

        System.out.println("Printing finished.");
        `

Is there something wrong with the way I am transmitting the bytes? Sending bytesas a whole array did not work, that is why I am sending every byte after the other.

Thanks!

Body:
I'm not 100% sure, but you might be missing the header:

Accept-Ranges: bytes


问:
Change icon color if condition
I am using a list that prints data from a model and one should have an icon. The thing is that the icon changes depending on the value and I should also change its color.

I have in my view :

```<code><ObjectListItem title="State" type="Active" number="{/Data/8/state}"
icon="{= ${/Data/8/state}.toUpperCase() === 'OK' ? 'sap-icon://accept' :
'sap-icon://decline' }"></ObjectListItem>
</code>```

Options like addStyleClass doesn't seem to work. I have changed the color by adding css to the id that SAP adds to the Icon, but since it has to change according to the value I don't know how to achieve it.
Another option was to add color directly to these two icons but I wasn't able to add the classes.

答:
You can use CustomData and then create a css selector to match it:

```<code><ObjectListItem title="State" type="Active" number="{/Data/8/state}"
icon="{= ${/Data/8/state}.toUpperCase() === 'OK' ? 'sap-icon://accept' :
'sap-icon://decline' }">
<customData>
  <core:CustomData writeToDom="true" key="class" value="{= ${/Data/8/state}.toUpperCase()}" />
</customData>
</ObjectListItem>
</code>```

This will render your control with an additional data-class attribute (actually, data-{key}, where key is the key that you defined on your core:CustomDatatag).

You can then match that with the CSS selector

```<code>[data-class='OK'] {
  color: blue !important;
}
[data-class='NOT-OK']{
  color: red !important;
}
</code>```

Title: Change icon color if condition

Body:
I am using a list that prints data from a model and one should have an icon. The thing is that the icon changes depending on the value and I should also change its color.

I have in my view :

<ObjectListItem title="State" type="Active" number="{/Data/8/state}"
icon="{= ${/Data/8/state}.toUpperCase() === 'OK' ? 'sap-icon://accept' :
'sap-icon://decline' }"></ObjectListItem>

Options like addStyleClass doesn't seem to work. I have changed the color by adding css to the id that SAP adds to the Icon, but since it has to change according to the value I don't know how to achieve it.
Another option was to add color directly to these two icons but I wasn't able to add the classes.

Body:
You can use CustomData and then create a css selector to match it:

<ObjectListItem title="State" type="Active" number="{/Data/8/state}"
icon="{= ${/Data/8/state}.toUpperCase() === 'OK' ? 'sap-icon://accept' :
'sap-icon://decline' }">
<customData>
  <core:CustomData writeToDom="true" key="class" value="{= ${/Data/8/state}.toUpperCase()}" />
</customData>
</ObjectListItem>

This will render your control with an additional data-class attribute (actually, data-{key}, where key is the key that you defined on your core:CustomDatatag).

You can then match that with the CSS selector

[data-class='OK'] {
  color: blue !important;
}
[data-class='NOT-OK']{
  color: red !important;
}


问:
Can I build a list of Strings using each constructor of a class?
I have a simple data type such as:

```<code>data Class = Class1
           | Class2
           | Class3
           deriving (Show, Eq)
</code>```

Is there a simple way for me to build a list of Strings that contains the String version of each of these such that:

```<code>func Class = ["Class1", "Class2", "Class3"]
</code>```

答:
You could, perhaps, do something like this:

```<code>data Class = Class1 | Class2 | Class3 deriving (Show, Eq, Enum)
</code>```

GHCI:

```<code>Prelude> fmap show $ enumFrom Class1
["Class1","Class2","Class3"]
</code>```

Body:
I have a simple data type such as:

data Class = Class1
           | Class2
           | Class3
           deriving (Show, Eq)

Is there a simple way for me to build a list of Strings that contains the String version of each of these such that:

func Class = ["Class1", "Class2", "Class3"]

Body:
You could, perhaps, do something like this:

data Class = Class1 | Class2 | Class3 deriving (Show, Eq, Enum)

GHCI:

Prelude> fmap show $ enumFrom Class1
["Class1","Class2","Class3"]


问:
How to check if mysql database exists
Is it possible to check if a (MySQL) database exists after having made a connection.

I know how to check if a table exists in a DB, but I need to check if the DB exists. If not I have to call another piece of code to create it and populate it.

I know this all sounds somewhat inelegant - this is a quick and dirty app.

答:
I am using simply the following query:

```<code>"USE 'DBname'"
</code>```

Then check if the result is FALSE.
Otherwise, there might be an access denied error, but I cannot know that.
So, in case of privileges involved, one can use:

```<code>"SHOW DATABASES LIKE 'DBname'"
</code>```

as already mentioned earlier.

Title: How to check if mysql database exists

Body:
I am using simply the following query:

"USE 'DBname'"

Then check if the result is FALSE.
Otherwise, there might be an access denied error, but I cannot know that.
So, in case of privileges involved, one can use:

"SHOW DATABASES LIKE 'DBname'"

as already mentioned earlier.


问:
multi module maven project with parent pom and svn layout
I currently have about 16 projects that I build with maven that get deployed to the same application server that make up something like a "portal". I have built a parent pom to handle common dependencies and plugin configurations. Currently, my SVN structure looks similar to this:

```<code>portal_root
    +project1
        +tags
        +branches
        +trunk
    +project2
        .
        .
        .
    +projectn
    pom.xml
</code>```

The individual projects are each separately deployed. That is, project1 doesn't have a dependency on project2 and each can be modified and deployed without having to modify anything else.

This presents a problem with SVN as if another developer wanted to check out the entire "portal" root (to also get the parent pom) they would also by default pull down copies of all the tags and branches! Not really ideal.

The only other thing I can think of is to use something like this:

```<code> portal_root
     +tags
     +branches
     +trunk
         +project1
              +src
              pom.xml
         +project2
             .
             .
             .
         pom.xml
</code>```

However, now all project changes will be tracked in the tags folder. This isn't a huge problem for me, but branching now seems to become a pain.

I am also currently working on hooking up Teamcity into this as well which would be a bit easier now, since I would only have to watch a single directory (e.g. tags) to catch everything that needs to be built. I am also deploying artifacts to a enterprise Nessus repository.

I'm hoping someone could give me some suggestions here as I have been unable to find any decent documentation that talks about the entire build lifecycle and best practices here.

I like the idea of being able to build and deploy all the projects with a single maven command. I also like having all the common dependencies, repository information and plugin information in one place.

答:
You can use following layout:

```<code>+parent-project
  pom.xml
+child-project-1
  pom.xml
+child-project-2
  pom.xml
</code>```

In parent project pom add:

```<code><modules>
    <module>../child-project-1</module>
    <module>../child-project-2</module>
</modules>
</code>```

In children projects pom add:

```<code><parent>
    <artifactId><!-- parent artifactId --></artifactId>
    <groupId><!-- parent groupdId --></groupId>
    <version><!-- parent version --></version>
    <relativePath>../parent-project</relativePath>
</parent>
</code>```

Children Projects can optionally be dependent.

Following links may also help:

http://maven.apache.org/guides/introduction/introduction-to-the-pom.html

Maven parent pom vs modules pom

Body:
I currently have about 16 projects that I build with maven that get deployed to the same application server that make up something like a "portal". I have built a parent pom to handle common dependencies and plugin configurations. Currently, my SVN structure looks similar to this:

portal_root
    +project1
        +tags
        +branches
        +trunk
    +project2
        .
        .
        .
    +projectn
    pom.xml

The individual projects are each separately deployed. That is, project1 doesn't have a dependency on project2 and each can be modified and deployed without having to modify anything else.

This presents a problem with SVN as if another developer wanted to check out the entire "portal" root (to also get the parent pom) they would also by default pull down copies of all the tags and branches! Not really ideal.

The only other thing I can think of is to use something like this:

 portal_root
     +tags
     +branches
     +trunk
         +project1
              +src
              pom.xml
         +project2
             .
             .
             .
         pom.xml

However, now all project changes will be tracked in the tags folder. This isn't a huge problem for me, but branching now seems to become a pain.

I am also currently working on hooking up Teamcity into this as well which would be a bit easier now, since I would only have to watch a single directory (e.g. tags) to catch everything that needs to be built. I am also deploying artifacts to a enterprise Nessus repository.

I'm hoping someone could give me some suggestions here as I have been unable to find any decent documentation that talks about the entire build lifecycle and best practices here.

I like the idea of being able to build and deploy all the projects with a single maven command. I also like having all the common dependencies, repository information and plugin information in one place.

Body:
You can use following layout:

+parent-project
  pom.xml
+child-project-1
  pom.xml
+child-project-2
  pom.xml

In parent project pom add:

<modules>
    <module>../child-project-1</module>
    <module>../child-project-2</module>
</modules>

In children projects pom add:

<parent>
    <artifactId><!-- parent artifactId --></artifactId>
    <groupId><!-- parent groupdId --></groupId>
    <version><!-- parent version --></version>
    <relativePath>../parent-project</relativePath>
</parent>

Children Projects can optionally be dependent.

Following links may also help:

http://maven.apache.org/guides/introduction/introduction-to-the-pom.html

Maven parent pom vs modules pom


问:
How to add Glyphicon to {{!! Form::Button !!}}
I'm using Laravel 5.0 and have the following problem.

This is my button:

```<code>{!! Form::button('Delete', array('class' => 'btn btn-sm btn-danger', 'data-toggle' => 'modal', 'data-target' => '#'.$category->id)) !!}
</code>```

How can I add something like this:

```<code><span class="glyphicon glyphicon-trash"></span>
</code>```

I'm came across to this -> Is it possible to put a bootstrap glyphicon inside of a {{ Form::submit(' ')}} - Laravel but it is for the notation wihtout exclamation marks (It does not work for me).

答:
This will do the trick:</p>

```<code>{{ Form::button('', ['type' => 'submit', 'class' => 'btn btn-danger glyphicon glyphicon-remove']) }}
</code>```

Body:
I'm using Laravel 5.0 and have the following problem.

This is my button:

{!! Form::button('Delete', array('class' => 'btn btn-sm btn-danger', 'data-toggle' => 'modal', 'data-target' => '#'.$category->id)) !!}

How can I add something like this:

I'm came across to this -> Is it possible to put a bootstrap glyphicon inside of a {{ Form::submit(' ')}} - Laravel but it is for the notation wihtout exclamation marks (It does not work for me).

Body:
This will do the trick:

{{ Form::button('', ['type' => 'submit', 'class' => 'btn btn-danger glyphicon glyphicon-remove']) }}


问:
How to create datasource with JNDI link (Wildfly)?
How I can connect to database with JTA and without persistence.xml, use only annotations?
And how create datasource with JNDI link ?

I have JNDI link from Wildfly_10 java:jboss/datasources/PostgreDataSource

persistence.xml snippet

```<code>    `<persistence-unit name="Unit1" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/PostgreDataSource</jta-data-source>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>`
</code>```

My config file:

```<code>@Configuration
@EnableTransactionManagement
@ComponentScan({ "net.myProg" })
@PropertySource(value = { "classpath:application.properties" })
@EnableJpaRepositories("net.myProg.repository")
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan("net.myProg.model");

        entityManagerFactoryBean.setJpaProperties(hibernateProperties());

        return entityManagerFactoryBean;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
//        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        //Lazy load initializayion. Hibernate сам открывает сессию для получения lazy объекта, если это нужно
        properties.put("hibernate.enable_lazy_load_no_trans", environment.getRequiredProperty("hibernate.enable_lazy_load_no_trans"));
//        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource());
        return db;
    }

}
</code>```

答:
Create a bean for data source using jndi name

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springmodules.org/schema/ehcache
        http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.1.xsd">

    <bean id="appDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:jboss/datasources/xyzDataSouce</value>
        </property>
    </bean>

</beans>
</code>```

If your Using a JPA Repository can use this Data Source like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springmodules.org/schema/ehcache
        http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <tx:annotation-driven transaction-manager="apptransactionManager" />

    <bean id="apptransactionManager"  class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="appEntityManagerFactory" />
    </bean>

    <bean id="appEntityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
              <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="dataSource" ref="appDataSource" />
        <property name="packagesToScan">
            <list>
                <value>net.something.something</value>
            </list>
        </property>
        <property name="jpaPropertyMap">
            <props>
                <prop key="hibernate.show_sql">${jpaVendorAdapter.hibernate.show_sql}</prop>
                <prop key="hibernate.dialect">${jpaVendorAdapter.hibernate.dialect}</prop>
                <prop key="hibernate.jdbc.batch_size">${jpaVendorAdapter.hibernate.jdbc.batch_size}</prop>
                <prop key="hibernate.hbm2ddl.auto">${jpaVendorAdapter.hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.default_schema">${jpaVendorAdapter.hibernate.default_schema}</prop>
                <prop key="org.hibernate.envers.audit_table_suffix">${jpaVendorAdapter.org.hibernate.envers.audit_table_suffix}</prop>
                <prop key="org.hibernate.envers.audit_table_prefix">${jpaVendorAdapter.org.hibernate.envers.audit_table_prefix}</prop>
                <prop key="org.hibernate.envers.revision_field_name">${jpaVendorAdapter.org.hibernate.envers.revision_field_name}</prop>
                <prop key="org.hibernate.envers.revision_type_field_name">${jpaVendorAdapter.org.hibernate.envers.revision_type_field_name}</prop>

            </props>
        </property>
    </bean>

    <jpa:repositories base-package="net.something.something.core.dao" transaction-manager-ref="apptransactionManager"/>

    <!-- Needed for @PersistenceContext annotation -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <tx:annotation-driven transaction-manager="apptransactionManager"/>
    <aop:aspectj-autoproxy/>

    <!-- JSR-303 bean validation -->
    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- <property name="providerClass" value="org.apache.bval.jsr303.ApacheValidationProvider" /> -->
    </bean>

</beans>
</code>```

If you want you can create two files and add those two files into application-context xml and everything will start working fine

Body:
How I can connect to database with JTA and without persistence.xml, use only annotations?
And how create datasource with JNDI link ?

I have JNDI link from Wildfly_10 java:jboss/datasources/PostgreDataSource

persistence.xml snippet

    `<persistence-unit name="Unit1" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/PostgreDataSource</jta-data-source>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>`

My config file:

@Configuration
@EnableTransactionManagement
@ComponentScan({ "net.myProg" })
@PropertySource(value = { "classpath:application.properties" })
@EnableJpaRepositories("net.myProg.repository")
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan("net.myProg.model");

        entityManagerFactoryBean.setJpaProperties(hibernateProperties());

        return entityManagerFactoryBean;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
//        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        //Lazy load initializayion. Hibernate сам открывает сессию для получения lazy объекта, если это нужно
        properties.put("hibernate.enable_lazy_load_no_trans", environment.getRequiredProperty("hibernate.enable_lazy_load_no_trans"));
//        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource());
        return db;
    }

}

Body:
Create a bean for data source using jndi name

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springmodules.org/schema/ehcache
        http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.1.xsd">

    <bean id="appDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:jboss/datasources/xyzDataSouce</value>
        </property>
    </bean>

</beans>

If your Using a JPA Repository can use this Data Source like this

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springmodules.org/schema/ehcache
        http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <tx:annotation-driven transaction-manager="apptransactionManager" />

    <bean id="apptransactionManager"  class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="appEntityManagerFactory" />
    </bean>

    <bean id="appEntityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
              <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="dataSource" ref="appDataSource" />
        <property name="packagesToScan">
            <list>
                <value>net.something.something</value>
            </list>
        </property>
        <property name="jpaPropertyMap">
            <props>
                <prop key="hibernate.show_sql">${jpaVendorAdapter.hibernate.show_sql}</prop>
                <prop key="hibernate.dialect">${jpaVendorAdapter.hibernate.dialect}</prop>
                <prop key="hibernate.jdbc.batch_size">${jpaVendorAdapter.hibernate.jdbc.batch_size}</prop>
                <prop key="hibernate.hbm2ddl.auto">${jpaVendorAdapter.hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.default_schema">${jpaVendorAdapter.hibernate.default_schema}</prop>
                <prop key="org.hibernate.envers.audit_table_suffix">${jpaVendorAdapter.org.hibernate.envers.audit_table_suffix}</prop>
                <prop key="org.hibernate.envers.audit_table_prefix">${jpaVendorAdapter.org.hibernate.envers.audit_table_prefix}</prop>
                <prop key="org.hibernate.envers.revision_field_name">${jpaVendorAdapter.org.hibernate.envers.revision_field_name}</prop>
                <prop key="org.hibernate.envers.revision_type_field_name">${jpaVendorAdapter.org.hibernate.envers.revision_type_field_name}</prop>

            </props>
        </property>
    </bean>

    <jpa:repositories base-package="net.something.something.core.dao" transaction-manager-ref="apptransactionManager"/>

    <!-- Needed for @PersistenceContext annotation -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <tx:annotation-driven transaction-manager="apptransactionManager"/>
    <aop:aspectj-autoproxy/>

    <!-- JSR-303 bean validation -->
    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- <property name="providerClass" value="org.apache.bval.jsr303.ApacheValidationProvider" /> -->
    </bean>

</beans>

If you want you can create two files and add those two files into application-context xml and everything will start working fine


问:
Implementing an integer merge sort in C#
Recently got a bubble sort algorithm functioning, and decided I would try a merge sort algorithm, I'm trying to write it from scratch as a personal challenge, I feel as though my logic is fundamentally flawed in it however, Not knowing where else to turn for advice, I welcome any input. I feel like C# doesn't like my declaration of sub-arrays, they do seem to be an improper solution also</p>

```<code>public static void MergeSort(int[] A) // WIP
    {
        if (A.Length % 2 == 0 )     //Checks if input array is even
        {
            int[] B;                //Declares sub array
            int[] C;                //Declares sub array
            for (int x = 0; x < A.Length ; x++)     //Performs an action for every item item in the array
            {
                if (x < A.Length / 2)               //selects the first half of the input array and assigns it to sub-Array B
                {
                    B[x] = A[x];
                }
                if(x > A.Length / 2)                //Selects the second half of the input array and assigns it to sub-Array C
                {
                    C[x] = A[x];

                }
            }

        }
</code>```

答:
You're declaring references to arrays, but never initializing them. B and C will be null and you'll get an exception if you try to do anything with them.

```<code>        //  Declares *reference* to sub array, and creates it as well.
        int[] B = new int[A.Length];

        //  Declares *reference* to sub array, and creates it as well.
        int[] C = new int[A.Length];
</code>```

You could use List<int> instead of arrays.

The thing is, you'll only be using the first half of B and the second half of C. Is that what you want? If you want B to be just the first half of  A, and C to be just the last half of A, do this. You can use List<int> pretty much identically to an array, but you can Add() to it, and it has a Count property instead of a Length property:

```<code>        var B = new List<int>();
        var C = new List<int>();

        for (int x = 0; x < A.Length ; x++)     //Performs an action for every item item in the array
        {
            if (x < A.Length / 2)               //selects the first half of the input array and assigns it to sub-Array B
            {
                B.Add(A[x]);
            }
            if(x > A.Length / 2)                //Selects the second half of the input array and assigns it to sub-Array C
            {
                C.Add(A[x]);
            }
        }
</code>```

Another thing: I'd put an else before the second if here, for clarity more than runtime efficiency.

But what happens if x is equal to A.Length / 2? If that case is handled in code you didn't include in your question, never mind.

```<code>            if (x < A.Length / 2)               //selects the first half of the input array and assigns it to sub-Array B
            {
                B.Add(A[x]);
            }
            else if(x > A.Length / 2)                //Selects the second half of the input array and assigns it to sub-Array C
            {
                C.Add(A[x]);
            }
</code>```

You could, howerver, simplify that code as follows:

```<code>if (A.Length % 2 == 0)
{
    //  Take the first half and make an array out of that sequence
    var B = A.Take(A.Length / 2).ToArray();

    //  Skip the first half and make an array out of the remaining sequence
    var C = A.Skip(A.Length / 2).ToArray();
}
</code>```

But if you're meant to be demonstrating a grasp of basic programming fundamentals rather than C# trivia, your loop method is best.

Body:
Recently got a bubble sort algorithm functioning, and decided I would try a merge sort algorithm, I'm trying to write it from scratch as a personal challenge, I feel as though my logic is fundamentally flawed in it however, Not knowing where else to turn for advice, I welcome any input. I feel like C# doesn't like my declaration of sub-arrays, they do seem to be an improper solution also

public static void MergeSort(int[] A) // WIP
    {
        if (A.Length % 2 == 0 )     //Checks if input array is even
        {
            int[] B;                //Declares sub array
            int[] C;                //Declares sub array
            for (int x = 0; x < A.Length ; x++)     //Performs an action for every item item in the array
            {
                if (x  A.Length / 2)                //Selects the second half of the input array and assigns it to sub-Array C
                {
                    C[x] = A[x];

                }
            }

        }

Body:
You're declaring references to arrays, but never initializing them. B and C will be null and you'll get an exception if you try to do anything with them.

        //  Declares *reference* to sub array, and creates it as well.
        int[] B = new int[A.Length];

        //  Declares *reference* to sub array, and creates it as well.
        int[] C = new int[A.Length];

You could use List<int> instead of arrays.

The thing is, you'll only be using the first half of B and the second half of C. Is that what you want? If you want B to be just the first half of  A, and C to be just the last half of A, do this. You can use List<int> pretty much identically to an array, but you can Add() to it, and it has a Count property instead of a Length property:

        var B = new List<int>();
        var C = new List<int>();

        for (int x = 0; x < A.Length ; x++)     //Performs an action for every item item in the array
        {
            if (x < A.Length / 2)               //selects the first half of the input array and assigns it to sub-Array B
            {
                B.Add(A[x]);
            }
            if(x > A.Length / 2)                //Selects the second half of the input array and assigns it to sub-Array C
            {
                C.Add(A[x]);
            }
        }

Another thing: I'd put an else before the second if here, for clarity more than runtime efficiency.

But what happens if x is equal to A.Length / 2? If that case is handled in code you didn't include in your question, never mind.

            if (x < A.Length / 2)               //selects the first half of the input array and assigns it to sub-Array B
            {
                B.Add(A[x]);
            }
            else if(x > A.Length / 2)                //Selects the second half of the input array and assigns it to sub-Array C
            {
                C.Add(A[x]);
            }

You could, howerver, simplify that code as follows:

if (A.Length % 2 == 0)
{
    //  Take the first half and make an array out of that sequence
    var B = A.Take(A.Length / 2).ToArray();

    //  Skip the first half and make an array out of the remaining sequence
    var C = A.Skip(A.Length / 2).ToArray();
}

But if you're meant to be demonstrating a grasp of basic programming fundamentals rather than C# trivia, your loop method is best.