问:
Need to create Indices (Index) for Sqlite3 Database
I am using C++ - sqlite3 for creating a Database. The database is regularly updated and after point of time becomes very large in size (in GB's) which make it very slow when we execute query (via C++ syntax).

I read in sqlite site that for large Database tables we can create Index tables for optimization and speeding up database queries. I now have successfully written an index syntax just after creating my database.

```<code>sqlQuery << "CREATE INDEX IF NOT EXISTS 'IdxNode_Val' ON node_values (aliasDevice,aliasProperty,sourceTimestamp);";
int rc = sqlite3_exec(this->db, sqlQuery.str().c_str(), 0, 0, &zErrMsg);
</code>```

Query:
The question is since my database gets updated on a daily basis (new entries added), will the index table also be updated automatically or should I have to write a syntax to update the index table just after my "insert into database" syntax?

Thanks & best Regards
rG

答: The database automatically updates indexes.</p>

Body:
I am using C++ - sqlite3 for creating a Database. The database is regularly updated and after point of time becomes very large in size (in GB's) which make it very slow when we execute query (via C++ syntax).

I read in sqlite site that for large Database tables we can create Index tables for optimization and speeding up database queries. I now have successfully written an index syntax just after creating my database.

sqlQuery << "CREATE INDEX IF NOT EXISTS 'IdxNode_Val' ON node_values (aliasDevice,aliasProperty,sourceTimestamp);";
int rc = sqlite3_exec(this->db, sqlQuery.str().c_str(), 0, 0, &zErrMsg);

Query:
The question is since my database gets updated on a daily basis (new entries added), will the index table also be updated automatically or should I have to write a syntax to update the index table just after my "insert into database" syntax?

Thanks & best Regards
rG


来源: stackexchange

问:
Kafka: What happens when the entire Kafka Cluster is down?
We're testing out the Producer and Consumer using Kafka. A few questions:

What happens when all the brokers are down and they're not responding at all?

Does the Producer need to keep pinging the Kafka brokers to know when it is back up online? Or is there a more elegant way for the Producer application to know?

How does Zookeeper help in all this? What if the ZK is down as well?

答:
Producer will fail because cluster will be unavailable, this means they will get a non retriable error from kafka client implementation and depending on your client process, message will buffer on the local send queue of your application.

I'm sure that if zookeeper is down your system will not work anymore. This is one of the weakness of Kafka, he need zookeeper to work.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to set up the configuration file in camera calibration source code from OpenCV?
Im using the camera calibration source code from OpenCV in this link http://docs.opencv.org/2.4/doc/tutorials/calib3d/camera_calibration/camera_calibration.html

In the configuration file may choose to use camera as an input, a video file or an image list.I would like to use the last option . So I tried to create a configuration file where I enumerate the images to use.

Here’s my configuration file .

```<code><?xml version="1.0"?>
-<opencv_storage>
<images> C:\Users\admin\Desktop\Images\img1.png C:\Users\admin\Desktop\Images\img2.png  C:\Users\admin\Desktop\Images\im3.png  C:\Users\admin\Desktop\Images\img4.png  C:\Users\admin\Desktop\Images\img5.png C:\Users\admin\Desktop\Images\img6.png  C:\Users\admin\Desktop\Images\img7.png C:\Users\admin\Desktop\Images\img8.png  </images>
</opencv_storage>
</code>```

So far I understand the config file in Visual Studio 2012 need to be specified with Right click on Project-> Properties-> Configuration->Configuration Properties, Debugging then Command Argument where I put the name of the config file. Then I placed the the config.xml file the project source file in Visual Studio 2012. But when run the code I code this error come in command window:

```<code>Could not open the configuration file:config.xml
</code>```

Any help?

答: Isn't that "-" before  the problem? I am pretty sure that shouldn't be there</p>

Body:
Im using the camera calibration source code from OpenCV in this link http://docs.opencv.org/2.4/doc/tutorials/calib3d/camera_calibration/camera_calibration.html

In the configuration file may choose to use camera as an input, a video file or an image list.I would like to use the last option . So I tried to create a configuration file where I enumerate the images to use.

Here’s my configuration file .

<?xml version="1.0"?>
-<opencv_storage>
<images> C:\Users\admin\Desktop\Images\img1.png C:\Users\admin\Desktop\Images\img2.png  C:\Users\admin\Desktop\Images\im3.png  C:\Users\admin\Desktop\Images\img4.png  C:\Users\admin\Desktop\Images\img5.png C:\Users\admin\Desktop\Images\img6.png  C:\Users\admin\Desktop\Images\img7.png C:\Users\admin\Desktop\Images\img8.png  </images>
</opencv_storage>

So far I understand the config file in Visual Studio 2012 need to be specified with Right click on Project-> Properties-> Configuration->Configuration Properties, Debugging then Command Argument where I put the name of the config file. Then I placed the the config.xml file the project source file in Visual Studio 2012. But when run the code I code this error come in command window:

Could not open the configuration file:config.xml

Any help?


问:
Program throwing OperationCanceledException despite catching it
I'm trying to use Tokens to cancel Task started by Task.Run. I took pattern from microsoft site: https://msdn.microsoft.com/pl-pl/library/hh160373(v=vs.110).aspx

This is my code:

```<code>public static class Sender
{

    public static async Task sendData(NetworkController nc) {
        await Task.Run(() => {
            IPEndPoint endPoint = new IPEndPoint(nc.serverIp, nc.dataPort);
            byte[] end = Encoding.ASCII.GetBytes("end");
            while (true) {
                if (Painting.pointsQueue.Count > 0 && !nc.paintingSenderToken.IsCancellationRequested) {

                    byte[] sendbuf = Encoding.ASCII.GetBytes(Painting.color.ToString());
                    nc.socket.SendTo(sendbuf, endPoint);

                    do {
                        sendbuf = Painting.pointsQueue.Take();
                        nc.socket.SendTo(sendbuf, endPoint);
                    } while (sendbuf != end && !nc.paintingSenderToken.IsCancellationRequested);

                }
                else if (nc.paintingSenderToken.IsCancellationRequested) {
                    nc.paintingSenderToken.ThrowIfCancellationRequested();
                    return;
                }
            }
        }, nc.paintingSenderToken);
    }
}
</code>```

And here I start this task:

```<code>    public void stopController() {
        try {
            paintingSenderTokenSource.Cancel();
            senderTask.Wait();
        } catch(AggregateException e) {
            string message = "";
            foreach (var ie in e.InnerExceptions)
                message += ie.GetType().Name + ": " + ie.Message + "\n";
            MessageBox.Show(message, "Przerwano wysylanie");
        }
        finally {
            paintingSenderTokenSource.Dispose();
            byte[] message = Encoding.ASCII.GetBytes("disconnect");
            IPEndPoint endPoint = new IPEndPoint(serverIp, serverPort);
            socket.SendTo(message, endPoint);
            socket.Close();
            mw.setStatus("disconnected");
        }

    }

    public async void initialize() {
        Task t = Reciver.waitForRespond(this);
        sendMessage("connect");
        mw.setStatus("connecting");
        if (await Task.WhenAny(t, Task.Delay(5000)) == t) {
            mw.setStatus("connected");
            Painting.pointsQueue = new System.Collections.Concurrent.BlockingCollection<byte[]>();
            senderTask = Sender.sendData(this);
        }
        else {
            mw.setStatus("failed");
        }
    }
}
</code>```

In initialize() method I'm waiting for the response from the server and if I get it I start new thread in this sendData() method. It is in static class to make code cleaner. If I want to stop this thread I call stopController() method. In microsoft site we can read:

The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task.Wait method.

But my program breaks onnc.paintingSenderToken.ThrowIfCancellationRequested(); which is in 'sendData()' method and the error says that OperationCanceledException was not handled. I started program from microsoft site and it works perfectly. I think I'm doing everything like they did but unfortunately it doesnt't work like it should.

答:
You may have "Enable Just My Code" enabled.
To find the settings go to:

Tools => Options => Debugging => General => Enable Just My Code

If this checkbox is checked could you un-check it and then run your application again.

Body:
I'm trying to use Tokens to cancel Task started by Task.Run. I took pattern from microsoft site: https://msdn.microsoft.com/pl-pl/library/hh160373(v=vs.110).aspx

This is my code:

public static class Sender
{

    public static async Task sendData(NetworkController nc) {
        await Task.Run(() => {
            IPEndPoint endPoint = new IPEndPoint(nc.serverIp, nc.dataPort);
            byte[] end = Encoding.ASCII.GetBytes("end");
            while (true) {
                if (Painting.pointsQueue.Count > 0 && !nc.paintingSenderToken.IsCancellationRequested) {

                    byte[] sendbuf = Encoding.ASCII.GetBytes(Painting.color.ToString());
                    nc.socket.SendTo(sendbuf, endPoint);

                    do {
                        sendbuf = Painting.pointsQueue.Take();
                        nc.socket.SendTo(sendbuf, endPoint);
                    } while (sendbuf != end && !nc.paintingSenderToken.IsCancellationRequested);

                }
                else if (nc.paintingSenderToken.IsCancellationRequested) {
                    nc.paintingSenderToken.ThrowIfCancellationRequested();
                    return;
                }
            }
        }, nc.paintingSenderToken);
    }
}

And here I start this task:

    public void stopController() {
        try {
            paintingSenderTokenSource.Cancel();
            senderTask.Wait();
        } catch(AggregateException e) {
            string message = "";
            foreach (var ie in e.InnerExceptions)
                message += ie.GetType().Name + ": " + ie.Message + "\n";
            MessageBox.Show(message, "Przerwano wysylanie");
        }
        finally {
            paintingSenderTokenSource.Dispose();
            byte[] message = Encoding.ASCII.GetBytes("disconnect");
            IPEndPoint endPoint = new IPEndPoint(serverIp, serverPort);
            socket.SendTo(message, endPoint);
            socket.Close();
            mw.setStatus("disconnected");
        }

    }

    public async void initialize() {
        Task t = Reciver.waitForRespond(this);
        sendMessage("connect");
        mw.setStatus("connecting");
        if (await Task.WhenAny(t, Task.Delay(5000)) == t) {
            mw.setStatus("connected");
            Painting.pointsQueue = new System.Collections.Concurrent.BlockingCollection<byte[]>();
            senderTask = Sender.sendData(this);
        }
        else {
            mw.setStatus("failed");
        }
    }
}

In initialize() method I'm waiting for the response from the server and if I get it I start new thread in this sendData() method. It is in static class to make code cleaner. If I want to stop this thread I call stopController() method. In microsoft site we can read:

The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task.Wait method.

But my program breaks onnc.paintingSenderToken.ThrowIfCancellationRequested(); which is in 'sendData()' method and the error says that OperationCanceledException was not handled. I started program from microsoft site and it works perfectly. I think I'm doing everything like they did but unfortunately it doesnt't work like it should.


问:
Cordova build for iOS - No profile found
I am confronted with a cordova builds on MacOS. The builds work fine for Android, but building iOS is really painful. Here is what happens:

```<code>>cordova build ios --device --debug --buildConfig ./build.json
.....
Check dependencies
No profile matching '******' found:  Xcode couldn't find a profile matching '******'. Install the profile (by dragging and dropping it onto Xcode's dock item) or select a different one in the General tab of the target editor.
Code signing is required for product type 'Application' in SDK 'iOS 10.2'
</code>```

This is a fresh install of latest versions of everything (node, cordova, cordova-ios, XCode, etc). I have everything set in terms of developer id, team, certificates and provisioning profiles. All those artifacts are valid and I know for sure because I am moving this build from Intel XDK into my local Mac computer. Here is my build.json:

```<code>{
    "ios": {
        "debug": {
            "provisioningProfile": "******",
            "developmentTeam": "******",
            "packageType": "development"
        },
        "release": {
            "provisioningProfile": "******",
            "developmentTeam": "*******",
            "packageType": "app-store"
        }
    }
}
</code>```

I can see all my provisioning profiles in XCode account preferences. I also see them in /Users/me/Library/MobileDevices/Provisioning Profiles folder. I've opened XCode project and adjusted the code signing for project and target in Build Settings and General tabs. The provisioning profiles are there, the team ID is there.

All I need now is to make cordova command line work.

So, how can I make cordova and XCode to cooperate? Where does it look for those profiles and why can't it find them? What gives?

答:
I've almost given up on this, but then..  magic happened.

Everything have fixed itself by upgrading Cordova to 7.0.1, MacOS to 10.12.5 and XCode to 8.3.2.

Frankly, I have no idea what was broken, the primary suspect is XCode - the most scary development environment in the universe.

Body:
I am confronted with a cordova builds on MacOS. The builds work fine for Android, but building iOS is really painful. Here is what happens:

>cordova build ios --device --debug --buildConfig ./build.json
.....
Check dependencies
No profile matching '******' found:  Xcode couldn't find a profile matching '******'. Install the profile (by dragging and dropping it onto Xcode's dock item) or select a different one in the General tab of the target editor.
Code signing is required for product type 'Application' in SDK 'iOS 10.2'

