问:
UITableView is not refreshing when scrolling
I have UITableView, with CustomCell. In CustomCell there is UICollectionView with CustomUICollectionViewCell.
Everything is created in the way, according to UICollectionView inside CustomTableCell.
Then, let's say I have 12 rows. On the beginning I can see 6 of them.
In CustomUICollectionViewCell, labels are fine, but when I scroll down, to see other cells, CustomUICollectionViewCells labels are not as expected. They are the same as first 6 rows, which are now scrolled up.

Where should I refresh CustomUICollectionViewCells label after scroll?

Example view:
Before scrolling:

After scrolling:

However when debugging, when assigning data to cell, everything is assigned fine.
All code is in the link as it's also my question.
Seems that it's duplicating rows. I guess that it should be reloaded(?).

Added prepareForReuse method, as advised, but didn't help. Now my CustomCellClass looks:

```<code>@implementation TemperatureTableViewCell

    NSNumberFormatter *decimalStyleFormatter;

- (void)awakeFromNib
{
    [super awakeFromNib];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.contentView addSubview:self.collectionView];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collection.count;
}

-(void)collectionView:(CollectionView *)collectionView willDisplayCell:(TemperatureItemCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureSensor *temp = self.collection[indexPath.item];
    cell.temperatureValue = temp.temperature.stringValue;
    cell.tempValTempCollViewCell.text = [NSString stringWithFormat:@"%@°C", cell.temperatureValue];
    cell.sensorName.text = temp.sensorName;
    cell.imageTempCollViewCell.image = [TemperatureImageHelper getTemperatureIcon:temp];
     [self.collectionView reloadData];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    return cell;
}

- (void)setCollectionViewDelegate:(id)dataSourceDelegate indexPath:(NSIndexPath *)indexPath {
    self.collectionView.delegate = dataSourceDelegate;
}

@end
</code>```

And my CustomCollectionViewCell:

```<code>@implementation TemperatureItemCollectionViewCell
-(void)awakeFromNib {
    [super awakeFromNib];

}
-(void)prepareForReuse {
    [super prepareForReuse];

    self.imageTempCollViewCell.image = nil;
    self.tempValTempCollViewCell.text = nil;
    self.sensorName.text = nil;
    self.temperatureValue = nil;

}
@end
</code>```

My TableViewController

```<code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_tempSensorsDictionary == nil)
        return 0;
    else {
        NSArray *allSensorKeys = [_tempSensorsDictionary allKeys];
        return [allSensorKeys count];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(TemperatureTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setCollectionViewDelegate:self indexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

    NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    cell.collection = [_tempSensorsDictionary  objectForKey:nodeNumbers[indexPath.row]];
    //NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    if([[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] != nil &&
       ![[[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] isEqualToString:@""]) {
        NSString *name = [NSString stringWithFormat:@"%@ (%@)", [[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]], nodeNumbers[indexPath.row]];
        cell.unitNameLabel.text = name;
    } else {
        cell.unitNameLabel.text = nodeNumbers[indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 85.0;
}
</code>```

答:
I think this is what's happening. Inside of your child cell (I think it's collectionViewCell) you should reset all the values of the ui elements. Basically you are reusing one cell and you neeed to reset the values of the text or the images on it.</p>

```<code>override func prepareForReuse() {
    super.prepareForReuse()
    titleLabel1.text = nil
    image1.image = nil
    ...
}
</code>```

Body:
I have UITableView, with CustomCell. In CustomCell there is UICollectionView with CustomUICollectionViewCell.
Everything is created in the way, according to UICollectionView inside CustomTableCell.
Then, let's say I have 12 rows. On the beginning I can see 6 of them.
In CustomUICollectionViewCell, labels are fine, but when I scroll down, to see other cells, CustomUICollectionViewCells labels are not as expected. They are the same as first 6 rows, which are now scrolled up.

Where should I refresh CustomUICollectionViewCells label after scroll?

Example view:
Before scrolling:

After scrolling:

However when debugging, when assigning data to cell, everything is assigned fine.
All code is in the link as it's also my question.
Seems that it's duplicating rows. I guess that it should be reloaded(?).

Added prepareForReuse method, as advised, but didn't help. Now my CustomCellClass looks:

@implementation TemperatureTableViewCell

    NSNumberFormatter *decimalStyleFormatter;

- (void)awakeFromNib
{
    [super awakeFromNib];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.contentView addSubview:self.collectionView];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collection.count;
}

-(void)collectionView:(CollectionView *)collectionView willDisplayCell:(TemperatureItemCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureSensor *temp = self.collection[indexPath.item];
    cell.temperatureValue = temp.temperature.stringValue;
    cell.tempValTempCollViewCell.text = [NSString stringWithFormat:@"%@°C", cell.temperatureValue];
    cell.sensorName.text = temp.sensorName;
    cell.imageTempCollViewCell.image = [TemperatureImageHelper getTemperatureIcon:temp];
     [self.collectionView reloadData];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    return cell;
}

- (void)setCollectionViewDelegate:(id)dataSourceDelegate indexPath:(NSIndexPath *)indexPath {
    self.collectionView.delegate = dataSourceDelegate;
}

@end

And my CustomCollectionViewCell:

@implementation TemperatureItemCollectionViewCell
-(void)awakeFromNib {
    [super awakeFromNib];

}
-(void)prepareForReuse {
    [super prepareForReuse];

    self.imageTempCollViewCell.image = nil;
    self.tempValTempCollViewCell.text = nil;
    self.sensorName.text = nil;
    self.temperatureValue = nil;

}
@end

My TableViewController

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_tempSensorsDictionary == nil)
        return 0;
    else {
        NSArray *allSensorKeys = [_tempSensorsDictionary allKeys];
        return [allSensorKeys count];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(TemperatureTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setCollectionViewDelegate:self indexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

    NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    cell.collection = [_tempSensorsDictionary  objectForKey:nodeNumbers[indexPath.row]];
    //NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    if([[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] != nil &&
       ![[[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] isEqualToString:@""]) {
        NSString *name = [NSString stringWithFormat:@"%@ (%@)", [[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]], nodeNumbers[indexPath.row]];
        cell.unitNameLabel.text = name;
    } else {
        cell.unitNameLabel.text = nodeNumbers[indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 85.0;
}

Body:
I think this is what's happening. Inside of your child cell (I think it's collectionViewCell) you should reset all the values of the ui elements. Basically you are reusing one cell and you neeed to reset the values of the text or the images on it.

override func prepareForReuse() {
    super.prepareForReuse()
    titleLabel1.text = nil
    image1.image = nil
    ...
}


来源: stackexchange

问:
Class PDO not found in laravel 5.2
i have a DB helper and code is in this way:

```<code><?php

namespace App\Business;

use DB;

Class DBHelper{

    private function dbConnectionInfo()

    {

    //$results = DB::select('Select UserName from user_master');
            //return "fetchUserLocation success". json_encode($results) ;
        $pdo_db = DB::connection()->getPdo() ;
        $pdo_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo_db;

    }

    function executeResultSet($DBQuery)
    {
        $pdo_object = DBHelper :: dbConnectionInfo();
        $stmt = $pdo_object->prepare($DBQuery);
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results;
    }

    function dbConnection()
    {
        return  DBHelper :: dbConnectionInfo();
    }
}

?>
</code>```

When i call return "fetchUserLocation success". json_encode($results) ; it executed that means DB connection works properly but when i call the function error : Class 'App\Business\PDO' not found
How can i use PDO in this code. please suggest

答:
this is your problem, this PDO:: does not exist, you are doing the raw pdo thing instead of the one your dependencies. this is what you should do</p>

```<code>$results = $stmt->fetchAll($pdo_object::FETCH_ASSOC);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Class PDO not found in laravel 5.2

Body:
i have a DB helper and code is in this way:

<?php

namespace App\Business;

use DB;

Class DBHelper{

    private function dbConnectionInfo()

    {

    //$results = DB::select('Select UserName from user_master');
            //return "fetchUserLocation success". json_encode($results) ;
        $pdo_db = DB::connection()->getPdo() ;
        $pdo_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo_db;

    }

    function executeResultSet($DBQuery)
    {
        $pdo_object = DBHelper :: dbConnectionInfo();
        $stmt = $pdo_object->prepare($DBQuery);
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results;
    }

    function dbConnection()
    {
        return  DBHelper :: dbConnectionInfo();
    }
}

?>

When i call return "fetchUserLocation success". json_encode($results) ; it executed that means DB connection works properly but when i call the function error : Class 'App\Business\PDO' not found
How can i use PDO in this code. please suggest

Body:
this is your problem, this PDO:: does not exist, you are doing the raw pdo thing instead of the one your dependencies. this is what you should do

$results = $stmt->fetchAll($pdo_object::FETCH_ASSOC);


问:
How to validate date field with format MMM/DD/YY or MMM/DD/YYYY?
My field contains the string values like JUL/11/2017, JAN/11/17. Though it is a valid field, i am not able to validate it using is_date function

```<code>SET DATEFORMAT MDY;
if isdate('JUL/11/2017')=1
print 'VALID_DATE'
else
print 'invalid date'
</code>```

If the field value is DD/MMM/YY or DD/MMM/YYYY , it works fine. Any one can help me validating this field.

Note:I have tried using set language option too.

答:
What you need is just to replace your '/' separator with space to have 109 data format:

```<code>SET DATEFORMAT MDY;
if isdate(replace('JUL/11/2017', '/', ' '))=1
print 'VALID_DATE'
else
print 'invalid date'
</code>```

Body:
My field contains the string values like JUL/11/2017, JAN/11/17. Though it is a valid field, i am not able to validate it using is_date function

SET DATEFORMAT MDY;
if isdate('JUL/11/2017')=1
print 'VALID_DATE'
else
print 'invalid date'

If the field value is DD/MMM/YY or DD/MMM/YYYY , it works fine. Any one can help me validating this field.

Note:I have tried using set language option too.

Body:
What you need is just to replace your '/' separator with space to have 109 data format:

SET DATEFORMAT MDY;
if isdate(replace('JUL/11/2017', '/', ' '))=1
print 'VALID_DATE'
else
print 'invalid date'


问:
how to git log amendments
So basically, I know that to see past git commits, you do git log. But at my company we work with gerrit on one commit and you make amendments to that commits. How do I see all the past amendments to that specific commit, so I see each of their commit message and I can diff between the amendments? THANKS!</p>

答:
If all the amendments have the same Change-Id, then thay are patch sets of one change. You don't specify in the question how the diff is displayed, so here's one of the possible solutions.

```<code>ssh -p <port> <username>@<gerrithost> gerrit query commit:<commit-id> --patch-sets --format=json
</code>```

port is 29418 by default;

username is the gerrit username to run
gerrit query. It should be assinged the right to read the refs of
the repository;

gerrithost is the the host name or the IP address of your gerrit;

commit-id is the sha1 value of a commit.

--format=json is optional. The default format is text.

The output includes details about the patch sets of the change, including entries like:

```<code>ref: refs/changes/90/812290/3
ref: refs/changes/90/812290/2
ref: refs/changes/90/812290/1
</code>```

These are the refs that Gerrit creates for every commit that is pushed to refs/for destination. If you know the number 812290, you could use change:812290 to replace commit:<commit-id> in the gerrit query. Fetch these refs in a local repository:

```<code>git fetch origin refs/changes/90/812290/3
</code>```

The commits that are pointed at by these refs are downloaded and then you can run git commands to manipulate them as you like.

```<code>git diff commit1 commit2
</code>```

You could search for gerrit query in Gerrit's docs to learn more.

Title: how to git log amendments

Body:
If all the amendments have the same Change-Id, then thay are patch sets of one change. You don't specify in the question how the diff is displayed, so here's one of the possible solutions.

ssh -p <port> <username>@<gerrithost> gerrit query commit:<commit-id> --patch-sets --format=json

port is 29418 by default;

username is the gerrit username to run
gerrit query. It should be assinged the right to read the refs of
the repository;

gerrithost is the the host name or the IP address of your gerrit;

commit-id is the sha1 value of a commit.

--format=json is optional. The default format is text.

The output includes details about the patch sets of the change, including entries like:

ref: refs/changes/90/812290/3
ref: refs/changes/90/812290/2
ref: refs/changes/90/812290/1

These are the refs that Gerrit creates for every commit that is pushed to refs/for destination. If you know the number 812290, you could use change:812290 to replace commit:<commit-id> in the gerrit query. Fetch these refs in a local repository:

git fetch origin refs/changes/90/812290/3

The commits that are pointed at by these refs are downloaded and then you can run git commands to manipulate them as you like.

git diff commit1 commit2

You could search for gerrit query in Gerrit's docs to learn more.


问:
Node JS request blocking other requests
I have created Node JS app, i am explicitly downloading more than 100000 records from database. While the request is in proceeding, i try to login in the same application from another browser it wont respond unless the previous request is completed. Any idea ? Anything to do with event loop or threads ??
So here is my logic.
I make a get request to my API in Step 1, API calls database layer in Step 2. Database is returning only 21 records, i am explicitly looping 100000*21 to make heavy rendering just to test the load on json2csv. While doing so, the other requests to server will not respond until the last processing completes.</p>

```<code>Step 1:

router.get('/report/downloadOverdueTrainings/:criteria', function (req, res, next) {
        var overDueTrainings = [];
        var reportManager = new ReportManager();
        var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
        result.then(function (result) {
            var fields = ['Over Due Trainings'];
            for (var i = 0; i < 100000; i++) { //Testing purpose
                for (var training of result) {
                    overDueTrainings.push({
                        'Over Due Trainings': training.OverDueTrainings
                    })
                }
            }
            json2csv({
                data: overDueTrainings,
                fields: fields
            }, function (err, csv) {
                if (err)
                    throw err;
                res.setHeader('Content-disposition', 'attachment; filename=OverdueTrainings.csv');
                res.set('Content-Type', 'text/csv');
                res.send(csv);
            });
        }).catch(function (err) {
            next(err);
        });
    });

Step 2: Database Logic
var xtrDatabaseConnection =require('./xtrDatabaseConnection').XTRDatabaseConnection;
       ReportData.prototype.getOverdueTrainings = async function (params) {
        var connection = new xtrDatabaseConnection();
        var sequelize = connection.getSequelize();
        try {
            var query = "CALL report_getOverdueTrainings(:p_CourseCode,:p_Revision,:p_RevisionNo,:p_UserGroup,:p_Username,:p_Status,:p_SortColoumnNo,:p_SortColoumnDirection,:p_callType,:p_StartIndex,:p_PageSize)";
            var replacements = {
                p_CourseCode: params.CourseCode,
                p_Revision: params.Revision,
                p_RevisionNo: (params.RevisionNo == '' || params.RevisionNo == null) ? 0 : params.RevisionNo,
                p_UserGroup: params.UserGroup,
                p_Username: params.Username,
                p_Status: params.Status,
                p_SortColoumnNo: params.SortColoumnNo,
                p_SortColoumnDirection: params.SortColoumnDirection,
                p_callType: params.callType,
                p_StartIndex: params.startIndex,
                p_PageSize: params.pageSize
            };
            //console.log(replacements);
            return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);
        } catch (e) {
            throw (e);
        } finally {
            //To close connections
            sequelize.connectionManager.close().then(() => console.log('Connection Closed'));
        }
    }

XTRDatabaseConnection.prototype.executeQuerySequelize = function (sequelize, query, queryType, replacements) {
    return sequelize.authenticate()
        .then(() => {
            return sequelize.query(query, {
                replacements: replacements,
                type: queryType
            }).
            then(result => result)
                .catch(err => {
                    throw (err);
                });
        })
        .catch(err => {
            xtrUtility.logErrorsToWinstonTransports('Unable to connect to the database or some error occurred while executing your query. ', err);
            throw new AppError(err, "dbError", "Unable to connect to the database or some error occurred while executing your query.");
        });
}
</code>```

答:
Node.js is working on single thread. So you need use it for small process with async calls. When you use async/await you are blocking the callback function.

So you need to use your database functions as promise. It will work async.

```<code>.query('CALL someFunction()')
.then(function(response){
      //done
    }).error(function(err){
     //error
});
</code>```

But there is a problem about it. You need to load 21 times your result. So in this case you need to use recursive function. When you finished recursive call you can send your data to client as async.

Title: Node JS request blocking other requests

Body:
I have created Node JS app, i am explicitly downloading more than 100000 records from database. While the request is in proceeding, i try to login in the same application from another browser it wont respond unless the previous request is completed. Any idea ? Anything to do with event loop or threads ??
So here is my logic.
I make a get request to my API in Step 1, API calls database layer in Step 2. Database is returning only 21 records, i am explicitly looping 100000*21 to make heavy rendering just to test the load on json2csv. While doing so, the other requests to server will not respond until the last processing completes.

Step 1:

router.get('/report/downloadOverdueTrainings/:criteria', function (req, res, next) {
        var overDueTrainings = [];
        var reportManager = new ReportManager();
        var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
        result.then(function (result) {
            var fields = ['Over Due Trainings'];
            for (var i = 0; i < 100000; i++) { //Testing purpose
                for (var training of result) {
                    overDueTrainings.push({
                        'Over Due Trainings': training.OverDueTrainings
                    })
                }
            }
            json2csv({
                data: overDueTrainings,
                fields: fields
            }, function (err, csv) {
                if (err)
                    throw err;
                res.setHeader('Content-disposition', 'attachment; filename=OverdueTrainings.csv');
                res.set('Content-Type', 'text/csv');
                res.send(csv);
            });
        }).catch(function (err) {
            next(err);
        });
    });

Step 2: Database Logic
var xtrDatabaseConnection =require('./xtrDatabaseConnection').XTRDatabaseConnection;
       ReportData.prototype.getOverdueTrainings = async function (params) {
        var connection = new xtrDatabaseConnection();
        var sequelize = connection.getSequelize();
        try {
            var query = "CALL report_getOverdueTrainings(:p_CourseCode,:p_Revision,:p_RevisionNo,:p_UserGroup,:p_Username,:p_Status,:p_SortColoumnNo,:p_SortColoumnDirection,:p_callType,:p_StartIndex,:p_PageSize)";
            var replacements = {
                p_CourseCode: params.CourseCode,
                p_Revision: params.Revision,
                p_RevisionNo: (params.RevisionNo == '' || params.RevisionNo == null) ? 0 : params.RevisionNo,
                p_UserGroup: params.UserGroup,
                p_Username: params.Username,
                p_Status: params.Status,
                p_SortColoumnNo: params.SortColoumnNo,
                p_SortColoumnDirection: params.SortColoumnDirection,
                p_callType: params.callType,
                p_StartIndex: params.startIndex,
                p_PageSize: params.pageSize
            };
            //console.log(replacements);
            return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);
        } catch (e) {
            throw (e);
        } finally {
            //To close connections
            sequelize.connectionManager.close().then(() => console.log('Connection Closed'));
        }
    }

XTRDatabaseConnection.prototype.executeQuerySequelize = function (sequelize, query, queryType, replacements) {
    return sequelize.authenticate()
        .then(() => {
            return sequelize.query(query, {
                replacements: replacements,
                type: queryType
            }).
            then(result => result)
                .catch(err => {
                    throw (err);
                });
        })
        .catch(err => {
            xtrUtility.logErrorsToWinstonTransports('Unable to connect to the database or some error occurred while executing your query. ', err);
            throw new AppError(err, "dbError", "Unable to connect to the database or some error occurred while executing your query.");
        });
}

Body:
Node.js is working on single thread. So you need use it for small process with async calls. When you use async/await you are blocking the callback function.

So you need to use your database functions as promise. It will work async.

.query('CALL someFunction()')
.then(function(response){
      //done
    }).error(function(err){
     //error
});

But there is a problem about it. You need to load 21 times your result. So in this case you need to use recursive function. When you finished recursive call you can send your data to client as async.


问:
How to find last number (in a row) for a certain variable using excel
The implementation include a lot of data. For simple example in this Image I should be able to find the last number in the row either "500" for "Amy", "700" for "Sam", etc.

Kindly need all your help to figure this out.
Thanks in advance..

答:
The following formula entered as array formula (by using Ctrl+Shift+Enter) could be used:

```<code>=INDEX($C$2:$C$9,MAX(($A$2:$A$9=E2)*(ROW($A$2:$A$9)-ROW($A$2)+1)))
</code>```

For F2, where the last amount for Amy is being calculated:

($A$2:$A$9=E2) returns an array of True and False for those that match Amy

(ROW($A$2:$A$9)-ROW($A$2)+1) gives an array for the rows in the dataset. $A$2:$A$9 is the range for the names, $A$2 is the first name in the dataset.

The two above multipled together gives the row numbers in which Amy was found.

MAX() then gives the highest row number, which is used by INDEX to retrieve the Amount matching this row number.

Body:
The following formula entered as array formula (by using Ctrl+Shift+Enter) could be used:

=INDEX($C$2:$C$9,MAX(($A$2:$A$9=E2)*(ROW($A$2:$A$9)-ROW($A$2)+1)))

For F2, where the last amount for Amy is being calculated:

($A$2:$A$9=E2) returns an array of True and False for those that match Amy

(ROW($A$2:$A$9)-ROW($A$2)+1) gives an array for the rows in the dataset. $A$2:$A$9 is the range for the names, $A$2 is the first name in the dataset.

The two above multipled together gives the row numbers in which Amy was found.

MAX() then gives the highest row number, which is used by INDEX to retrieve the Amount matching this row number.


问:
Scala convention for Future type if result doesn't matter
I have a future for which I care if it completes successfully, but the result is meaningless. One such example is a Future that saves or deletes a record from a DB.
What is the best way to represent such future? Future[Any]? Future[Unit]?</p>

答:
Future[Unit] would be better. You can use callback with your future as it returns unit. So, there will be success or failure.

```<code>futureResult.onComplete{
case Success(result) => //code
case Failure(ex) => ex.printStackTrace
}
</code>```

Body:
Future[Unit] would be better. You can use callback with your future as it returns unit. So, there will be success or failure.

futureResult.onComplete{
case Success(result) => //code
case Failure(ex) => ex.printStackTrace
}


问:
Fedex PHP API Integration for indian address
Does anyone integrated fedex API in PHP to generate tracking numbers and shipping label? I am submitting below XML to fedex -

```<code><?xml version="1.0" encoding="UTF-8"?>

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:m0="http://fedex.com/ws/ship/v19">

<SOAP-ENV:Body>

<ProcessShipmentRequest xmlns="http://fedex.com/ws/ship/v19">

<WebAuthenticationDetail>

<UserCredential>

<Key>avpSZAQRg9gu3zfm</Key>

<Password>gSmYLbjJwCYYVsoIwfp2ux2FY</Password>

</UserCredential>

</WebAuthenticationDetail>

<ClientDetail>

<AccountNumber>604794161</AccountNumber>

<MeterNumber>100339204</MeterNumber>

</ClientDetail>

<TransactionDetail>

<CustomerTransactionId>8787</CustomerTransactionId>

</TransactionDetail>

<Version>

<ServiceId>ship</ServiceId>

<Major>19</Major>

<Intermediate>0</Intermediate>

<Minor>0</Minor>

</Version>

<RequestedShipment>

<ShipTimestamp>2017-07-29T12:34:56-06:00</ShipTimestamp>

<DropoffType>REGULAR_PICKUP</DropoffType>

<ServiceType>STANDARD_OVERNIGHT</ServiceType>

<PackagingType>YOUR_PACKAGING</PackagingType>

<Shipper>

<Contact>

<PersonName>Piyush Rana</PersonName>

<CompanyName>Eclators</CompanyName>

<PhoneNumber>9925383633</PhoneNumber>

<EMailAddress>rana@gmail.com</EMailAddress>

</Contact>

<Address>

<StreetLines>14-B-5</StreetLines>

<StreetLines>DkPark</StreetLines>

<City>Surat</City>

<StateOrProvinceCode>Gujarat</StateOrProvinceCode>

<PostalCode>395007</PostalCode>

<CountryCode>IN</CountryCode>

</Address>

</Shipper>

<Recipient>

<Contact>

<PersonName>Panakj Rana</PersonName>

<CompanyName>pp</CompanyName>

<PhoneNumber>9252905058</PhoneNumber>

<EMailAddress>php.pankaj@gmail.com</EMailAddress>

</Contact>

<Address>

<StreetLines>Near yadav floor mill</StreetLines>

<StreetLines>sarvodaya basti</StreetLines>

<City>Bikaner</City>

<StateOrProvinceCode>rajasthan</StateOrProvinceCode>

<PostalCode>334004</PostalCode>

<CountryCode>IN</CountryCode>

</Address>

</Recipient>

<ShippingChargesPayment>

<PaymentType>SENDER</PaymentType>

<Payor>

<ResponsibleParty>

<AccountNumber>604794161</AccountNumber>

<Contact>

<ContactId>12345</ContactId>

<PersonName>shanu rana</PersonName>

</Contact>

</ResponsibleParty>

</Payor>

</ShippingChargesPayment>

<SpecialServicesRequested>

<SpecialServiceTypes>ELECTRONIC_TRADE_DOCUMENTS</SpecialServiceTypes>

</SpecialServicesRequested>

<CustomsClearanceDetail>

<DutiesPayment>

<PaymentType>SENDER</PaymentType>

<Payor>

<ResponsibleParty>

<AccountNumber>604794161</AccountNumber>

<Contact>

<ContactId>12345</ContactId>

<PersonName>Input Your Information</PersonName>

</Contact>

</ResponsibleParty>

</Payor>

</DutiesPayment>

<DocumentContent>DOCUMENTS_ONLY</DocumentContent>

<CustomsValue>

<Currency>INR</Currency>

<Amount>100.00</Amount>

</CustomsValue>

<Commodities>

<NumberOfPieces>1</NumberOfPieces>

<Description>ABCD</Description>

<CountryOfManufacture>US</CountryOfManufacture>

<Weight>

<Units>LB</Units>

<Value>1.0</Value>

</Weight>

<Quantity>1</Quantity>

<QuantityUnits>cm</QuantityUnits>

<UnitPrice>

<Currency>INR</Currency>

<Amount>1.000000</Amount>

</UnitPrice>

<CustomsValue>

<Currency>INR</Currency>

<Amount>100.000000</Amount>

</CustomsValue>

</Commodities>

<ExportDetail>

<ExportComplianceStatement>30.37(f)</ExportComplianceStatement>

</ExportDetail>

</CustomsClearanceDetail>

<LabelSpecification>

<LabelFormatType>COMMON2D</LabelFormatType>

<ImageType>PNG</ImageType>

<LabelStockType>PAPER_7X4.75</LabelStockType>

</LabelSpecification>

<ShippingDocumentSpecification>

<ShippingDocumentTypes>COMMERCIAL_INVOICE</ShippingDocumentTypes>

<CommercialInvoiceDetail>

<Format>

<ImageType>PDF</ImageType>

<StockType>PAPER_LETTER</StockType>

<ProvideInstructions>1</ProvideInstructions>

</Format>

</CommercialInvoiceDetail>

</ShippingDocumentSpecification>

<RateRequestTypes>LIST</RateRequestTypes>

<PackageCount>1</PackageCount>

<RequestedPackageLineItems>

<SequenceNumber>1</SequenceNumber>

<Weight>

<Units>LB</Units>

<Value>20.0</Value>

</Weight>

<Dimensions>

<Length>12</Length>

<Width>12</Width>

<Height>12</Height>

<Units>IN</Units>

</Dimensions>

<CustomerReferences>

<CustomerReferenceType>CUSTOMER_REFERENCE</CustomerReferenceType>

<Value>TC001_01_PT1_ST01_PK01_SNDUS_RCPCA_POS</Value>

</CustomerReferences>

</RequestedPackageLineItems>

</RequestedShipment>

</ProcessShipmentRequest>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>
</code>```

But getting below output -

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [xmlnsSOAPENV] => http//schemas.xmlsoap.org/soap/envelope/
        )

```<code>[SOAPENVHeader] => SimpleXMLElement Object
    (
    )

[SOAPENVBody] => SimpleXMLElement Object
    (
        [ProcessShipmentReply] => SimpleXMLElement Object
            (
                [HighestSeverity] => ERROR
                [Notifications] => SimpleXMLElement Object
                    (
                        [Severity] => ERROR
                        [Source] => ship
                        [Code] => 2200
                        [Message] => Missing or Invalid Shipment purpose for Commercial Invoice
                        [LocalizedMessage] => Missing or Invalid Shipment purpose for Commercial Invoice
                    )

                [TransactionDetail] => SimpleXMLElement Object
                    (
                        [CustomerTransactionId] => 8787
                    )

                [Version] => SimpleXMLElement Object
                    (
                        [ServiceId] => ship
                        [Major] => 19
                        [Intermediate] => 0
                        [Minor] => 0
                    )

            )

    )
</code>```

)

What is the issue with this api? Please suggest. Or if anyone already integrated then please provide us the code snippet which i can use to generate fedex tracking number and shipping label.

答: Actually, you have the wrong structure of sending the request. You should add CommercialInvoice under CustomsClearanceDetail. This error is occurring due to wrong placement of request parameters in the request.

Body:
Does anyone integrated fedex API in PHP to generate tracking numbers and shipping label? I am submitting below XML to fedex -

<?xml version="1.0" encoding="UTF-8"?>

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:m0="http://fedex.com/ws/ship/v19">

<SOAP-ENV:Body>

<ProcessShipmentRequest xmlns="http://fedex.com/ws/ship/v19">

<WebAuthenticationDetail>

<UserCredential>

<Key>avpSZAQRg9gu3zfm</Key>

<Password>gSmYLbjJwCYYVsoIwfp2ux2FY</Password>

</UserCredential>

</WebAuthenticationDetail>

<ClientDetail>

<AccountNumber>604794161</AccountNumber>

<MeterNumber>100339204</MeterNumber>

</ClientDetail>

<TransactionDetail>

<CustomerTransactionId>8787</CustomerTransactionId>

</TransactionDetail>

<Version>

<ServiceId>ship</ServiceId>

<Major>19</Major>

<Intermediate>0</Intermediate>

<Minor>0</Minor>

</Version>

<RequestedShipment>

<ShipTimestamp>2017-07-29T12:34:56-06:00</ShipTimestamp>

<DropoffType>REGULAR_PICKUP</DropoffType>

<ServiceType>STANDARD_OVERNIGHT</ServiceType>

<PackagingType>YOUR_PACKAGING</PackagingType>

<Shipper>

<Contact>

<PersonName>Piyush Rana</PersonName>

<CompanyName>Eclators</CompanyName>

<PhoneNumber>9925383633</PhoneNumber>

<EMailAddress>rana@gmail.com</EMailAddress>

</Contact>

<Address>

<StreetLines>14-B-5</StreetLines>

<StreetLines>DkPark</StreetLines>

<City>Surat</City>

<StateOrProvinceCode>Gujarat</StateOrProvinceCode>

<PostalCode>395007</PostalCode>

<CountryCode>IN</CountryCode>

</Address>

</Shipper>

<Recipient>

<Contact>

<PersonName>Panakj Rana</PersonName>

<CompanyName>pp</CompanyName>

<PhoneNumber>9252905058</PhoneNumber>

<EMailAddress>php.pankaj@gmail.com</EMailAddress>

</Contact>

<Address>

<StreetLines>Near yadav floor mill</StreetLines>

<StreetLines>sarvodaya basti</StreetLines>

<City>Bikaner</City>

<StateOrProvinceCode>rajasthan</StateOrProvinceCode>

<PostalCode>334004</PostalCode>

<CountryCode>IN</CountryCode>

</Address>

</Recipient>

<ShippingChargesPayment>

<PaymentType>SENDER</PaymentType>

<Payor>

<ResponsibleParty>

<AccountNumber>604794161</AccountNumber>

<Contact>

<ContactId>12345</ContactId>

<PersonName>shanu rana</PersonName>

</Contact>

</ResponsibleParty>

</Payor>

</ShippingChargesPayment>

<SpecialServicesRequested>

<SpecialServiceTypes>ELECTRONIC_TRADE_DOCUMENTS</SpecialServiceTypes>

</SpecialServicesRequested>

<CustomsClearanceDetail>

<DutiesPayment>

<PaymentType>SENDER</PaymentType>

<Payor>

<ResponsibleParty>

<AccountNumber>604794161</AccountNumber>

<Contact>

<ContactId>12345</ContactId>

<PersonName>Input Your Information</PersonName>

</Contact>

</ResponsibleParty>

</Payor>

</DutiesPayment>

<DocumentContent>DOCUMENTS_ONLY</DocumentContent>

<CustomsValue>

<Currency>INR</Currency>

<Amount>100.00</Amount>

</CustomsValue>

<Commodities>

<NumberOfPieces>1</NumberOfPieces>

<Description>ABCD</Description>

<CountryOfManufacture>US</CountryOfManufacture>

<Weight>

<Units>LB</Units>

<Value>1.0</Value>

</Weight>

<Quantity>1</Quantity>

<QuantityUnits>cm</QuantityUnits>

<UnitPrice>

<Currency>INR</Currency>

<Amount>1.000000</Amount>

</UnitPrice>

<CustomsValue>

<Currency>INR</Currency>

<Amount>100.000000</Amount>

</CustomsValue>

</Commodities>

<ExportDetail>

<ExportComplianceStatement>30.37(f)</ExportComplianceStatement>

</ExportDetail>

</CustomsClearanceDetail>

<LabelSpecification>

<LabelFormatType>COMMON2D</LabelFormatType>

<ImageType>PNG</ImageType>

<LabelStockType>PAPER_7X4.75</LabelStockType>

</LabelSpecification>

<ShippingDocumentSpecification>

<ShippingDocumentTypes>COMMERCIAL_INVOICE</ShippingDocumentTypes>

<CommercialInvoiceDetail>

<Format>

<ImageType>PDF</ImageType>

<StockType>PAPER_LETTER</StockType>

<ProvideInstructions>1</ProvideInstructions>

</Format>

</CommercialInvoiceDetail>

</ShippingDocumentSpecification>

<RateRequestTypes>LIST</RateRequestTypes>

<PackageCount>1</PackageCount>

<RequestedPackageLineItems>

<SequenceNumber>1</SequenceNumber>

<Weight>

<Units>LB</Units>

<Value>20.0</Value>

</Weight>

<Dimensions>

<Length>12</Length>

<Width>12</Width>

<Height>12</Height>

<Units>IN</Units>

</Dimensions>

<CustomerReferences>

<CustomerReferenceType>CUSTOMER_REFERENCE</CustomerReferenceType>

<Value>TC001_01_PT1_ST01_PK01_SNDUS_RCPCA_POS</Value>

</CustomerReferences>

</RequestedPackageLineItems>

</RequestedShipment>

</ProcessShipmentRequest>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

But getting below output -

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [xmlnsSOAPENV] => http//schemas.xmlsoap.org/soap/envelope/
        )

[SOAPENVHeader] => SimpleXMLElement Object
    (
    )

[SOAPENVBody] => SimpleXMLElement Object
    (
        [ProcessShipmentReply] => SimpleXMLElement Object
            (
                [HighestSeverity] => ERROR
                [Notifications] => SimpleXMLElement Object
                    (
                        [Severity] => ERROR
                        [Source] => ship
                        [Code] => 2200
                        [Message] => Missing or Invalid Shipment purpose for Commercial Invoice
                        [LocalizedMessage] => Missing or Invalid Shipment purpose for Commercial Invoice
                    )

                [TransactionDetail] => SimpleXMLElement Object
                    (
                        [CustomerTransactionId] => 8787
                    )

                [Version] => SimpleXMLElement Object
                    (
                        [ServiceId] => ship
                        [Major] => 19
                        [Intermediate] => 0
                        [Minor] => 0
                    )

            )

    )

)

What is the issue with this api? Please suggest. Or if anyone already integrated then please provide us the code snippet which i can use to generate fedex tracking number and shipping label.


问:
Image Skeletonization using Medial Axis Transform
My requirement is something like this:

Lets take there is a Bitmap with a big letter 'A'.
The Bitmap is two colors (Either Black or White).

I need to skeletonize the big 'A'. (see: http://en.wikipedia.org/wiki/Topological_skeleton)
Using "Medial Axis Transforming" algorithm.

I tried my best in googling but i ended up being lost in finding a C#, C++ or at least pseudo code implementation of this algorithm.

I would like if someone could help me on this.

答:
The following two articles are the ones where the Medial Axis Transform was first proposed, so I think that you can find the algorithm to implement there. Do not expect a C++/C# implementation though.

A transformation for extracting new descriptors of shape

Shape description using weighted symmetric axis features

For the first one I was able to find a URL to a pdf. For the second one you will have to have access to ScienceDirect to download.

Another approach that you can use to extract the skeleton of a shape is by the Image Foresting Transform (IFT). It consists in representing the binary image as a graph. I made an implementation of the skeletonization by IFT in Matlab using the following article:

Multiscale skeletons by image foresting transform and its applications to neuromorphometry

ContentLicense: CC BY-SA 2.5


答:
Try the following:</p>

```<code>DECLARE @Date VARCHAR(20)='JUL/11/2017'

SELECT @Date=STUFF(STUFF(@Date,1,3,RIGHT(LEFT(@Date,6),2)),4,2,LEFT(@Date,3))--,LEFT(@Date,3),RIGHT(LEFT(@Date,6),2)

IF ISDATE(@Date)=1
print 'VALID_DATE'
else
print 'INVALID_DATE'
</code>```

Title: How to validate date field with format MMM/DD/YY or MMM/DD/YYYY?

Body:
Try the following:

DECLARE @Date VARCHAR(20)='JUL/11/2017'

SELECT @Date=STUFF(STUFF(@Date,1,3,RIGHT(LEFT(@Date,6),2)),4,2,LEFT(@Date,3))--,LEFT(@Date,3),RIGHT(LEFT(@Date,6),2)

IF ISDATE(@Date)=1
print 'VALID_DATE'
else
print 'INVALID_DATE'


问:
How to pass complete Webcontrol?
I need to pass a complete Webcontrol to a method with reference that will set value of that webcontrol by determining its type.

```<code>enter code here
public void SetValue(ref WebControl,string value){
       Type t=WebControl.Gettype();

       if(t.Name== "TextBox"){
          // set TextBox Value
       }
      else if (t.Name=="Dropdown"){
      // set Dropdown value.
  }
</code>```

}

//////////////Calling of above function in aspx.cs file.

```<code>SetValue(ref txEmployee,"123");
</code>```

I am using asp.net Webforms.

答:
Box control into object and work with object itself.

```<code>//Method
public void SetValue(ref object oWebControl,string value){
       switch (oWebControl.GetType().Name)
        {
            case "RadioButton": { /*do stuff here*/} break;
            case "DropDownList": { /*do stuff here*/} break;
            case "TextBox": { /*do here*/} break;
            /*more checking here*/
            default: break;
        }
  }

//Box the control (Boxing)
//For RadioButton
object o = RadioButton as object;
//For DropDownList
object o = DropDownList as object;
//For TextBox
object o = TextBox as object;
/*more control here*/

//Call Method
SetValue(ref o,"123");
</code>```

I hope this is something you are looking for.

Title: How to pass complete Webcontrol?

Body:
I need to pass a complete Webcontrol to a method with reference that will set value of that webcontrol by determining its type.

enter code here
public void SetValue(ref WebControl,string value){
       Type t=WebControl.Gettype();

       if(t.Name== "TextBox"){
          // set TextBox Value
       }
      else if (t.Name=="Dropdown"){
      // set Dropdown value.
  }

}

//////////////Calling of above function in aspx.cs file.

SetValue(ref txEmployee,"123");

I am using asp.net Webforms.

Body:
Box control into object and work with object itself.

//Method
public void SetValue(ref object oWebControl,string value){
       switch (oWebControl.GetType().Name)
        {
            case "RadioButton": { /*do stuff here*/} break;
            case "DropDownList": { /*do stuff here*/} break;
            case "TextBox": { /*do here*/} break;
            /*more checking here*/
            default: break;
        }
  }

//Box the control (Boxing)
//For RadioButton
object o = RadioButton as object;
//For DropDownList
object o = DropDownList as object;
//For TextBox
object o = TextBox as object;
/*more control here*/

//Call Method
SetValue(ref o,"123");

I hope this is something you are looking for.


问:
Regular expression to exclude a string/character in nodejs
Currently I have a variable that has turnallplugsoffR1, turnallplugsonR1.
I wanted to exclude R1 from the string and get only turnallplugsoff in my variable in nodejs.
Could you please help me in achieving the same?
dataval="turnallplugsoffR1"</p>

```<code>var room_value=dataval.match(/R[0-9]+/i); //matched R1/R2 any other string
    console.log(excl); // i want only turnallplugsoff. I dont want R1/R2
    console.log(room_value[0]);
</code>```

答:
Just split the string with R1 and get the value you want.</p>

```<code>dataval="turnallplugsoffR1"
var room_value= dataval.split('R1');
alert(data[0]);
</code>```

Body:
Currently I have a variable that has turnallplugsoffR1, turnallplugsonR1.
I wanted to exclude R1 from the string and get only turnallplugsoff in my variable in nodejs.
Could you please help me in achieving the same?
dataval="turnallplugsoffR1"

var room_value=dataval.match(/R[0-9]+/i); //matched R1/R2 any other string
    console.log(excl); // i want only turnallplugsoff. I dont want R1/R2
    console.log(room_value[0]);

Body:
Just split the string with R1 and get the value you want.

dataval="turnallplugsoffR1"
var room_value= dataval.split('R1');
alert(data[0]);


问:
Golang Mysql connectex socket block
I use the "go-sql-driver/mysql" driver.
I have a product table that has a few dependencies. So i Select the product and get dependencies that would create cartesian products in subqueries. Usually there is a 200 products limit to have a better performance but in rare cases the limit will be removed or raised to lets say 3000-5000 then then i will get the following error:

dial tcp 127.0.0.1:3306: connectex: Normalerweise darf jede
  Socketadresse (Protokoll, Netzwerkadresse oder Anschluss) nur jeweils
  einmal verwendet werden.

which basically means:

connectex: Use every Socketaddress only once.

This is a snipped from my code, basically all my query-functions are build like that:

```<code>mysql := this.DBController.Connect()
defer mysql.Close()
.
.
.
for rows.Next() {
    err := rows.Scan(&x, &y, &z)
    if err != nil {
        log.Println("DBFetchMachines: Scan Error")
        log.Println(err)
    }
    product.PurchasePrice = this.priceR.DBFetchPurchasePriceByProductID(product.ID)
    product.SellingPrice = this.priceR.DBFetchSellingPriceByProductID(product.ID)
    product.DealerContact = this.contactR.DBGetBasicContact(product.DealerContact.ID)
    .
    .
    .
}
</code>```

When i just query 200-1000 rows there is no issue.
Is this maybe a OS related issue? I use Win10 64Bit as my dev machine.

答: As reticentroot in the comments suggested i checked  alexedwards.net/blog/organising-database-access for some best practices examples. I choose Dependency injection and it works like a charm.

Title: Golang Mysql connectex socket block

Body:
I use the "go-sql-driver/mysql" driver.
I have a product table that has a few dependencies. So i Select the product and get dependencies that would create cartesian products in subqueries. Usually there is a 200 products limit to have a better performance but in rare cases the limit will be removed or raised to lets say 3000-5000 then then i will get the following error:

dial tcp 127.0.0.1:3306: connectex: Normalerweise darf jede
  Socketadresse (Protokoll, Netzwerkadresse oder Anschluss) nur jeweils
  einmal verwendet werden.

which basically means:

connectex: Use every Socketaddress only once.

This is a snipped from my code, basically all my query-functions are build like that:

mysql := this.DBController.Connect()
defer mysql.Close()
.
.
.
for rows.Next() {
    err := rows.Scan(&x, &y, &z)
    if err != nil {
        log.Println("DBFetchMachines: Scan Error")
        log.Println(err)
    }
    product.PurchasePrice = this.priceR.DBFetchPurchasePriceByProductID(product.ID)
    product.SellingPrice = this.priceR.DBFetchSellingPriceByProductID(product.ID)
    product.DealerContact = this.contactR.DBGetBasicContact(product.DealerContact.ID)
    .
    .
    .
}

When i just query 200-1000 rows there is no issue.
Is this maybe a OS related issue? I use Win10 64Bit as my dev machine.


问:
pointers in matrix multiplication not working
```<code>class mm
{
    public :
    static int** multiPlyMatrix(int** matrix1, int** matrix2,int r1,int c1,int r2,int c2) {
    int** multiplication;

    if (c1==r2)
    {
    multiplication=new int*[r1];
    for (int row = 0; row < r1; row++)
    {
        multiplication[row]=new int[c2];

        for (int colIndex = 0; colIndex <c2; colIndex++)
        {
            for (int col = 0; col <r2; col++)
            {
                multiplication[row][colIndex] = multiplication[row][colIndex] + matrix1[row][col] * matrix2[col][colIndex];
            }
        }
    }
    }else
    {
           cout<<"Multiplication Not Possible"<<endl;
    }
        return multiplication;
    }

    static void deleteMemory(int** array,int rows)
    {
        if(array)
        {
            for(int i=0;i<rows;i++)
            {
                if(array[i])
                {
                    delete[]array[i];
                }
            }
            delete[] array;
        }
    }
};
void main()
{
    mm obj;
    int r,c;
    char ch;
    int rows,cols,rows2,cols2;
    int** matrix1;
    int** matrix2;
    int** result;
    do{
     rows=0,cols=0,rows2=0,cols2=0;
    clrscr();
    cout<<"Enter number of rows:";
    cin>>rows;
    cout<<"Enter number of columns:";
    cin>>cols;
    matrix1=new int* [rows];
    cout<<"Enter Elements in Matrix 1:"<<endl;
    for ( r = 0; r < rows; r++)
    {
        matrix1[r]=new int[cols];
        for ( c = 0; c < cols; c++)
        {
         cin>>matrix1[r][c];
        }
    }

    cout<<"Enter number of rows:";
    cin>>rows2;
    cout<<"Enter number of columns:";
    cin>>cols2;
    matrix2=new int* [rows2];
    cout<<"Enter Elements in matrix2:"<<endl;
    for ( r = 0; r < rows2; r++)
    {
        matrix2[r]=new int[cols2];
        for ( c = 0; c < cols2; c++)
        {
        cin>>matrix2[r][c];
        }
    }
    result=obj.multiPlyMatrix(matrix1, matrix2,rows,cols,rows2,cols2);

    cout<<"Multiplication of matrix:"<<endl;

    for ( r = 0; r < rows; r++)
    {
        cout<<"|";
        for ( c = 0; c < cols2; c++)
        {
         cout<<result[r][c] << " ";
        }
        cout<<"|"<<endl;
    }

    obj.deleteMemory(matrix1,rows);
    obj.deleteMemory(matrix2,rows2);
    obj.deleteMemory(result,rows);
    cout<<"\nWanna Enter Again?(y/n):";
    cin>>ch;
    }while(ch=='y'||ch=='Y');
}
</code>```

So, thats full code, program works perfectly for first run but when i run it second time it gives garbage value as output, when i exit IDE and open it again it will run great for first time then again it will give garbage value,
what am I doing wrong?

I think theres some problem with delete method and I use turbo c++ as IDE and gcc compiler

答:
What do you expect multiplication[row][colIndex] to be the first time the line of code using it gets hit?  (Just to be perfectly clear, you need to initialize it before you read it.)

This'd be obvious in a debugger.  Learn cgdb (on Cygwin or WSL) or try the Oracle Netbeans C++ download package.  The VS 2017 Community Edition can also work with gcc and cmake (a little less so with straight Makefiles).

```<code>multiplication[row]=new int[c2];

for (int colIndex = 0; colIndex <c2; colIndex++)
{
    for (int col = 0; col <r2; col++)
    {
        multiplication[row][colIndex] = multiplication[row][colIndex] + matrix1[row][col] * matrix2[col][colIndex];
</code>```

Body:
class mm
{
    public :
    static int** multiPlyMatrix(int** matrix1, int** matrix2,int r1,int c1,int r2,int c2) {
    int** multiplication;

    if (c1==r2)
    {
    multiplication=new int*[r1];
    for (int row = 0; row < r1; row++)
    {
        multiplication[row]=new int[c2];

        for (int colIndex = 0; colIndex <c2; colIndex++)
        {
            for (int col = 0; col <r2; col++)
            {
                multiplication[row][colIndex] = multiplication[row][colIndex] + matrix1[row][col] * matrix2[col][colIndex];
            }
        }
    }
    }else
    {
           cout<<"Multiplication Not Possible"<<endl;
    }
        return multiplication;
    }

    static void deleteMemory(int** array,int rows)
    {
        if(array)
        {
            for(int i=0;i<rows;i++)
            {
                if(array[i])
                {
                    delete[]array[i];
                }
            }
            delete[] array;
        }
    }
};
void main()
{
    mm obj;
    int r,c;
    char ch;
    int rows,cols,rows2,cols2;
    int** matrix1;
    int** matrix2;
    int** result;
    do{
     rows=0,cols=0,rows2=0,cols2=0;
    clrscr();
    cout<<"Enter number of rows:";
    cin>>rows;
    cout<<"Enter number of columns:";
    cin>>cols;
    matrix1=new int* [rows];
    cout<<"Enter Elements in Matrix 1:"<<endl;
    for ( r = 0; r < rows; r++)
    {
        matrix1[r]=new int[cols];
        for ( c = 0; c < cols; c++)
        {
         cin>>matrix1[r][c];
        }
    }

    cout<<"Enter number of rows:";
    cin>>rows2;
    cout<<"Enter number of columns:";
    cin>>cols2;
    matrix2=new int* [rows2];
    cout<<"Enter Elements in matrix2:"<<endl;
    for ( r = 0; r < rows2; r++)
    {
        matrix2[r]=new int[cols2];
        for ( c = 0; c < cols2; c++)
        {
        cin>>matrix2[r][c];
        }
    }
    result=obj.multiPlyMatrix(matrix1, matrix2,rows,cols,rows2,cols2);

    cout<<"Multiplication of matrix:"<<endl;

    for ( r = 0; r < rows; r++)
    {
        cout<<"|";
        for ( c = 0; c < cols2; c++)
        {
         cout<<result[r][c] << " ";
        }
        cout<<"|"<<endl;
    }

    obj.deleteMemory(matrix1,rows);
    obj.deleteMemory(matrix2,rows2);
    obj.deleteMemory(result,rows);
    cout<<"\nWanna Enter Again?(y/n):";
    cin>>ch;
    }while(ch=='y'||ch=='Y');
}

So, thats full code, program works perfectly for first run but when i run it second time it gives garbage value as output, when i exit IDE and open it again it will run great for first time then again it will give garbage value,
what am I doing wrong?

I think theres some problem with delete method and I use turbo c++ as IDE and gcc compiler

Body:
What do you expect multiplication[row][colIndex] to be the first time the line of code using it gets hit?  (Just to be perfectly clear, you need to initialize it before you read it.)

This'd be obvious in a debugger.  Learn cgdb (on Cygwin or WSL) or try the Oracle Netbeans C++ download package.  The VS 2017 Community Edition can also work with gcc and cmake (a little less so with straight Makefiles).

multiplication[row]=new int[c2];

for (int colIndex = 0; colIndex <c2; colIndex++)
{
    for (int col = 0; col <r2; col++)
    {
        multiplication[row][colIndex] = multiplication[row][colIndex] + matrix1[row][col] * matrix2[col][colIndex];


问:
How to figure out used JARs?
In a bigger project we might be using tons of JARs. How do I find out which JARs are being used by a certain module/package in the project (not the whole project). Any tool, technique,  etc?</p>

答:
Bigger projects typically use a build tool like maven or ant.  maven has the maven dependency plugin to list the dependencies for a particular project which you invoke by mvn dependency:list.  In case of ant, it depends on the way the build script is written.

Maybe you should give more details about your project environment and you may get better answers.

Title: How to figure out used JARs?


问:
dd fail to write to tmpfs
I'd like to measure tmpfs performance by using dd. But it fail, like below:

```<code># dd if=/dev/zero of=/tmp/128M bs=4M count=32 oflag=direct
dd: failed to open ‘/tmp/128M’: Invalid argument
</code>```

Any help?

答:
Vasily Tarasov solution worked with NFS too.
I had:

```<code>dd if=/dev/urandom of=TEST.200GB iflag=direct bs=1M count=204800
dd: failed to open ‘/dev/urandom’: Invalid argument
</code>```

then I have removed iflag=direct and it worked

Title: dd fail to write to tmpfs

Body:
I'd like to measure tmpfs performance by using dd. But it fail, like below:

# dd if=/dev/zero of=/tmp/128M bs=4M count=32 oflag=direct
dd: failed to open ‘/tmp/128M’: Invalid argument

Any help?

Body:
Vasily Tarasov solution worked with NFS too.
I had:

dd if=/dev/urandom of=TEST.200GB iflag=direct bs=1M count=204800
dd: failed to open ‘/dev/urandom’: Invalid argument

then I have removed iflag=direct and it worked


问:
Is there any way to make R Shiny support multiple users? I'm talking about hundreds of concurrent users
Is there any way to make R Shiny support multiple users? I'm talking about hundreds of concurrent users.
To add some context: I'm not talking about Authentication (username / password). That will be taken care of by Auth0 (see auth0.com). So AFTER they are logged in, I see that Shiny Server does not pass the username to the Shiny session (maybe deliberately, so that you are forced to purchase the Commercial license to Shiny Server?).My question is more about : a) how do I make it recognize the username of the logged in user? b) will it scale to hundreds of concurrent (simultaneous) users?</p>

答:
With the Shiny-Pro you can enable Authentification. The server then gives the App information about username over the variable session$user.

In the basic version Shiny-Pro can handle 20 Concurrent users but you can buy an extension so that it can handle up to 120 - 150 concurrent Users.


问:
Make text bold in SQLite
I'm new to Android I want to make some text bold or italic or insert a new paragraph in Android sqlite database.db
I know that I can do it using HTML tags but it doesn't show in the app it displays tags instead of bold or italic text. Can anyone help here is my code
https://drive.google.com/file/d/0B7KpqDyiTdk5cVc0X2t3N3F1WjA/view
I could have pasted it here but stack overflow doesn't let me paste that much code.

Also it would be a huge help if any one can tell me how can I mark some words as favorite and display them in new activity.

Thanks

答:
While setting text in textview use this - </p>

```<code>yourTextView.setText(Html.fromHtml(yourStrinfFromDb));
</code>```

Title: Make text bold in SQLite

Body:
While setting text in textview use this -

yourTextView.setText(Html.fromHtml(yourStrinfFromDb));


问:
How to move the three images and text towards right in layout?
I have an icon with images at left followed by text.

And towards right, there should be three images and three text below the three images. I done everything but problem is i couldn't move the three images and text towards right side.

Though I gave in LinearLayout (for reference: android:id="@+id/right_side_layout") android:gravity="right|end" it's not moving towards right side.

Here is layout and screenshot.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_mark" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_profile" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_number"
                android:textColor="@color/black"
                android:textSize="@dimen/text_size_very_small" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_name"
                android:textColor="@color/dark_green"
                android:textSize="@dimen/text_size_very_small" />

        </LinearLayout>
  <!--
        This layout should be right side. Though I given  android:gravity="right|end" it's not moving right.
    -->
        <LinearLayout
            android:id="@+id/right_side_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="28dp"
            android:layout_weight="1"
            android:gravity="right|end"
            android:orientation="horizontal">

            <RelativeLayout
                android:id="@+id/relative"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/sell_in_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_red" />

                <TextView
                    android:id="@+id/textLabel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_red"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="In"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="9dp"
                android:layout_marginRight="9dp">

                <ImageView
                    android:id="@+id/sell_in_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_in_yellow" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_yellow"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="Out"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/growth_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_green" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/growth_icon"
                    android:layout_centerInParent="true"
                    android:gravity="center"
                    android:paddingTop="2dp"
                    android:text="growth"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

You can see the below image where three circular icons are not moving towards right side.

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="route_plan_default_number"
                android:textColor="@color/black"
                android:textSize="12dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="route_plan_default_name"
                android:textColor="@color/black"
                android:textSize="18dp" />

        </LinearLayout>
        <LinearLayout
            android:id="@+id/right_side_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="28dp"
            android:layout_weight="1"
            android:gravity="right|end"
            android:weightSum="3"
            android:orientation="horizontal">

            <RelativeLayout
                android:id="@+id/relative"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/sell_in_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_launcher" />

                <TextView
                    android:id="@+id/textLabel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="In "
                    android:layout_centerHorizontal="true"
                    android:layout_below="@+id/sell_in_red"
                    android:textSize="15dp"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="9dp"
                android:layout_weight="1"
                android:layout_marginRight="9dp">

                <ImageView
                    android:id="@+id/sell_in_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_launcher" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_below="@+id/sell_in_yellow"
                    android:paddingTop="2dp"
                    android:text="Out"
                    android:textSize="15dp"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/growth_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_launcher" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_below="@+id/growth_icon"
                    android:gravity="center"
                    android:paddingTop="2dp"
                    android:text="growth"
                    android:textSize="15dp"
                    android:textStyle="bold" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</code>```

Body:
I have an icon with images at left followed by text.

And towards right, there should be three images and three text below the three images. I done everything but problem is i couldn't move the three images and text towards right side.

Though I gave in LinearLayout (for reference: android:id="@+id/right_side_layout") android:gravity="right|end" it's not moving towards right side.

Here is layout and screenshot.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_mark" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_profile" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_number"
                android:textColor="@color/black"
                android:textSize="@dimen/text_size_very_small" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_name"
                android:textColor="@color/dark_green"
                android:textSize="@dimen/text_size_very_small" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/right_side_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="28dp"
            android:layout_weight="1"
            android:gravity="right|end"
            android:orientation="horizontal">

            <RelativeLayout
                android:id="@+id/relative"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/sell_in_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_red" />

                <TextView
                    android:id="@+id/textLabel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_red"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="In"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="9dp"
                android:layout_marginRight="9dp">

                <ImageView
                    android:id="@+id/sell_in_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_in_yellow" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_yellow"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="Out"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/growth_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_green" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/growth_icon"
                    android:layout_centerInParent="true"
                    android:gravity="center"
                    android:paddingTop="2dp"
                    android:text="growth"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

You can see the below image where three circular icons are not moving towards right side.


问:
Java making sublist from array list and store into array list of list of objects
I have a list of object. I want to make sublist from the arraylist.. according to the file size.

Example:

```<code>[{
        "name": "food_image1.jpeg",
        "fileSize": 10
    },
    {
        "name": "food_image2.jpeg",
        "fileSize": 20
    },
    {
        "name": "food_image3.jpeg",
        "fileSize": 30
    },
    {
        "name": "food_image4.jpeg",
        "fileSize": 10
    }
]
</code>```

My fixed size is: 40;

so my sublist will be:

```<code>[
    [{
            "name": "food_image1.jpeg",
            "fileSize": 10
        },
        {
            "name": "food_image2.jpeg",
            "fileSize": 20
        },
        {
            "name": "food_image4.jpeg",
            "fileSize": 10
        }
    ],
    [{
        "name": "food_image3.jpeg",
        "fileSize": 30
    }]
]
</code>```

So, I have mojo object FileInfo.java with two properties

```<code>public class FileInfo{

    private String name;
    private Long fileSize;
 //setter and getters
}
</code>```

and my logic is:

```<code> public List<List<FileInfo>> getAllSublistFromList(){

        //fixed size data
        long fixedPartSize =40;
        long tempSize = 0;
        long finalSize = 0;

        //here I am fetching all the list
        List<FileInfo> fileInfoList = jsondataList();

        List<FileInfo> makeSublist = new ArrayList<>();

        //Initializing list of DriveFileInfo object within a list.
        List<List<FileInfo>> allDataAspart = new ArrayList<>();

        //iterating arraylist of DriveFileInfo object
        for (int i = fileInfoList.size() - 1; i >= 0; i--) {

                //first fetching filesize of every DriveFileInfo object

                tempSize = fileInfoList.get(i).getFileSize();

                //checking if the file exist or not

                if (tempSize >= 1) {

                    //if the file exist keep it as finalSize.

                    finalSize = finalSize + tempSize;

                    //now checking new size is greater than fixed size or not.

                    if (finalSize <= fixedPartSize) {

                        //if the finalSize is lessar than fixedSize then add to ArrayList,named makeSublist
                        makeSublist.add(fileInfoList.get(i));

                        //after adding to the list remove index from  makeSublist Arraylist
                        fileInfoList.remove(i);
                    } else {
                        finalSize = 0;

                        //if the finalSize is greater than fixedSize then add to ArrayList of Arraylist,named allDataAspart
                        allDataAspart.add(makeSublist);

                        //and clean the arraylist means initialize makeSublist arraylist data
                        makeSublist = new ArrayList<>();
                    }
                }

                //checking if the file not exist
                else {
                    //remove the index from fileInfoList arraylist
                    fileInfoList.remove(i);
                }
            }
            allDataAspart.add(makeSublist);

        //returning the arraylist of List object data.
        return allDataAspart;
    }
</code>```

But I am not getting proper list from the list..some files are missing when the list is long and fixed size is change.. please help me guys..

答:
How about this:</p>

```<code>public List<List<FileInfo>> partition(List<FileInfo> list, int maxSize) {
    List<List<FileInfo>> result = new ArrayList<>();
    List<FileInfo> current = new ArrayList<>();
    int currentSize = 0;
    for (FileInfo fi: list) {
        if (fi.getFileSize() > 0) {
            if (!current.isEmpty()
                    && currentSize + fi.getFileSize() > maxSize) {
                result.add(current);
                current = new ArrayList<>();
                currentSize = 0;
            }
            current.add(fi);
            currentSize += fi.getFileSize();
        }
    }
    if (!current.isEmpty()) {
        result.add(current);
    }
    return result;
}
</code>```

Body:
I have a list of object. I want to make sublist from the arraylist.. according to the file size.

Example:

[{
        "name": "food_image1.jpeg",
        "fileSize": 10
    },
    {
        "name": "food_image2.jpeg",
        "fileSize": 20
    },
    {
        "name": "food_image3.jpeg",
        "fileSize": 30
    },
    {
        "name": "food_image4.jpeg",
        "fileSize": 10
    }
]

My fixed size is: 40;

so my sublist will be:

[
    [{
            "name": "food_image1.jpeg",
            "fileSize": 10
        },
        {
            "name": "food_image2.jpeg",
            "fileSize": 20
        },
        {
            "name": "food_image4.jpeg",
            "fileSize": 10
        }
    ],
    [{
        "name": "food_image3.jpeg",
        "fileSize": 30
    }]
]

So, I have mojo object FileInfo.java with two properties

public class FileInfo{

    private String name;
    private Long fileSize;
 //setter and getters
}

and my logic is:

 public List<List<FileInfo>> getAllSublistFromList(){

        //fixed size data
        long fixedPartSize =40;
        long tempSize = 0;
        long finalSize = 0;

        //here I am fetching all the list
        List<FileInfo> fileInfoList = jsondataList();

        List<FileInfo> makeSublist = new ArrayList<>();

        //Initializing list of DriveFileInfo object within a list.
        List<List<FileInfo>> allDataAspart = new ArrayList<>();

        //iterating arraylist of DriveFileInfo object
        for (int i = fileInfoList.size() - 1; i >= 0; i--) {

                //first fetching filesize of every DriveFileInfo object

                tempSize = fileInfoList.get(i).getFileSize();

                //checking if the file exist or not

                if (tempSize >= 1) {

                    //if the file exist keep it as finalSize.

                    finalSize = finalSize + tempSize;

                    //now checking new size is greater than fixed size or not.

                    if (finalSize <= fixedPartSize) {

                        //if the finalSize is lessar than fixedSize then add to ArrayList,named makeSublist
                        makeSublist.add(fileInfoList.get(i));

                        //after adding to the list remove index from  makeSublist Arraylist
                        fileInfoList.remove(i);
                    } else {
                        finalSize = 0;

                        //if the finalSize is greater than fixedSize then add to ArrayList of Arraylist,named allDataAspart
                        allDataAspart.add(makeSublist);

                        //and clean the arraylist means initialize makeSublist arraylist data
                        makeSublist = new ArrayList<>();
                    }
                }

                //checking if the file not exist
                else {
                    //remove the index from fileInfoList arraylist
                    fileInfoList.remove(i);
                }
            }
            allDataAspart.add(makeSublist);

        //returning the arraylist of List object data.
        return allDataAspart;
    }

But I am not getting proper list from the list..some files are missing when the list is long and fixed size is change.. please help me guys..

Body:
How about this:

public List<List<FileInfo>> partition(List<FileInfo> list, int maxSize) {
    List<List<FileInfo>> result = new ArrayList<>();
    List<FileInfo> current = new ArrayList<>();
    int currentSize = 0;
    for (FileInfo fi: list) {
        if (fi.getFileSize() > 0) {
            if (!current.isEmpty()
                    && currentSize + fi.getFileSize() > maxSize) {
                result.add(current);
                current = new ArrayList<>();
                currentSize = 0;
            }
            current.add(fi);
            currentSize += fi.getFileSize();
        }
    }
    if (!current.isEmpty()) {
        result.add(current);
    }
    return result;
}


问:
Redirect to Custom URL after Registration in Laravel 5.5
I am working on cart in laravel 5.5. Whenever guests click on "Add to cart", i am redirecting to login. If they have account, they will login and redirecting to product info they have selected. Otherwise they are registering. I wanted to redirect to customer selected product after registration.
For Login, this is working fine..  return redirect()->intended();
For Registration intended url not working..

答:
In Controllers/Auth/RegisterController
change protected $redirectTo = '/'; at line 30

For dynamic URL replace protected $redirectTo = '/'; with

```<code>protected function redirectTo()
{
    /* generate URL dynamicaly */.
    return '/path'; // return dynamicaly generated URL.
}
</code>```

you can also use return redirect()->intended(/* default uri to redirect user goes here */);

The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

Body:
In Controllers/Auth/RegisterController
change protected $redirectTo = '/'; at line 30

For dynamic URL replace protected $redirectTo = '/'; with

protected function redirectTo()
{
    /* generate URL dynamicaly */.
    return '/path'; // return dynamicaly generated URL.
}

you can also use return redirect()->intended(/* default uri to redirect user goes here */);

The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

ContentLicense: CC BY-SA 4.0


问:
Issue when python called from Javascript
I am new to Javascript, python and php. I have a js program wherein I click a button, it calls a python program and receive the returned value to display on the screen. I am trying to avoid using Jquery and Json.

Below is the code of both Javascript and Python.

Javascript:

```<code><html>
<head>
<script>
function cal()
{
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function()
  {
     if (this.readyState == 4 && this.status == 200) {
     document.getElementById("do").innerHTML = this.responseText;
     }
  };
  xhttp.open("POST", "./pth.py", true);
  xhttp.send();

}
</script>
</head>
<body>
<input type="submit" id="submit" class="btn btn-default" name="Submit"
onClick="cal();" value="Test"/>
<div id="do">

</div>
</body>
</html>
</code>```

Python:

```<code>#!/usr/bin/python

print "hello";
</code>```

For the above code, the following is the output I am receiving (I see the entire python code rather than just hello)

```<code>#!/usr/bin/python print "hello";
</code>```

答:
To perform such actions you need to use CGI layer between your webserver and python scripts, because a webserver does not work with them directly. Usually the following backend stack is commonly used:

```<code>Scripts with business logic (python/perl/php) -> CGI layer (WSGI, uWSGI, etc..) -> Webserver (Apache, nginx, etc..)
</code>```

So, you receive content of your script instead of it's output because it wasn't executed, just read like a text file.

Body:
I am new to Javascript, python and php. I have a js program wherein I click a button, it calls a python program and receive the returned value to display on the screen. I am trying to avoid using Jquery and Json.

Below is the code of both Javascript and Python.

Javascript:

<input type="submit" id="submit" class="btn btn-default" name="Submit"
onClick="cal();" value="Test"/>

Python:

#!/usr/bin/python

print "hello";

For the above code, the following is the output I am receiving (I see the entire python code rather than just hello)

#!/usr/bin/python print "hello";

Body:
To perform such actions you need to use CGI layer between your webserver and python scripts, because a webserver does not work with them directly. Usually the following backend stack is commonly used:

Scripts with business logic (python/perl/php) -> CGI layer (WSGI, uWSGI, etc..) -> Webserver (Apache, nginx, etc..)

So, you receive content of your script instead of it's output because it wasn't executed, just read like a text file.