This is a fresh install of latest versions of everything (node, cordova, cordova-ios, XCode, etc). I have everything set in terms of developer id, team, certificates and provisioning profiles. All those artifacts are valid and I know for sure because I am moving this build from Intel XDK into my local Mac computer. Here is my build.json:

{
    "ios": {
        "debug": {
            "provisioningProfile": "******",
            "developmentTeam": "******",
            "packageType": "development"
        },
        "release": {
            "provisioningProfile": "******",
            "developmentTeam": "*******",
            "packageType": "app-store"
        }
    }
}

I can see all my provisioning profiles in XCode account preferences. I also see them in /Users/me/Library/MobileDevices/Provisioning Profiles folder. I've opened XCode project and adjusted the code signing for project and target in Build Settings and General tabs. The provisioning profiles are there, the team ID is there.

All I need now is to make cordova command line work.

So, how can I make cordova and XCode to cooperate? Where does it look for those profiles and why can't it find them? What gives?


问:
Python regex capture issue
I have a regex expression that captures the text from a text file. The regex can ve viewed at the following URL:
https://regex101.com/r/wwEjTF/1

In my python code I would like extract the text that is matched by the regex only from all the other text in the text file.
I have following python code for matching th regex and storing it in a variable.

```<code>match = re.findall(r'test\s.+\n\sdescription\s\"(.+)\"', text, re.S)
</code>```

I am expecting all the matches to be in the match variable and returned a list.
But when I do print (match) I get empty list. I do not understand why it is coming up an empty list. How do i capture the matched part of the regex into the variable.
Thanks for your help.
Just in case if there is an issue with the above url, is the regex and the sample text string:

```<code>test\s.+\n\sdescription\s\"(.+)\"
</code>```

```<code>some random text
test 111.333.555.666
  description "text10"
some random text
some random text
test 22.44.55.66
  description "text12"
some random text
some random text
test 77.77.88.99
  description "text13"
some random text
some random text
test 14.22.55.99
  description "text16"
some random text
some random text
test 13.33.55.66
  description "text17"
some random text`
</code>```

答:
Like I said in my comment try omitting re.S because It makes the '.' special character match any character at all, including a newline

Also \n\s is not appropriate. As \s includes newline. You will have to use \s+

Your regex will be:

```<code>match = re.findall(r'test\s.+\s+description\s\"(.+)\"', text)
</code>```

Ideone Demo

Title: Python regex capture issue

Body:
I have a regex expression that captures the text from a text file. The regex can ve viewed at the following URL:
https://regex101.com/r/wwEjTF/1

In my python code I would like extract the text that is matched by the regex only from all the other text in the text file.
I have following python code for matching th regex and storing it in a variable.

match = re.findall(r'test\s.+\n\sdescription\s\"(.+)\"', text, re.S)

I am expecting all the matches to be in the match variable and returned a list.
But when I do print (match) I get empty list. I do not understand why it is coming up an empty list. How do i capture the matched part of the regex into the variable.
Thanks for your help.
Just in case if there is an issue with the above url, is the regex and the sample text string:

test\s.+\n\sdescription\s\"(.+)\"

some random text
test 111.333.555.666
  description "text10"
some random text
some random text
test 22.44.55.66
  description "text12"
some random text
some random text
test 77.77.88.99
  description "text13"
some random text
some random text
test 14.22.55.99
  description "text16"
some random text
some random text
test 13.33.55.66
  description "text17"
some random text`

Body:
Like I said in my comment try omitting re.S because It makes the '.' special character match any character at all, including a newline

Also \n\s is not appropriate. As \s includes newline. You will have to use \s+

Your regex will be:

match = re.findall(r'test\s.+\s+description\s\"(.+)\"', text)

Ideone Demo


问:
null is not an object
i am trying to get stored value from the AsyncStorage. but it gives null is not an object error.
here is my code.

```<code>import React, { Component } from 'react';
import { AsyncStorage, Image, View, StatusBar } from 'react-native';
import { connect } from 'react-redux';
import { Container, Button, H3, Text, Header, Title, Content, Icon, Footer, FooterTab, Left, Right, Body } from 'native-base';

import { openDrawer } from '../../actions/drawer';
import styles from './styles';
import Anatomy from '../anatomy/index.js';

const launchscreenBg = require('../../../img/abc.png');
const launchscreenLogo = require('../../../img/mob_app_bg.png');

var STORAGE_KEY_USER = '@ExpLocal:user';

class Home extends Component { // eslint-disable-line

  componentDidMount() {
    this._loadInitialState().done();
  }

  async _loadInitialState() {
    try {
      var user = await AsyncStorage.getItem(STORAGE_KEY_USER);
      if (user !== null){
        this.setState({selectedUser: user});
        this._appendMessage('Logged In User: ' + user);
      } else {
        this._appendMessage('Empty');
      }
    } catch (error) {
      this._appendMessage('AsyncStorage error: ' + error.message);
    }
  }

  getInitialState() {
    return {
      selectedUser: null,
      messages: [],
    };
  }

  static propTypes = {
    openDrawer: React.PropTypes.func,
  }

  render() {
    this._loadInitialState().done();
    // var loggedUser = this.state.selectedUser;
    if(this.state.selectedUser !== null){
      return (
        <Container style={styles.container}>
        <Header>
        <Left>
        <Button transparent onPress={this.props.openDrawer}>
        <Icon name="ios-menu" />
        </Button>
        </Left>
        <Body>
        <Title>Home</Title>
        </Body>
        <Right />
        </Header>
        </Container>
        );
    }else{
      return (
        <Anatomy />
        );
    }

  }
}

function bindActions(dispatch) {
  return {
    openDrawer: () => dispatch(openDrawer()),
  };
}

const mapStateToProps = state => ({
  navigation: state.cardNavigation,
  themeState: state.drawer.themeState,
  routes: state.drawer.routes,
});

export default connect(mapStateToProps, bindActions)(Home);
</code>```

gives following error
null is not an object (evaluating 'this.state.selectedUser')
 E:\REACT_NATIVE_PROJECTS\NativeBase-KitchenSink-master\js\components\home\index.js:49:18
What do i do wrong?

答:
You can just check if the variable has in fact value or not. In other words

```<code>if( value ) {}
</code>```

Where you get true if there's value or false if there is no.

Title: null is not an object

Body:
i am trying to get stored value from the AsyncStorage. but it gives null is not an object error.
here is my code.

import React, { Component } from 'react';
import { AsyncStorage, Image, View, StatusBar } from 'react-native';
import { connect } from 'react-redux';
import { Container, Button, H3, Text, Header, Title, Content, Icon, Footer, FooterTab, Left, Right, Body } from 'native-base';

import { openDrawer } from '../../actions/drawer';
import styles from './styles';
import Anatomy from '../anatomy/index.js';

const launchscreenBg = require('../../../img/abc.png');
const launchscreenLogo = require('../../../img/mob_app_bg.png');

var STORAGE_KEY_USER = '@ExpLocal:user';

class Home extends Component { // eslint-disable-line

  componentDidMount() {
    this._loadInitialState().done();
  }

  async _loadInitialState() {
    try {
      var user = await AsyncStorage.getItem(STORAGE_KEY_USER);
      if (user !== null){
        this.setState({selectedUser: user});
        this._appendMessage('Logged In User: ' + user);
      } else {
        this._appendMessage('Empty');
      }
    } catch (error) {
      this._appendMessage('AsyncStorage error: ' + error.message);
    }
  }

  getInitialState() {
    return {
      selectedUser: null,
      messages: [],
    };
  }

  static propTypes = {
    openDrawer: React.PropTypes.func,
  }

  render() {
    this._loadInitialState().done();
    // var loggedUser = this.state.selectedUser;
    if(this.state.selectedUser !== null){
      return (
        <Container style={styles.container}>

        <Left>
        <Button transparent onPress={this.props.openDrawer}>
        <Icon name="ios-menu" />
        </Button>
        </Left>

        <Title>Home</Title>

        <Right />

        </Container>
        );
    }else{
      return (
        <Anatomy />
        );
    }

  }
}

function bindActions(dispatch) {
  return {
    openDrawer: () => dispatch(openDrawer()),
  };
}

const mapStateToProps = state => ({
  navigation: state.cardNavigation,
  themeState: state.drawer.themeState,
  routes: state.drawer.routes,
});

export default connect(mapStateToProps, bindActions)(Home);

gives following error
null is not an object (evaluating 'this.state.selectedUser')
 E:\REACT_NATIVE_PROJECTS\NativeBase-KitchenSink-master\js\components\home\index.js:49:18
What do i do wrong?

Body:
You can just check if the variable has in fact value or not. In other words

if( value ) {}

Where you get true if there's value or false if there is no.


问:
Simple one dimension array of float with numpy
I want to make a simple one-dimensional array with numpy.

```<code>import numpy as np
arr = np.array()  # how do I initialize a float array?

np.append(arr, "3453.2")
np.append(arr, "1321.3")
np.append(arr, "2003.6")
</code>```

I have tried np.zeros(), np.ones(), np.empty() and so on. But I can't find out how to initialize an empty array.

答:
Array from list of floats:

```<code>arr = np.array([1., 2., 3.])
</code>```

Empty array:

```<code>arr = np.empty(shape=())
print(arr.shape)  # ()
</code>```

Empty 1d-array:

```<code>arr = np.empty(shape(1,))
print(arr.shape)  # (1,)
</code>```

It's unclear what you really want.

Read the docs about array-creation.

Important remark: don't overuse append and co. / don't resize array's often! This calls for bad performance because of copying of data! That's not how numpy-array should be used.

Build a list (where append is fast) and then build an array when the list is ready. Research append on lists vs. arrays for the reasons!

Like:

```<code>l = []
l.append(1.)
l.append(2.)
arr = np.array(l)
</code>```

Body:
I want to make a simple one-dimensional array with numpy.

import numpy as np
arr = np.array()  # how do I initialize a float array?

np.append(arr, "3453.2")
np.append(arr, "1321.3")
np.append(arr, "2003.6")

I have tried np.zeros(), np.ones(), np.empty() and so on. But I can't find out how to initialize an empty array.

Body:
Array from list of floats:

arr = np.array([1., 2., 3.])

Empty array:

arr = np.empty(shape=())
print(arr.shape)  # ()

Empty 1d-array:

arr = np.empty(shape(1,))
print(arr.shape)  # (1,)

It's unclear what you really want.

Read the docs about array-creation.

Important remark: don't overuse append and co. / don't resize array's often! This calls for bad performance because of copying of data! That's not how numpy-array should be used.

Build a list (where append is fast) and then build an array when the list is ready. Research append on lists vs. arrays for the reasons!

Like:

l = []
l.append(1.)
l.append(2.)
arr = np.array(l)


问:
Excel VBA - Adjusting a formula to let VBA loop it
I have following formula

=IF(Matching_Sheet!F3=0;"";Matching_Sheet!F3)

I want to let VBA fill in the B column of a sheet with this formula adjusted to the respective column number. I have tried this

```<code>For x = 2 To destMaxRow
Range("$B$" & x).FormulaLocal = "=IF(Matching_Sheet!$F$=0;" & x & Chr(34) & Chr(34) & ";Matching_Sheet!$F$)" & x
Next
</code>```

Unfortunately, this form apparently has a mistake but I cannot figure out what it is.

Any help would be appreciated. Thanks in advance.

答:
Not sure, try this

```<code>For x = 2 To destMaxRow
  Range("$B$" & x).FormulaLocal = "=IF(Matching_Sheet!$F$" & x & "=0;" & Chr(34) & Chr(34) & ";Matching_Sheet!$F$" & x & ")"
Next
</code>```

Which I think could be shortened to (obviating need for a loop)

```<code>Range("$B$2:B" & destMaxRow).FormulaLocal = "=IF(Matching_Sheet!$F2=0;" & Chr(34) & Chr(34) & ";Matching_Sheet!$F2)"
</code>```

Body:
I have following formula

=IF(Matching_Sheet!F3=0;"";Matching_Sheet!F3)

I want to let VBA fill in the B column of a sheet with this formula adjusted to the respective column number. I have tried this

For x = 2 To destMaxRow
Range("$B$" & x).FormulaLocal = "=IF(Matching_Sheet!$F$=0;" & x & Chr(34) & Chr(34) & ";Matching_Sheet!$F$)" & x
Next

Unfortunately, this form apparently has a mistake but I cannot figure out what it is.

Any help would be appreciated. Thanks in advance.

Body:
Not sure, try this

For x = 2 To destMaxRow
  Range("$B$" & x).FormulaLocal = "=IF(Matching_Sheet!$F$" & x & "=0;" & Chr(34) & Chr(34) & ";Matching_Sheet!$F$" & x & ")"
Next

Which I think could be shortened to (obviating need for a loop)

Range("$B$2:B" & destMaxRow).FormulaLocal = "=IF(Matching_Sheet!$F2=0;" & Chr(34) & Chr(34) & ";Matching_Sheet!$F2)"


问:
MessageDrivenBean: AMQ122000: I''m closing a JMS connection you left open
when sending some messages via a MDB there are some warnings about unclosed JMS connections which then are closed by ActiveMQ.
The MDB gets a messageHandler injected which gets a replysender injected whichs method is given below.

This is the warning I do get:

```<code>[org.apache.activemq.artemis.jms.client] (Finalizer) AMQ122000: I''m closing a JMS connection you left open. Please make sure you close all JMS connections explicitly before letting them go out of scope! see stacktrace to find out where it was created: java.lang.Exception
at org.apache.activemq.artemis.jms.client.ActiveMQConnection.<init>(ActiveMQConnection.java:155)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnectionInternal(ActiveMQConnectionFactory.java:750)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:233)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:229)
[...]
</code>```

The warning occurs (not every time) within the following code when the try-block has finished (so directly after log.debug(..)):

```<code>    private Message doSendAndReturn(XmlMessageCreator messageCreator) throws JMSException {
    Message message = null;
    try (Session session = cf.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);) {
        MessageProducer producer = session.createProducer(jmsReplyQueue);
        message = messageCreator.createMessage(session);

        producer.send(message);
        log.debug("JMSTemplate sended message to myEnvironment with ID "
                + message.getJMSMessageID()
                + "\n Using Thread "
                + Thread.currentThread().getName());
    }
    return message;
}
</code>```

I still read that these warnings also occur when theres no reference to the connection factory but "cf" is a global singleton variable which is defined via the context:

```<code>    @Resource(lookup = "java:/myProject_myEnvironment_factory")
private ConnectionFactory cf;
</code>```

When setting a break-point on log.debug(...) I can see that it seems to work some times but sometimes not. This method is called about 7 times while the first three times work, then one time throws the warning four times (probably also for every previous call) and so on for a few times.
This is reproducable every time I do a specific task within the webapp.

I do not know whats going wrong here.

Any advice would be grateful. Thanks in advance.

答:
I think the problem is that although the session object is defined in the try-with-resource part but there is no explicit variable for the connection within the try-with-resource part.

After changing it from:

```<code> try (Session session = cf.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);) {
</code>```

to:

```<code> try (
            Connection connection = cf.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        ) {
</code>```

I am not getting the warnings any more.
Thanks for listening.

Body:
when sending some messages via a MDB there are some warnings about unclosed JMS connections which then are closed by ActiveMQ.
The MDB gets a messageHandler injected which gets a replysender injected whichs method is given below.

This is the warning I do get:

[org.apache.activemq.artemis.jms.client] (Finalizer) AMQ122000: I''m closing a JMS connection you left open. Please make sure you close all JMS connections explicitly before letting them go out of scope! see stacktrace to find out where it was created: java.lang.Exception
at org.apache.activemq.artemis.jms.client.ActiveMQConnection.<init>(ActiveMQConnection.java:155)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnectionInternal(ActiveMQConnectionFactory.java:750)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:233)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:229)
[...]

The warning occurs (not every time) within the following code when the try-block has finished (so directly after log.debug(..)):

    private Message doSendAndReturn(XmlMessageCreator messageCreator) throws JMSException {
    Message message = null;
    try (Session session = cf.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);) {
        MessageProducer producer = session.createProducer(jmsReplyQueue);
        message = messageCreator.createMessage(session);

        producer.send(message);
        log.debug("JMSTemplate sended message to myEnvironment with ID "
                + message.getJMSMessageID()
                + "\n Using Thread "
                + Thread.currentThread().getName());
    }
    return message;
}

I still read that these warnings also occur when theres no reference to the connection factory but "cf" is a global singleton variable which is defined via the context:

    @Resource(lookup = "java:/myProject_myEnvironment_factory")
private ConnectionFactory cf;

When setting a break-point on log.debug(...) I can see that it seems to work some times but sometimes not. This method is called about 7 times while the first three times work, then one time throws the warning four times (probably also for every previous call) and so on for a few times.
This is reproducable every time I do a specific task within the webapp.

I do not know whats going wrong here.

Any advice would be grateful. Thanks in advance.

Body:
I think the problem is that although the session object is defined in the try-with-resource part but there is no explicit variable for the connection within the try-with-resource part.

After changing it from:

 try (Session session = cf.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);) {

to:

 try (
            Connection connection = cf.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        ) {

I am not getting the warnings any more.
Thanks for listening.


问:
How to save product image as in PNG extension in prestashop 1.7
In Prestashop 1.7 all the images save as "jpg" format. I want to save all the product image as PNG format. Am a new to prestashop, Please anybody help me to save the images as PNG format.

Thanks,

答:
In your backoffice go to Design -> Image Settings the scroll down until you see the box with this title 'IMAGES GENERATION OPTIONS', then change the Image format option, click on:
 Use PNG only if the base image is in PNG format.
 or
 Use PNG for all images.
then click save :).

Now the images will saved in PNG format ;)


问:
How did I generate all these extra files during git mergetool and how do I get rid of them?
I just setup my new git repo with p4merge setup as my external git mergetool. I'm on Mac and I just followed the git tutorial for external mergetools:

https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

I worked through my merge conflicts, and I noticed it seemed to be keeping a separate instance of p4merge open for each new class conflict I opened up. In my old repo I would just hit save, close the window and git would automatically open up the next conflict (I was also on Windows at the time). Now doing so seemed to only result in the save persisting half the time, and I was having to keep entering 'git mergetool' into the terminal to get back into p4merge. After I got everything done my branch was clean but I had all these separate processes for p4merge still open. Closing them all out threw a bunch of errors in the command line and then I ended up with a TON of base/local/remote artifacts. Now the status of my branch looks something like this:

```<code>modified:   src/main/java/com/utils/ClientResponseUtils.java.orig
    deleted:    src/main/java/com/utils/ClientResponseUtils_BACKUP_70929.java
    deleted:    src/main/java/com/utils/ClientResponseUtils_BASE_70929.java
    deleted:    src/main/java/com/utils/ClientResponseUtils_LOCAL_70929.java
    deleted:    src/main/java/com/utils/ClientResponseUtils_REMOTE_70929.java
    modified:   src/main/java/com/utils/ListUtils.java.orig
    deleted:    src/main/java/com/utils/ListUtils_BACKUP_85524.java
    deleted:    src/main/java/com/utils/ListUtils_BASE_85524.java
    deleted:    src/main/java/com/utils/ListUtils_LOCAL_85524.java
    deleted:    src/main/java/com/utils/ListUtils_REMOTE_85524.java
</code>```

Except MUCH, MUCH longer, it basically has a set of these for everything that I touched, and that was a lot of classes in the merge.

How do I go through this quickly without having to rm each one individually, and how do I prevent this from happening again in the future?

Looking a little further before posting, I realize this support page might help me clean up my command line usage:

http://answers.perforce.com/articles/KB/2848/

But I'm still wondering the best way to clean up such a horrible and lengthy mess, and why it happened in the first place.

答:
This will help

```<code>git config --global mergetool.keepBackup false
</code>```

If you are mainly concerned with not committing the files, you can add them to .gitignore:

```<code>*_BACKUP_*
*_BASE_*
*_LOCAL_*
*_REMOTE_*
</code>```

And you can occasionally run git clean -fx to remove them all

Body:
I just setup my new git repo with p4merge setup as my external git mergetool. I'm on Mac and I just followed the git tutorial for external mergetools:

https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

I worked through my merge conflicts, and I noticed it seemed to be keeping a separate instance of p4merge open for each new class conflict I opened up. In my old repo I would just hit save, close the window and git would automatically open up the next conflict (I was also on Windows at the time). Now doing so seemed to only result in the save persisting half the time, and I was having to keep entering 'git mergetool' into the terminal to get back into p4merge. After I got everything done my branch was clean but I had all these separate processes for p4merge still open. Closing them all out threw a bunch of errors in the command line and then I ended up with a TON of base/local/remote artifacts. Now the status of my branch looks something like this:

modified:   src/main/java/com/utils/ClientResponseUtils.java.orig
    deleted:    src/main/java/com/utils/ClientResponseUtils_BACKUP_70929.java
    deleted:    src/main/java/com/utils/ClientResponseUtils_BASE_70929.java
    deleted:    src/main/java/com/utils/ClientResponseUtils_LOCAL_70929.java
    deleted:    src/main/java/com/utils/ClientResponseUtils_REMOTE_70929.java
    modified:   src/main/java/com/utils/ListUtils.java.orig
    deleted:    src/main/java/com/utils/ListUtils_BACKUP_85524.java
    deleted:    src/main/java/com/utils/ListUtils_BASE_85524.java
    deleted:    src/main/java/com/utils/ListUtils_LOCAL_85524.java
    deleted:    src/main/java/com/utils/ListUtils_REMOTE_85524.java

Except MUCH, MUCH longer, it basically has a set of these for everything that I touched, and that was a lot of classes in the merge.

How do I go through this quickly without having to rm each one individually, and how do I prevent this from happening again in the future?

Looking a little further before posting, I realize this support page might help me clean up my command line usage:

http://answers.perforce.com/articles/KB/2848/

But I'm still wondering the best way to clean up such a horrible and lengthy mess, and why it happened in the first place.

Body:
This will help

git config --global mergetool.keepBackup false

If you are mainly concerned with not committing the files, you can add them to .gitignore:

*_BACKUP_*
*_BASE_*
*_LOCAL_*
*_REMOTE_*

And you can occasionally run git clean -fx to remove them all


问:
Mix_PlayMusic causing memory corruption
I've been having trouble with a game I've been working on, where once I added music it started segfaulting in my frequently-called texture-loading code, between 5-30 secs after it started playing. The best I could come up with was that it is some sort of memory corruption. After a good week of unsuccessfully trying to debug it (trying things like GFlags pageheap), I managed to cut it down to the following code, which still exhibits the problem.

Sometimes this segfaults with the callstack going through SDL2_mixer.dll, but mostly it occurs in the SDL_CreateTextureFromSurface call, due to the renderer being in a bad state. numTextures gets to between 15000-40000 on my machine (Windows 10 x64, with program compiled for x86).

My gut tells me that there's an issue in my environment or code, rather than an issue in SDL itself, but I'm at a loss. Any help or insights would be greatly appreciated.

```<code>#include <SDL_image.h>
#include <SDL_mixer.h>
#include <cassert>

int main(int argc, char* argv[])
{
    assert(SDL_Init(SDL_INIT_EVERYTHING) == 0);

    SDL_Window * pWindow_ = SDL_CreateWindow(
        "", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0x0);
    assert(pWindow_ != nullptr);

    SDL_Renderer * pRenderer_ = SDL_CreateRenderer(pWindow_, -1, 0);
    assert(pRenderer_ != nullptr);

    assert(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 512) == 0);

    Mix_Music * pMusic = Mix_LoadMUS("sounds/tranquility.wav");
    assert(pMusic != nullptr);
    assert(Mix_PlayMusic(pMusic, -1) == 0);

    SDL_Surface * pSurface = IMG_Load("images/caution.png");
    assert(pSurface != nullptr);
    SDL_Texture * pTexture = SDL_CreateTextureFromSurface(pRenderer_, pSurface);
    assert(pTexture != nullptr);

    int numTextures = 0;
    while (true)
    {
        numTextures += 10;
        assert(pTexture != nullptr);
        SDL_DestroyTexture(pTexture);
        pTexture = SDL_CreateTextureFromSurface(pRenderer_, pSurface);
        assert(pTexture != nullptr);
    }
}
</code>```

答:
The solution turned out to be to update to the latest version of SDL (2.0.3 -> 2.0.5).

I started developing the project in question with an engine code base which I upgraded from SDL 1.2 to 2.0 about 2 years ago, when the latest version was 2.0.3.

When I recently added sound and music, I took the latest SDL_mixer, and didn't think to update SDL to the latest 2.0.5.

After getting the latest development and runtime libraries for SDL (and SDL_image and SDL_mixer for good measure), the problem disappeared.

I'm not entirely satisfied with this. I'm quite surprised that the newer SDL_mixer linked successfully with an older SDL, if they were not compatible. In addition, I can't find any resources online that suggest any compatibility issues. Therefore, I have an uneasy feeling there may have been something else going on, which was resolved incidentally by the upgrade.

Title: Mix_PlayMusic causing memory corruption

Body:
I've been having trouble with a game I've been working on, where once I added music it started segfaulting in my frequently-called texture-loading code, between 5-30 secs after it started playing. The best I could come up with was that it is some sort of memory corruption. After a good week of unsuccessfully trying to debug it (trying things like GFlags pageheap), I managed to cut it down to the following code, which still exhibits the problem.

Sometimes this segfaults with the callstack going through SDL2_mixer.dll, but mostly it occurs in the SDL_CreateTextureFromSurface call, due to the renderer being in a bad state. numTextures gets to between 15000-40000 on my machine (Windows 10 x64, with program compiled for x86).

My gut tells me that there's an issue in my environment or code, rather than an issue in SDL itself, but I'm at a loss. Any help or insights would be greatly appreciated.

#include <SDL_image.h>
#include <SDL_mixer.h>
#include <cassert>

int main(int argc, char* argv[])
{
    assert(SDL_Init(SDL_INIT_EVERYTHING) == 0);

    SDL_Window * pWindow_ = SDL_CreateWindow(
        "", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0x0);
    assert(pWindow_ != nullptr);

    SDL_Renderer * pRenderer_ = SDL_CreateRenderer(pWindow_, -1, 0);
    assert(pRenderer_ != nullptr);

    assert(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 512) == 0);

    Mix_Music * pMusic = Mix_LoadMUS("sounds/tranquility.wav");
    assert(pMusic != nullptr);
    assert(Mix_PlayMusic(pMusic, -1) == 0);

    SDL_Surface * pSurface = IMG_Load("images/caution.png");
    assert(pSurface != nullptr);
    SDL_Texture * pTexture = SDL_CreateTextureFromSurface(pRenderer_, pSurface);
    assert(pTexture != nullptr);

    int numTextures = 0;
    while (true)
    {
        numTextures += 10;
        assert(pTexture != nullptr);
        SDL_DestroyTexture(pTexture);
        pTexture = SDL_CreateTextureFromSurface(pRenderer_, pSurface);
        assert(pTexture != nullptr);
    }
}


问:
Ansible Tower Inventory Groups from playbook
How can I reference a tower inventory group from the playbook? My playbook is calling specific roles, each role will call on a different inventory group from tower.

So far what I have tried is:

```<code>host: "{{ inventory_hostname in groups['ios'] }}"
</code>```

or

```<code>host: "ios"
</code>```

or

```<code>host: ios
</code>```

Is it just my syntax there on the templating?
I can't find any reference to this when using a tower inventory group.

I get some type of error stating could not be found, or attempting to acctually connect to "ios"

```<code>"failed to connect to ios:22"
</code>```

答:
From Ansible Tower support:

Each job template can see only one top-level inventory.  It is possible, though, to create potentially overlapping groups and sub-groups within a single inventory.  For most applications, the single inventory can be organized to provide necessary specificity.  In cases where an particular inventory grouping must be referenced in multiple job templates, it is necessary to either use the same top-level inventory in both cases, or to duplicate the inventory group to both inventories.

So you can't reference other groups in hosts, each job template only sees the inventory it was provided but you can either use Workflow to change inventories or create overlapping groups.

Body:
How can I reference a tower inventory group from the playbook? My playbook is calling specific roles, each role will call on a different inventory group from tower.

So far what I have tried is:

host: "{{ inventory_hostname in groups['ios'] }}"

or

host: "ios"

or

host: ios

Is it just my syntax there on the templating?
I can't find any reference to this when using a tower inventory group.

I get some type of error stating could not be found, or attempting to acctually connect to "ios"

"failed to connect to ios:22"


问:
Using fork() results in a memory map
I'd like to add up numbers using fork and divide-and-conquer. The idea is that i fill an array, and i'm checking it's length, using the 'left' and 'right' variables.

If the length is 1, it just returns the number, if it's 2 , it adds up that two numbers and returns their sum. If the length is more than 2, i set a 'middle' variable and cut the array into two pieces, those have two sums, and i add those together and return the final sum.

The two parts of the array are being processed by different processes, which i create with fork. The parent processes always wait for the child processes to finish, and the parent process gets the child's sum via a pipe, so they shouldn't collide, but if the number of integers to add is more than 6, it's not working. Here's the code :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int DivEtImp(int left, int right, int v[]) {
    switch (right-left) {
        case 0 : return v[left]; break;
        case 1 : return v[left]+v[right]; break;
        default : {
            int pfd[2];
            if (pipe (pfd) < 0)
                        perror("Pipe error !");
            int middle;
            middle=(left+right)/2;
            pid_t pid;
            pid = fork();
            if ( pid < 0 )
                perror("Fork error !\n");
            else {
                if ( pid == 0 ) { // Child process.
                    close(pfd[0]);
                    int s;
                    s =  DivEtImp(left,middle,v);
                    write(pfd[1],&s,sizeof(int));
                    exit(0);
                }
                else {
                    wait(NULL); // Parent process.
                    close(pfd[1]);
                    int s2,s3;
                    s2 = DivEtImp(middle+1,right,v);
                    read(pfd[0],&s3,sizeof(int));
                    return s2+s3;
                }
            }
        }
    }
}

int main() {
    int n,i,sum,a;
    int* v;
    FILE *f = fopen("input.dat","r");
    v = (int*)malloc(sizeof(int));
    fscanf(f,"%d",&n);
    for (i=0;i<n;i++) {
        fscanf(f,"%d",&a);
        v[i]=a;
    }
    fclose(f);
    sum = DivEtImp(0,n-1,v);
    f=fopen("output.dat","w");
    fprintf(f,"sum : %d\n",sum);
    fclose(f);
    free(v);
    return 0;
}
</code>```

If the input.dat looks like this :

```<code>6
1 2 3 4 5 6
</code>```

I get the result :

```<code>sum : 21
</code>```

But with an input with more numbers :

```<code>7
1 2 3 4 5 6 7
</code>```

I get this :

```<code>*** Error in `./p': munmap_chunk(): invalid pointer: 0x0000000001c73260 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7925b)[0x7f0a46c9225b]
/lib64/libc.so.6(cfree+0x1f8)[0x7f0a46c9f4c8]
/lib64/libc.so.6(_IO_setb+0x4b)[0x7f0a46c969ab]
/lib64/libc.so.6(_IO_file_close_it+0xae)[0x7f0a46c94a6e]
/lib64/libc.so.6(fclose+0x1bf)[0x7f0a46c8777f]
./p[0x400bc1]
/lib64/libc.so.6(__libc_start_main+0xf1)[0x7f0a46c39401]
./p[0x4008ca]
======= Memory map: ========
00400000-00401000 r-xp 00000000 fd:00 432360                             /home/CaTNiP/Documents/fork/p
00601000-00602000 r--p 00001000 fd:00 432360                             /home/CaTNiP/Documents/fork/p
00602000-00603000 rw-p 00002000 fd:00 432360                             /home/CaTNiP/Documents/fork/p
01c73000-01c94000 rw-p 00000000 00:00 0                                  [heap]
7f0a46a02000-7f0a46a18000 r-xp 00000000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46a18000-7f0a46c17000 ---p 00016000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46c17000-7f0a46c18000 r--p 00015000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46c18000-7f0a46c19000 rw-p 00016000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46c19000-7f0a46dd6000 r-xp 00000000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46dd6000-7f0a46fd5000 ---p 001bd000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46fd5000-7f0a46fd9000 r--p 001bc000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46fd9000-7f0a46fdb000 rw-p 001c0000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46fdb000-7f0a46fdf000 rw-p 00000000 00:00 0
7f0a46fdf000-7f0a47004000 r-xp 00000000 fd:00 269637                     /usr/lib64/ld-2.24.so
7f0a471eb000-7f0a471ed000 rw-p 00000000 00:00 0
7f0a47201000-7f0a47204000 rw-p 00000000 00:00 0
7f0a47204000-7f0a47205000 r--p 00025000 fd:00 269637                     /usr/lib64/ld-2.24.so
7f0a47205000-7f0a47206000 rw-p 00026000 fd:00 269637                     /usr/lib64/ld-2.24.so
7f0a47206000-7f0a47207000 rw-p 00000000 00:00 0
7ffce2cc4000-7ffce2ce5000 rw-p 00000000 00:00 0                          [stack]
7ffce2d75000-7ffce2d77000 r--p 00000000 00:00 0                          [vvar]
7ffce2d77000-7ffce2d79000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)
</code>```

Clearly, the code does multiple fork and pipe if the array has at least 7 elements, but i don't know which one causes the error, and how to fix it. Thanks in advance.

答:
Each (forked) process has its own virtual address space (and don't share memory by default with others).

And your

```<code>v = (int*)malloc(sizeof(int)); // wrong
</code>```

is very wrong. You should allocate a large enough v. Your current code has some buffer overflow (an instance of undefined behavior). Learn to use valgrind.

You should replace

```<code>// bad code
v = (int*)malloc(sizeof(int));
fscanf(f,"%d",&n);
</code>```

with

```<code>n=0;
if (fscanf(f, "%d", &n)<1 || ((n<0) && (errno=EINVAL)) {
    perror("fscanf n"); exit(EXIT_FAILURE);
}
v = calloc(n, sizeof(int));
if (v==NULL)  {
    perror("calloc v"); exit(EXIT_FAILURE);
}
</code>```

(I am explicitly setting errno to  EINVAL when n<0 so that perror outputs a sensible error)

FYI, see also shm_overview(7) and sem_overview(7), but in your case they are not needed. Notice that calloc is probably using mmap(2) (or sbrk).

Title: Using fork() results in a memory map

Body:
I'd like to add up numbers using fork and divide-and-conquer. The idea is that i fill an array, and i'm checking it's length, using the 'left' and 'right' variables.

If the length is 1, it just returns the number, if it's 2 , it adds up that two numbers and returns their sum. If the length is more than 2, i set a 'middle' variable and cut the array into two pieces, those have two sums, and i add those together and return the final sum.

The two parts of the array are being processed by different processes, which i create with fork. The parent processes always wait for the child processes to finish, and the parent process gets the child's sum via a pipe, so they shouldn't collide, but if the number of integers to add is more than 6, it's not working. Here's the code :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int DivEtImp(int left, int right, int v[]) {
    switch (right-left) {
        case 0 : return v[left]; break;
        case 1 : return v[left]+v[right]; break;
        default : {
            int pfd[2];
            if (pipe (pfd) < 0)
                        perror("Pipe error !");
            int middle;
            middle=(left+right)/2;
            pid_t pid;
            pid = fork();
            if ( pid < 0 )
                perror("Fork error !\n");
            else {
                if ( pid == 0 ) { // Child process.
                    close(pfd[0]);
                    int s;
                    s =  DivEtImp(left,middle,v);
                    write(pfd[1],&s,sizeof(int));
                    exit(0);
                }
                else {
                    wait(NULL); // Parent process.
                    close(pfd[1]);
                    int s2,s3;
                    s2 = DivEtImp(middle+1,right,v);
                    read(pfd[0],&s3,sizeof(int));
                    return s2+s3;
                }
            }
        }
    }
}

int main() {
    int n,i,sum,a;
    int* v;
    FILE *f = fopen("input.dat","r");
    v = (int*)malloc(sizeof(int));
    fscanf(f,"%d",&n);
    for (i=0;i<n;i++) {
        fscanf(f,"%d",&a);
        v[i]=a;
    }
    fclose(f);
    sum = DivEtImp(0,n-1,v);
    f=fopen("output.dat","w");
    fprintf(f,"sum : %d\n",sum);
    fclose(f);
    free(v);
    return 0;
}

If the input.dat looks like this :

6
1 2 3 4 5 6

I get the result :

sum : 21

But with an input with more numbers :

7
1 2 3 4 5 6 7

I get this :

*** Error in `./p': munmap_chunk(): invalid pointer: 0x0000000001c73260 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7925b)[0x7f0a46c9225b]
/lib64/libc.so.6(cfree+0x1f8)[0x7f0a46c9f4c8]
/lib64/libc.so.6(_IO_setb+0x4b)[0x7f0a46c969ab]
/lib64/libc.so.6(_IO_file_close_it+0xae)[0x7f0a46c94a6e]
/lib64/libc.so.6(fclose+0x1bf)[0x7f0a46c8777f]
./p[0x400bc1]
/lib64/libc.so.6(__libc_start_main+0xf1)[0x7f0a46c39401]
./p[0x4008ca]
======= Memory map: ========
00400000-00401000 r-xp 00000000 fd:00 432360                             /home/CaTNiP/Documents/fork/p
00601000-00602000 r--p 00001000 fd:00 432360                             /home/CaTNiP/Documents/fork/p
00602000-00603000 rw-p 00002000 fd:00 432360                             /home/CaTNiP/Documents/fork/p
01c73000-01c94000 rw-p 00000000 00:00 0                                  [heap]
7f0a46a02000-7f0a46a18000 r-xp 00000000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46a18000-7f0a46c17000 ---p 00016000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46c17000-7f0a46c18000 r--p 00015000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46c18000-7f0a46c19000 rw-p 00016000 fd:00 269994                     /usr/lib64/libgcc_s-6.2.1-20160916.so.1
7f0a46c19000-7f0a46dd6000 r-xp 00000000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46dd6000-7f0a46fd5000 ---p 001bd000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46fd5000-7f0a46fd9000 r--p 001bc000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46fd9000-7f0a46fdb000 rw-p 001c0000 fd:00 269812                     /usr/lib64/libc-2.24.so
7f0a46fdb000-7f0a46fdf000 rw-p 00000000 00:00 0
7f0a46fdf000-7f0a47004000 r-xp 00000000 fd:00 269637                     /usr/lib64/ld-2.24.so
7f0a471eb000-7f0a471ed000 rw-p 00000000 00:00 0
7f0a47201000-7f0a47204000 rw-p 00000000 00:00 0
7f0a47204000-7f0a47205000 r--p 00025000 fd:00 269637                     /usr/lib64/ld-2.24.so
7f0a47205000-7f0a47206000 rw-p 00026000 fd:00 269637                     /usr/lib64/ld-2.24.so
7f0a47206000-7f0a47207000 rw-p 00000000 00:00 0
7ffce2cc4000-7ffce2ce5000 rw-p 00000000 00:00 0                          [stack]
7ffce2d75000-7ffce2d77000 r--p 00000000 00:00 0                          [vvar]
7ffce2d77000-7ffce2d79000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)

Clearly, the code does multiple fork and pipe if the array has at least 7 elements, but i don't know which one causes the error, and how to fix it. Thanks in advance.

Body:
Each (forked) process has its own virtual address space (and don't share memory by default with others).

And your

v = (int*)malloc(sizeof(int)); // wrong

is very wrong. You should allocate a large enough v. Your current code has some buffer overflow (an instance of undefined behavior). Learn to use valgrind.

You should replace

// bad code
v = (int*)malloc(sizeof(int));
fscanf(f,"%d",&n);

with

n=0;
if (fscanf(f, "%d", &n)<1 || ((n<0) && (errno=EINVAL)) {
    perror("fscanf n"); exit(EXIT_FAILURE);
}
v = calloc(n, sizeof(int));
if (v==NULL)  {
    perror("calloc v"); exit(EXIT_FAILURE);
}

(I am explicitly setting errno to  EINVAL when n<0 so that perror outputs a sensible error)

FYI, see also shm_overview(7) and sem_overview(7), but in your case they are not needed. Notice that calloc is probably using mmap(2) (or sbrk).


问:
Issue with BackgroundWorker thread that crashes tree
I have WinForm App with tree control. I am loading tree with XML in BackgroundWorker thread. Everything works fine with small data. But tree is crashing with big data and I am not able to trace any reason.

I am getting unhandled exception and tree is not painted on form. Some details below-

```<code>//object array is used for file types, path etc.
object objArr = new object[5] { fileType, Path1, Path2, this.myWorker, returnType };
this.myWorker.WorkerReportsProgress = true;
this.myWorker.ProgressChanged += new ProgressChangedEventHandler(this.CompareWorker_ProgressChanged);
this.myWorker.DoWork += new DoWorkEventHandler(this.myWorker_DoWork);
this.myWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.myWorker_RunWorkerCompleted);
this.myWorker.RunWorkerAsync(objArr);
</code>```

myWorker_DoWork is building the tree with XML. Each node in tree is added by tree Invoke(new AddNodes(AddNode), new object[] { isChildNode, parentNode, childNode }); inside myWorker_DoWork.

答: I resolved this issue by moving out all UI updates from Background thread to UI thread. That's always good practice to perform business logic in background thread and update your UI controls in UI thread. This will never cause any issue.</p>

Body:
I have WinForm App with tree control. I am loading tree with XML in BackgroundWorker thread. Everything works fine with small data. But tree is crashing with big data and I am not able to trace any reason.

I am getting unhandled exception and tree is not painted on form. Some details below-

//object array is used for file types, path etc.
object objArr = new object[5] { fileType, Path1, Path2, this.myWorker, returnType };
this.myWorker.WorkerReportsProgress = true;
this.myWorker.ProgressChanged += new ProgressChangedEventHandler(this.CompareWorker_ProgressChanged);
this.myWorker.DoWork += new DoWorkEventHandler(this.myWorker_DoWork);
this.myWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.myWorker_RunWorkerCompleted);
this.myWorker.RunWorkerAsync(objArr);

myWorker_DoWork is building the tree with XML. Each node in tree is added by tree Invoke(new AddNodes(AddNode), new object[] { isChildNode, parentNode, childNode }); inside myWorker_DoWork.


问:
Drupal — disable CSS cache
I am using Drupal 6. Every time I modify the CSS files, I need to clear the cache to see the updated result, which is a waste of my time. Is there any way to disable the cache system?</p>

答:
The reason the CSS cache needs refreshing is because Drupal optimizes all individual CSS files from various modules and themes into one CSS file which is optimized into a single file.

So that this file is not recompiled every page load, which would loose the benefit of optimization, Drupal needs to know when the CSS file has changed in order to recompile this. At which cache refresh seems like the ideal time. To turn this off - rather than turn off caching completely you can simply:

Go to /admin/settings/performance where there is a field labeled "Optimize CSS files":

Disable this whilst you are doing your development and making changes to your CSS file. Then when in production and most of your CSS is set then you can enable it. I highly recommend the performance gains this brings in the loading of your pages.

I have the administration menu module installed, and it is very easy to empty the cache from here in a single click - have a try...

ContentLicense: CC BY-SA 2.5

Title: Drupal — disable CSS cache


问:
How many bytes does memory arbiter protect?
How many bytes does memory arbiter protect?

While reading "Understanding the linux kernel, 3rd edition" chapter 2, section2.1, I encounter the following statement:

In multiprocessor systems, all CPUs usually share the same memory; this means that RAM chips may be accessed concurrently by independent CPUs. Because read or write operations on a RAM chip must be performed serially, a hardware circuit called a memory arbiter is inserted between the bus and every RAM chip. Its role is to grant access to a CPU if the chip is free and to delay it if the chip is busy servicing a request by another processor.

Here i have some questions:

. how many bytes does a ram chip have? (Seem that this question is equal to "How many bytes does memory arbiter protect?" )

. as i said, "My PC has 1G memory". Does this means that the "1 G memory" is comprised of many ram chips.

答:
The "arbiter" is not inside the RAM chips; it's a part of memory coherency stuff, nowadays probably inside the CPU chips.

As for granularity - I'd guess it's L3 cacheline, so usually 64 bytes.


问:
How do I use the ebook functions epub_book and kindlegen() for existing bookdown documents?
I've found a couple bookdown documents on github (namely Hadley's R for Data Science and Efficient R) that I'd like to build from source as ebooks. Bookdown, which the documents are written in, has a couple functions, namely epub_book() and kindlegen() to build a ebook (rather than github book site), which I'd like to use so I can read the books on my Kindle.

I've looked at the bookdown documentation for those functions, but I don't understand how/where to use those functions to build the ebook files and/or if there are output options already written in the code that I need to edit.

答:
They are the structure. You should do something like this

```<code>render_book("file.Rmd", epub_book())
</code>```

to build the ebook. Some variables can be passed to epub_book().

You could take a look to https://bookdown.org/yihui/bookdown/ . It is a book about bookdown written in bookdown.

Body:
They are the structure. You should do something like this

render_book("file.Rmd", epub_book())

to build the ebook. Some variables can be passed to epub_book().

You could take a look to https://bookdown.org/yihui/bookdown/ . It is a book about bookdown written in bookdown.


问:
How to draw map layer only inside FeatureGroup elements in Leaflet?
For example, I have two map layers: open street maps and our own one. Both can be defined this way:

```<code>L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a>'
}).addTo(mapObject);
</code>```

The question is in that I do not need to draw the second layer on a whole map, but only inside elements of L.FeatureGroup:

```<code>var drawnItems = new L.FeatureGroup().addTo(mapObject);
</code>```

Especially inside polygons, rectangles, etc... Is that possible with leaflet? If yes, how this can be achieved?

Thanks.

答:
One approach would be to use the bounds option of your L.TileLayer, i.e.:

```<code>var drawnItems = new L.FeatureGroup( .... );

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: ...,
    bounds: drawnItems.getBounds()
}).addTo(mapObject);
</code>```

Another approach would be to look at the list of plugins for tile display, and use either TileLayer.BoundaryCanvas or leaflet-tilelayer-mask (keep in mind that more plugins might be applicable, and more plugins might appear in the future).

Body:
For example, I have two map layers: open street maps and our own one. Both can be defined this way:

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap'
}).addTo(mapObject);

The question is in that I do not need to draw the second layer on a whole map, but only inside elements of L.FeatureGroup:

var drawnItems = new L.FeatureGroup().addTo(mapObject);

Especially inside polygons, rectangles, etc... Is that possible with leaflet? If yes, how this can be achieved?

Thanks.

Body:
One approach would be to use the bounds option of your L.TileLayer, i.e.:

var drawnItems = new L.FeatureGroup( .... );

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: ...,
    bounds: drawnItems.getBounds()
}).addTo(mapObject);

Another approach would be to look at the list of plugins for tile display, and use either TileLayer.BoundaryCanvas or leaflet-tilelayer-mask (keep in mind that more plugins might be applicable, and more plugins might appear in the future).


问:
Django sitemaps, two pages using the same object
I am trying to add a sitemap to a jobsite I have built (first time using the sitemaps framework in Djnago, so not 100% sure what I should be doing).

Anyway, I have two pages, a "job detail" page, and a "job apply" page. These are both based on the Job model, and have urls referencing the job id.

urls.py

```<code>url(r'^job-details/(?P<pk>\d+)/$', views.JobDetailView.as_view(), name='job_detail' ) ,
url(r'apply/(?P<pk>\d+)/$', views.JobApplyView.as_view(), name='job_apply'  ),
</code>```

sitemap.py

```<code>class JobsSitemap(Sitemap):
    changefreq = "daily"
    priority = 0.5

    def items(self):
        return Job.objects.filter( active=True,
                               venue__contacts__account_verified=True,
                               date_expires__gte=date.today())

    def lastmod(self, obj):
        return obj.date_posted
</code>```

models.py

```<code>class Job(models.Model):
    ... field definitions here ....

    def get_absolute_url(self):
        return reverse('job_detail',  kwargs={'pk': self.id})
</code>```

Now the problem is that I have already specified get_absolute_url() on the Job model to point to the job detail page. So I can't point it to the job_apply page as well.

I tried configuring it according to the "Sitemap for static views" section in the docs, but that complains that there is no reverse match for that URL (as it is expecting the kwargs argument).

What is the correct way to deal with pages based on the same object?

答:
There maybe other ways of doing it, but one that's really simple is to create two SiteMaps. Let the current one be as it is and create a new one, this time make sure to override the [location][1] property.

Location Optional. Either a method or attribute.

If it’s a method, it should return the absolute path for a given
  object as returned by items().

If it’s an attribute, its value should be a string representing an
  absolute path to use for every object returned

```<code>class JobsApplySitemap(Sitemap):
    changefreq = "daily"
    priority = 0.5

    def items(self):
        return Job.objects.filter( active=True,
                               venue__contacts__account_verified=True,
                               date_expires__gte=date.today())

    def location(self, obj):
        return "/apply/{0}/".format(obj.pk)
        # you can use reverse instead

    def lastmod(self, obj):
        return obj.date_posted
</code>```

Body:
I am trying to add a sitemap to a jobsite I have built (first time using the sitemaps framework in Djnago, so not 100% sure what I should be doing).

Anyway, I have two pages, a "job detail" page, and a "job apply" page. These are both based on the Job model, and have urls referencing the job id.

urls.py

url(r'^job-details/(?P<pk>\d+)/$', views.JobDetailView.as_view(), name='job_detail' ) ,
url(r'apply/(?P<pk>\d+)/$', views.JobApplyView.as_view(), name='job_apply'  ),

sitemap.py

class JobsSitemap(Sitemap):
    changefreq = "daily"
    priority = 0.5

    def items(self):
        return Job.objects.filter( active=True,
                               venue__contacts__account_verified=True,
                               date_expires__gte=date.today())

    def lastmod(self, obj):
        return obj.date_posted

models.py

class Job(models.Model):
    ... field definitions here ....

    def get_absolute_url(self):
        return reverse('job_detail',  kwargs={'pk': self.id})

Now the problem is that I have already specified get_absolute_url() on the Job model to point to the job detail page. So I can't point it to the job_apply page as well.

I tried configuring it according to the "Sitemap for static views" section in the docs, but that complains that there is no reverse match for that URL (as it is expecting the kwargs argument).

What is the correct way to deal with pages based on the same object?

Body:
There maybe other ways of doing it, but one that's really simple is to create two SiteMaps. Let the current one be as it is and create a new one, this time make sure to override the [location][1] property.

Location Optional. Either a method or attribute.

If it’s a method, it should return the absolute path for a given
  object as returned by items().

If it’s an attribute, its value should be a string representing an
  absolute path to use for every object returned

class JobsApplySitemap(Sitemap):
    changefreq = "daily"
    priority = 0.5

    def items(self):
        return Job.objects.filter( active=True,
                               venue__contacts__account_verified=True,
                               date_expires__gte=date.today())

    def location(self, obj):
        return "/apply/{0}/".format(obj.pk)
        # you can use reverse instead

    def lastmod(self, obj):
        return obj.date_posted


问:
Disabling of sap.m.panel in sapui5
How to disable sap.m.panel? I have found that there is no property as setEnabled in sap.m.panel. But the customer requirement is to disable a panel. Can anyhow panel be disabled?</p>

答:
There is no property to disable the panel. But you can try to freeze that panel(Section Tag in Html) by using CSS property.

```<code> pointer-events: none;
</code>```

This may help you.

Title: Disabling of sap.m.panel in sapui5

Body:
There is no property to disable the panel. But you can try to freeze that panel(Section Tag in Html) by using CSS property.

 pointer-events: none;

This may help you.


问:
How to read File using PDFReader
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

```<code>public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}
</code>```

答:
Please, read much more carefully through PdfReader constructors. Best way for your example is to wrap File into InputStream.

```<code>new PdfReader(new FileInputStream(inputFile))
</code>```

Title: How to read File using PDFReader

Body:
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}

Body:
Please, read much more carefully through PdfReader constructors. Best way for your example is to wrap File into InputStream.

new PdfReader(new FileInputStream(inputFile))


问:
Keyboard doesn't show up when SAMSUNG Multi-Window Sdk is implemented on galaxy S3 running Android 4.2 and 4.3
When I add samsung multiwindow sdk, I realised that on galaxy phones running android 4.2 and 4.3 have a problem on showing soft-keyboard.
If I don't use the samsung multiwindow sdk, soft-keyboard works fine.
I'm using this searchbar library. Maybe it's related with this library too. Also I've tried to force to show soft-keyboard with the following code; but still keyboard is not visible.

```<code>InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,  InputMethodManager.HIDE_IMPLICIT_ONLY);
</code>```

Manifest file (site):

```<code>   <uses-library android:required="false" android:name="com.sec.android.app.multiwindow"> </uses-library>
   <meta-data android:name="com.sec.android.support.multiwindow" android:value="true" />

    <intent-filter>
      <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.MULTIWINDOW_LAUNCHER" />
    </intent-filter>
</code>```

答:
```<code><meta-data android:name="com.samsung.android.sdk.multiwindow.enable" android:value="true" />
</code>```

Problem (Soft keyboard isn't shown on focus of searcbar) that I've faced with is because of the enabling multiwindow meta-data. So I defined two 'bool.xml's under values-v18 and values-v19 in order to disable samsung multiwindow library below Kitkat.

changed in to this:

```<code><meta-data android:name="com.samsung.android.sdk.multiwindow.enable" android:value="@bool/samsung_multi_window" />
</code>```

Body:
When I add samsung multiwindow sdk, I realised that on galaxy phones running android 4.2 and 4.3 have a problem on showing soft-keyboard.
If I don't use the samsung multiwindow sdk, soft-keyboard works fine.
I'm using this searchbar library. Maybe it's related with this library too. Also I've tried to force to show soft-keyboard with the following code; but still keyboard is not visible.

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,  InputMethodManager.HIDE_IMPLICIT_ONLY);

Manifest file (site):

   <uses-library android:required="false" android:name="com.sec.android.app.multiwindow"> </uses-library>
   <meta-data android:name="com.sec.android.support.multiwindow" android:value="true" />

    <intent-filter>
      <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.MULTIWINDOW_LAUNCHER" />
    </intent-filter>

Body:
<meta-data android:name="com.samsung.android.sdk.multiwindow.enable" android:value="true" />

Problem (Soft keyboard isn't shown on focus of searcbar) that I've faced with is because of the enabling multiwindow meta-data. So I defined two 'bool.xml's under values-v18 and values-v19 in order to disable samsung multiwindow library below Kitkat.

changed in to this:

<meta-data android:name="com.samsung.android.sdk.multiwindow.enable" android:value="@bool/samsung_multi_window" />


问:
Lack of practical insights into using Play+Scala vs. JavaScript
We (my team) is starting on a cloud-hosted web based application. We embarked upon Scala+Play as the server side web application. Since no one knew Scala in my team (previous experience in Java/Java Script/Python/C++) all of us are experiencing a steep learning curve. After spending a few weeks on learning basics of Scala, we started with play-scala-starter example as a basis. It took a few days of time for a team member to create a prototype GET+POST API handler accessing mysql DB.
Given significant efforts and the time spent on Scala, a team member for the sake of comparison built the same prototype functionality using node.js in just half-a-day (4-5 hours). That was a revelation for all of us. To add to that the Internet is replete with node.js success stories used in enterprise grade applications (note that for front-end anyway we are going to use JS based framework e.g. Angular, React, etc.).
Now as a team we are debating on next approach - play+scala or node.js. We don't want to take a decision based on short-term gains or to avoid initial struggle in ramping-up. That's why posting this question here to get real-world insights. If this is a wrong-place to ask such questions then please suggest appropriate one. Most likely this question will be closed as it is of 'discussion' type.
NOTE: This post is not to criticize any of the approaches. So apologies in advance. </p>

答:
In general, if you're new to a language : EXpect time. So I'm not surprised that doing the prototype in Node.js is way faster.

My advice : Stick to Java in this case. It's easier if you're coming from C++ / Java / JS.

I won't recommend nodejs from a technical point of view : It has scalability issues, and Play is build on Akka, so you get all the Akka goodies for free. Getting that right in another language is hard. As in : Really hard.

In short : Start with Play Java, and do the move to Scala later on.


问:
Containers and divs in CSS
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dealsglobal">
<h2>Global Coupons</h2>
    <div class="dealsleft">
 <img src="thumb-heavengifts.jpg" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
    Test
    </div>
</div>

<div class="dealsindia">
<h2>Indian Coupons</h2>
    <div class="dealsleft">
    Test
    </div>
    <div class="dealsright">
 Test
    </div>
</div></code>```

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

答:
You missed adding this css property:</p>

```<code>.dealsleft {
   text-align:center;
}
</code>```

Title: Containers and divs in CSS

Body:
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}

Global Coupons

    Test

Indian Coupons

    Test

 Test

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

Body:
You missed adding this css property:

.dealsleft {
   text-align:center;
}


问:
Redux + Normalizr : Adding and deleting normalized entities in Redux state
I have an API response which has a lot of nested entities. I use normalizr to keep the redux state as flat as possible.
 For eg. the api response looks like below:

```<code>{
  "id": 1,
  "docs": [
    {
      "id": 1,
      "name": "IMG_0289.JPG"
    },
    {
      "id": 2,
      "name": "IMG_0223.JPG"
    }
  ],
  "tags": [
    {
      "id": "1",
      "name": "tag1"
    },
    {
      "id": "2",
      "name": "tag2"
    }
  ]
}
</code>```

This response is normalized using normalizr using the schema given below:

```<code>const OpeningSchema = new schema.Entity('openings', {
    tags: [new schema.Entity('tags')],
    docs: [new schema.Entity('docs')]
});
</code>```

and below is how it looks then:

```<code>{
  result: "1",
  entities: {
    "openings": {
       "1": {
          "id": 1,
          "docs": [1,2],
          "tags": [1,2]
       }
    },
    "docs": {
      "1": {
        id: "1",
        "name": "IMG_0289.JPG"
      },
      "2": {
        id: "2",
        "name": "IMG_0223.JPG"
      }
    },
    "tags": {
      "1": {
          "id": 1,
          "name": "tag1"
      },
      "2": {
          "id": 2,
          "name": "tag2"
      }
    }
  }
}
</code>```

The redux state now looks something like below:

```<code>state = {
  "opening" : {
      id: 1,
      tags: [1,2],
      docs: [1,2]
  },
  "tags": [
      {
          "id":1,
          "name": "tag1"
      },
      {
          "id":2,
          "name": "tag2"
      }
  ],
  "docs": [
      {
          "id":1,
          "name": "IMG_0289.JPG"
      },
      {
          "id":2,
          "name": "IMG_0223.JPG"
      }
  ]
}
</code>```

Now if I dispatch an action to add a tag, then it adds a tag object to state.tags but it doesn't update state.opening.tags array. Same behavior while deleting a tag also.

I keep opening, tags and docs in three different reducers.

This is an inconsistency in the state. I can think of the following ways to keep the state consistent:

I dispatch an action to update tags and listen to it in both tags reducer and opening reducer and update tags subsequently at both places.

The patch request to update opening with tags returns the opening response. I can again dispatch the action which normalizes the response and set tags, opening etc with proper consistency.

What is the right way to do this. Shouldn't the entities be observing for changes to the related entities and make the changes itself. Or there are any other patterns that could be followed any such action.

答:
First to summarise how normalizr works: normalizr flattens nested API response to entities defined by your schemas. So, when you made your initial GET openings API request, normalizr flattened the response and created your Redux entities and the flattened objects: openings, docs, tags.

Your suggestions are viable, but I find normalizr's real benefit in separating API data from UI state; so I don't update the data in Redux store myself... All my API data are kept in entities and they are not altered by me; they are vanilla back-end data... All I do is to do a GET upon state changing API operations, and normalise the GET response. There is a small exception for DELETE case that I'll expand on later on... A middleware will deal with such cases, so you should use one if you haven't been using. I created my own middleware, but I know redux-promise-middleware is quite popular.

In your data set above; when you add a new tag, I assume you are making an API POST to do so, which in turn updates the back-end. Then, you should do another GET openings which will update the entities for openings and all its nested schemas.

When you delete a tag, e.g. tag[2], upon sending the DELETE request to the back-end, you should nullify the deleted object in your entities state, ie. entities.tags[2] = null before making the GET openings again to update your normalizr entities.

Body:
I have an API response which has a lot of nested entities. I use normalizr to keep the redux state as flat as possible.
 For eg. the api response looks like below:

{
  "id": 1,
  "docs": [
    {
      "id": 1,
      "name": "IMG_0289.JPG"
    },
    {
      "id": 2,
      "name": "IMG_0223.JPG"
    }
  ],
  "tags": [
    {
      "id": "1",
      "name": "tag1"
    },
    {
      "id": "2",
      "name": "tag2"
    }
  ]
}

This response is normalized using normalizr using the schema given below:

const OpeningSchema = new schema.Entity('openings', {
    tags: [new schema.Entity('tags')],
    docs: [new schema.Entity('docs')]
});

and below is how it looks then:

{
  result: "1",
  entities: {
    "openings": {
       "1": {
          "id": 1,
          "docs": [1,2],
          "tags": [1,2]
       }
    },
    "docs": {
      "1": {
        id: "1",
        "name": "IMG_0289.JPG"
      },
      "2": {
        id: "2",
        "name": "IMG_0223.JPG"
      }
    },
    "tags": {
      "1": {
          "id": 1,
          "name": "tag1"
      },
      "2": {
          "id": 2,
          "name": "tag2"
      }
    }
  }
}

The redux state now looks something like below:

state = {
  "opening" : {
      id: 1,
      tags: [1,2],
      docs: [1,2]
  },
  "tags": [
      {
          "id":1,
          "name": "tag1"
      },
      {
          "id":2,
          "name": "tag2"
      }
  ],
  "docs": [
      {
          "id":1,
          "name": "IMG_0289.JPG"
      },
      {
          "id":2,
          "name": "IMG_0223.JPG"
      }
  ]
}

Now if I dispatch an action to add a tag, then it adds a tag object to state.tags but it doesn't update state.opening.tags array. Same behavior while deleting a tag also.

I keep opening, tags and docs in three different reducers.

This is an inconsistency in the state. I can think of the following ways to keep the state consistent:

I dispatch an action to update tags and listen to it in both tags reducer and opening reducer and update tags subsequently at both places.

The patch request to update opening with tags returns the opening response. I can again dispatch the action which normalizes the response and set tags, opening etc with proper consistency.

What is the right way to do this. Shouldn't the entities be observing for changes to the related entities and make the changes itself. Or there are any other patterns that could be followed any such action.


问:
Find the middle of a weighted list
How to find the index i that minimizes abs(sum(A[:i])-sum(A[i:])).

Examples:

```<code>ex1: A = [1, 2, 3, 4, 5], i = 3
ex2: A = [1, 2, 3], i = 2
ex3: A = [9, 1, 2, 3, 4], i = 1
ex4: A = [1, 2, 3, 4], i = 3
</code>```

答:
Let us denote by Si the value abs(sum(A[:i])-sum(A[i:])). If you knew all the values you could find the minimum, right? Do a simple iteration and find this value.

Now the problem is how to compute the values Si. As it turns out this is not very hard: first compute the sum of all elements SUM. Then iterate from left to right and accumulate the sum of all elements to the left of the current position(denote that lefti). Si = abs((SUM - lefti) - lefti).

So what you need to do is two iterations over the input - one to compute the total sum and second to find the value Si (and find the minimum of them).

Title: Find the middle of a weighted list

Body:
How to find the index i that minimizes abs(sum(A[:i])-sum(A[i:])).

Examples:

ex1: A = [1, 2, 3, 4, 5], i = 3
ex2: A = [1, 2, 3], i = 2
ex3: A = [9, 1, 2, 3, 4], i = 1
ex4: A = [1, 2, 3, 4], i = 3


问:
How to correctly re-attach onclick events
I have an OL that contains LIs with small inset buttons:

```<code><li id="123">
  <button class="action1">Do 1</button>
  <button class="action2">Do 2</button>
</li>
</code>```

And my jquery which has set up the functions on document load:

```<code>$('.action1').on('click', function() {
  // do stuff
});
</code>```

Only, when I'm appending to the list:

```<code>li = '<li...' //defines li item here
$('#myol').append(li);
</code>```

The buttons don't do anything. I guess this is because the listeners were attached before the listitem was created, but what is the correct way to attach the listeners to the newly created items (or even better, set them up in such a way that newly created items are accounted for?

答:
You can attach event to your dynamic element like that:

```<code>$('body').on('click', '.action1', function() {
    // do something
});
</code>```

This will work for all a tags with class 'action1' in the body, whether already present or dynamically added later.

Body:
I have an OL that contains LIs with small inset buttons:

  <button class="action1">Do 1</button>
  <button class="action2">Do 2</button>

And my jquery which has set up the functions on document load:

$('.action1').on('click', function() {
  // do stuff
});

Only, when I'm appending to the list:

li = '<li...' //defines li item here
$('#myol').append(li);

The buttons don't do anything. I guess this is because the listeners were attached before the listitem was created, but what is the correct way to attach the listeners to the newly created items (or even better, set them up in such a way that newly created items are accounted for?

Body:
You can attach event to your dynamic element like that:

$('body').on('click', '.action1', function() {
    // do something
});

This will work for all a tags with class 'action1' in the body, whether already present or dynamically added later.


问:
how to assign values to multidimensional arrays in javascript?
I tried to do this with:

arr[i][j] = 'whatever';

but I get some kind of error "cannot convert to object..."

答:
Set Like</p>

```<code>a[3]["fieldName"]="xxxx";
</code>```

Body:
Set Like

a[3]["fieldName"]="xxxx";


问:
Angular Resource - intercepting and transforming request/response data
I'm trying to transform / intercept some requests in my angular + closure project but not all requests to change my camelCase keys to snake_case.

I managed to add a default interceptors and transformers with $httpProvider in my config however this did all requests including templates. Adding an option in each of my Resource configs i could allow / disallow the transforms however that config option is only accessible in requests not responses meaning I'd have to check if its JSON first which isn't ideal.

I believe also transforms get the raw request body (or maybe it was interceptors I can't remember with all the testing i did) and converting it to and from JSON etc seems error prone.

The interceptor for $resource only allows response and responseError interceptors for some frustrating reason.

Is there any way to intercept each request/response JSON object where I can keep the transformers in its own file / class / factory and either allow it or require the function and call it on each request?

What would the best route be to take for this?

答:
You can use an $http interceptor. $resource is using $http service in the background to make requests, so it will be applied.

```<code>function MyInterceptor() {
    return {
        request: config => {
            // do your logic here
            // you can modify only end-points you want to modify by using if statements
        }
    }
}

function config($httpProvider) {
    $httpProvider.interceptors.push('MyInterceptor');
}

angular
    .module('app')
    .factory('MyInterceptor', MyInterceptor)
    .config(config);
</code>```

Body:
You can use an $http interceptor. $resource is using $http service in the background to make requests, so it will be applied.

function MyInterceptor() {
    return {
        request: config => {
            // do your logic here
            // you can modify only end-points you want to modify by using if statements
        }
    }
}

function config($httpProvider) {
    $httpProvider.interceptors.push('MyInterceptor');
}

angular
    .module('app')
    .factory('MyInterceptor', MyInterceptor)
    .config(config);


问:
R function to return matrix rows that satisfy min and max ranges
Having the following matrix:

```<code>      [,1] [,2] [,3] [,4]
  [1,]  231   14  517  310
  [2,]    1  154   18   21
  [3,]  121    6  198   23
</code>```

I want to get only the rows that have a minimum range for each row between 2
   and 30.

Min range for each row:

```<code> [1] 79
 [2]  3
 [3] 17
</code>```

so we get only [2] and [3]

and a max range between 0 and 160
   Max range for each row:

```<code>  [1] 503
  [2] 153
  [3] 192
</code>```

so finally we get only [2] that satisfies the two conditions.
   Can you please provide an R language function which can generate this result?

Regards,
Dimitris

答:
Setting up the data

```<code>m <- read.table(text="231   14  517  310
                        1  154   18   21
                      121    6  198   23")

m <- as.matrix(m)
</code>```

Maximum range of each row

```<code>maxr <- apply(m, 1, function(x) diff(range(x)))
</code>```

Minimum range of each row

```<code>minr <- apply(m, 1, function(x) min(diff(sort(x))))
</code>```

Stringing it together into a condition on rows

```<code>m[minr > 2 & minr < 20 & maxr > 0 & maxr < 160, ]
#   1 154  18  21
</code>```

Body:
Having the following matrix:

      [,1] [,2] [,3] [,4]
  [1,]  231   14  517  310
  [2,]    1  154   18   21
  [3,]  121    6  198   23

I want to get only the rows that have a minimum range for each row between 2
   and 30.

Min range for each row:

 [1] 79
 [2]  3
 [3] 17

so we get only [2] and [3]

and a max range between 0 and 160
   Max range for each row:

  [1] 503
  [2] 153
  [3] 192

so finally we get only [2] that satisfies the two conditions.
   Can you please provide an R language function which can generate this result?

Regards,
Dimitris

Body:
Setting up the data

m <- read.table(text="231   14  517  310
                        1  154   18   21
                      121    6  198   23")

m <- as.matrix(m)

Maximum range of each row

maxr <- apply(m, 1, function(x) diff(range(x)))

Minimum range of each row

minr <- apply(m, 1, function(x) min(diff(sort(x))))

Stringing it together into a condition on rows

m[minr > 2 & minr < 20 & maxr > 0 & maxr < 160, ]
#   1 154  18  21


问:
MVC Dropdownlist with multiple doesn't bind with server values
I have the following element

```<code><div class="col-md-6">
 @Html.DropDownListFor(model => model.SelectedEmployees, Model.Employees, new { @class = "form-control select2", multiple = "1" })
</div>
</code>```

When I select the items and I do a Postback the values are found "SelectedEmployees" which is a List, but if I put default values in the List it will not bind back to the dropdown list when I open the page.
I am using the select2 bootstrap control

答:
Fixed it by changing the DropDownList

```<code><div class="form-group">
    <label class="col-md-2">Linked Employees</label>
    <div class="col-md-6">
       @Html.ListBoxFor(model => model.SelectedEmployees, Model.Employees, new { @class = "form-control select2", multiple = "1" })
     </div>
</div>
</code>```

The html generate stays the same client side but the binding works now

Body:
I have the following element

 @Html.DropDownListFor(model => model.SelectedEmployees, Model.Employees, new { @class = "form-control select2", multiple = "1" })

When I select the items and I do a Postback the values are found "SelectedEmployees" which is a List, but if I put default values in the List it will not bind back to the dropdown list when I open the page.
I am using the select2 bootstrap control

Body:
Fixed it by changing the DropDownList

<div class="form-group">
    <label class="col-md-2">Linked Employees</label>
    <div class="col-md-6">
       @Html.ListBoxFor(model => model.SelectedEmployees, Model.Employees, new { @class = "form-control select2", multiple = "1" })
     </div>
</div>

The html generate stays the same client side but the binding works now