问:
Restore database from production to Development
We have the database named 'itreport' on production server and database named 'itreport_dev' on development server.

1)On Production server, 52 users are present in the database 'itreport'.
2)On Development server, 60 users are in present the database 'itreport_dev'.
3)I have taken the dump of production server database 'itreport'. Dump file name is backup_12082017.sql

My question is
 If I restore the above dump(backup) file to Development server database 'itreport_dev, Users(60) present will present in the Development database?

If not what option we have to give in the restore process?

What are the pre steps and post steps to be performed on Develpement server?

答:
Short answer: No, roles are not part of a single-database backup.

If you dump only the database using pg_dump it will only restore tables and data. not any roles. any objects owned by missing roles will end up owned by the user performing the restore (this user should be a superuser)

If you do pg_dumpall roles and all databases will be backed up.

Roles can be backed up separately using pg_dumpall -r

if you do pgdumpall --clean the resore will destroy and replace any databases and roles on the dev server that also exist in the dump.  any names that are not in both will be unaffected, (the special role "postgres" and template databases also are untouched)

pgdumpall backups are SQL backups and should be restores using psql

```<code>su postgres -c psql < all-database-backupfile.sql
</code>```

or

```<code>zcat all-database-backupfile.sql.gz | su postgres -c psql
</code>```

etc.

(for windows use runas instead of su, I'm not sure of the exact syntax needed)

Body:
Short answer: No, roles are not part of a single-database backup.

If you dump only the database using pg_dump it will only restore tables and data. not any roles. any objects owned by missing roles will end up owned by the user performing the restore (this user should be a superuser)

If you do pg_dumpall roles and all databases will be backed up.

Roles can be backed up separately using pg_dumpall -r

if you do pgdumpall --clean the resore will destroy and replace any databases and roles on the dev server that also exist in the dump.  any names that are not in both will be unaffected, (the special role "postgres" and template databases also are untouched)

pgdumpall backups are SQL backups and should be restores using psql

su postgres -c psql < all-database-backupfile.sql

or

zcat all-database-backupfile.sql.gz | su postgres -c psql

etc.

(for windows use runas instead of su, I'm not sure of the exact syntax needed)


来源: stackexchange

问:
Angular ui-grid adding new row dynamically

I am having a problem with the newly added row. It inherit the row in the grid (the buttons and behavior). The code is working adding a new row but I want a new row with the behavior in the AddOverride() function. Like a button with save and cancel button. Also when I add a new row. the new row >has the update and delete button. When I try to click update on the newly >added row, it is calling the service for updating.

-

HTML

```<code>   <button  id="addNew" ng-click="addOverride()" type="button" class="btn
btn-primary">Add Rank</button>
                <div ui-grid-auto-resize ui-grid="gridOptions" ui-grid-
pagination class="gridRank" style="height: 370px !important;"></div>
</code>```

Populating Grid

```<code>$scope.gridOptions = {
            columnDefs: [
                {
                    field: 'rankID', displayName: '', visible: false
                },
                {
                    name: 'rankDesc', field: 'rankDesc', displayName: 'Rank Desc',
                    cellTemplate: '<div  ng-if="!row.entity.editrow">{{COL_FIELD}}</div><div ng-if="row.entity.editrow"><input type="text" style="height:30px" ng-model="MODEL_COL_FIELD"</div>', width: 350

                },
                 {
                     field: 'createTime', displayName: 'Create Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                 },
                {
                    field: 'createUserID', displayName: 'Create UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                },
                 {
                     field: 'updateTime', displayName: 'Update Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                 },
                {
                    field: 'updateUserID', displayName: 'Update UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                },
            {
                name: 'Action', field: 'edit', enableFiltering: false, enableSorting: false, enableColumnMenu: false,
                cellTemplate: '<div><button ng-show="!row.entity.editrow"  ng-click="grid.appScope.edit(row.entity)"><span class="glyphicon glyphicon-edit"></span></button>' + ' ' + //Edit Button
                               '<button ng-show="row.entity.editrow" ng-click="grid.appScope.saveRow(row.entity)"><span class="glyphicon glyphicon-ok"></span></button>' + ' ' +//Save Button
                               '<button ng-show="row.entity.editrow"  ng-click="grid.appScope.cancelEdit(row.entity)"><span class="glyphicon glyphicon-remove"></span></button>' + ' ' + //Cancel Button
                               '<button ng-show="!row.entity.editrow" ng-click="grid.appScope.Delete(row.entity)"><span class="glyphicon glyphicon-trash"></span></button>' + ' ' + //Delete Button
                               '</div>', width: 75
            }],
            data: response.data.resultLists.cookRankList,
            paginationPageSizes : [10, 20, 30],
            paginationPageSize : 10,
            multiSelect: false
        };
</code>```

ADDING OF NEW ROW

```<code>$scope.addOverride = function () {
            var emptyData = [
                 {
                     field: 'rankID', displayName: '', visible: false
                 },
                  {
                      name: 'rankDesc', field: 'rankDesc', displayName: 'Rank Desc',
                      cellTemplate: '<div  ng-if="!row.entity.editrow">{{COL_FIELD}}</div><div ng-if="row.entity.editrow"><input type="text" style="height:30px" ng-model="MODEL_COL_FIELD"</div>', width: 350

                  },
                  {
                      field: 'createTime', displayName: 'Create Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                  },
                  {
                      field: 'createUserID', displayName: 'Create UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                  },
                  {
                           field: 'updateTime', displayName: 'Update Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                  },
                  {
                           field: 'updateUserID', displayName: 'Update UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                  },
                  {
                    name: 'Action', field: 'add', enableFiltering: false, enableSorting: false, enableColumnMenu: false,
                    cellTemplate: '<div><button  ng-click="grid.appScope.saveRow(row.entity)"><span class="glyphicon glyphicon-ok"></span></button>' + ' ' +//Save Button
                                   '<button ng-click="grid.appScope.cancelEdit(row.entity)"><span class="glyphicon glyphicon-remove"></span></button>' + ' ' + //Cancel Button
                                   '</div>', width: 75
                }

            ];
            $scope.gridOptions.data.unshift(emptyData);
         };
</code>```

答:
When you add a new row, it should be a single object with the same properties as the others within the grid. You are pushing the column definitions into a row, so the grid is confused.

Your add function should be shortened to simply push a new object into your data array:

```<code>$scope.addOverride = function () {
   $scope.gridOptions.data.unshift({
        rankID: "",
        // shortened
    });
};
</code>```

Then, for your templates, you could create two variables to keep things tidy. Or just put it all together. Basically, you want your template to toggle on some field that won't be there initially. I am guessing createTime is one such field. Oftentimes this would be an id. You could also create a new hidden field if you wanted.

A lightweight example:

```<code>  var cellTemplateReg = '<div ng-if="row.entity.createTime">Existing</div>';
  var cellTemplateNew = '<div ng-if="!row.entity.createTime">New</div>';

columnDefs: [ //shortened
  {
      name: 'Action,
      field: 'action',
      enableFiltering: false,
      enableSorting: false,
      enableColumnMenu: false,
      width: 200,
      cellTemplate: cellTemplateReg + cellTemplateNew
  }
]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having a problem with the newly added row. It inherit the row in the grid (the buttons and behavior). The code is working adding a new row but I want a new row with the behavior in the AddOverride() function. Like a button with save and cancel button. Also when I add a new row. the new row >has the update and delete button. When I try to click update on the newly >added row, it is calling the service for updating.

-

HTML

   <button  id="addNew" ng-click="addOverride()" type="button" class="btn
btn-primary">Add Rank</button>

Populating Grid

$scope.gridOptions = {
            columnDefs: [
                {
                    field: 'rankID', displayName: '', visible: false
                },
                {
                    name: 'rankDesc', field: 'rankDesc', displayName: 'Rank Desc',
                    cellTemplate: '
{{COL_FIELD}}

<input type="text" style="height:30px" ng-model="MODEL_COL_FIELD"
', width: 350

                },
                 {
                     field: 'createTime', displayName: 'Create Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                 },
                {
                    field: 'createUserID', displayName: 'Create UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                },
                 {
                     field: 'updateTime', displayName: 'Update Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                 },
                {
                    field: 'updateUserID', displayName: 'Update UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                },
            {
                name: 'Action', field: 'edit', enableFiltering: false, enableSorting: false, enableColumnMenu: false,
                cellTemplate: '
<button ng-show="!row.entity.editrow"  ng-click="grid.appScope.edit(row.entity)"></button>' + ' ' + //Edit Button
                               '<button ng-show="row.entity.editrow" ng-click="grid.appScope.saveRow(row.entity)"></button>' + ' ' +//Save Button
                               '<button ng-show="row.entity.editrow"  ng-click="grid.appScope.cancelEdit(row.entity)"></button>' + ' ' + //Cancel Button
                               '<button ng-show="!row.entity.editrow" ng-click="grid.appScope.Delete(row.entity)"></button>' + ' ' + //Delete Button
                               '
', width: 75
            }],
            data: response.data.resultLists.cookRankList,
            paginationPageSizes : [10, 20, 30],
            paginationPageSize : 10,
            multiSelect: false
        };

ADDING OF NEW ROW

$scope.addOverride = function () {
            var emptyData = [
                 {
                     field: 'rankID', displayName: '', visible: false
                 },
                  {
                      name: 'rankDesc', field: 'rankDesc', displayName: 'Rank Desc',
                      cellTemplate: '
{{COL_FIELD}}

<input type="text" style="height:30px" ng-model="MODEL_COL_FIELD"
', width: 350

                  },
                  {
                      field: 'createTime', displayName: 'Create Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                  },
                  {
                      field: 'createUserID', displayName: 'Create UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                  },
                  {
                           field: 'updateTime', displayName: 'Update Time', cellFilter: 'date:\'yyyy-MM-dd\'', width: 200
                  },
                  {
                           field: 'updateUserID', displayName: 'Update UserID', enableFiltering: false, enableSorting: false, enableColumnMenu: false, width: 130
                  },
                  {
                    name: 'Action', field: 'add', enableFiltering: false, enableSorting: false, enableColumnMenu: false,
                    cellTemplate: '
<button  ng-click="grid.appScope.saveRow(row.entity)"></button>' + ' ' +//Save Button
                                   '<button ng-click="grid.appScope.cancelEdit(row.entity)"></button>' + ' ' + //Cancel Button
                                   '
', width: 75
                }

            ];
            $scope.gridOptions.data.unshift(emptyData);
         };

Body:
When you add a new row, it should be a single object with the same properties as the others within the grid. You are pushing the column definitions into a row, so the grid is confused.

Your add function should be shortened to simply push a new object into your data array:

$scope.addOverride = function () {
   $scope.gridOptions.data.unshift({
        rankID: "",
        // shortened
    });
};

Then, for your templates, you could create two variables to keep things tidy. Or just put it all together. Basically, you want your template to toggle on some field that won't be there initially. I am guessing createTime is one such field. Oftentimes this would be an id. You could also create a new hidden field if you wanted.

A lightweight example:

  var cellTemplateReg = '<div ng-if="row.entity.createTime">Existing</div>';
  var cellTemplateNew = '<div ng-if="!row.entity.createTime">New</div>';

columnDefs: [ //shortened
  {
      name: 'Action,
      field: 'action',
      enableFiltering: false,
      enableSorting: false,
      enableColumnMenu: false,
      width: 200,
      cellTemplate: cellTemplateReg + cellTemplateNew
  }
]


问:
Xcode 9 bot add server to team error repeatedly
I am running Xcode 9.1 on a mac with Xcode Server.  We have it setup to run our bots but every time a bot is created when it gets to the tab that says signing we always see this error...

Every time I click Add Server to Team and it adds it and moves on but the next time I set up a bot the same thing occurs.

My issue is with people who are not admins then can't click on the button so I need to make the bots for them.  Is there a way around this? Am I missing something/doing it wrong?

答: This turned out to be something stupid but will leave it here in case someone else experiences it.  Another one of my teammates had re-built key/cert pair and had never re-built the provision for it.  So we were still using the old on the server.  Once I added the new one that problem went away


问:
KeyError: 'DystopiaResidual', error with pandas
I'm learning python and linear regression. As I am a beginner, I cannot solve a problem.

My code:

```<code>import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.utils import shuffle
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from sklearn.preprocessing import StandardScaler
from sklearn.manifold import TSNE

from subprocess import check_output

print(check_output(["ls", "input"]).decode("utf8"))
df1 = pd.read_csv("input/2015.csv")
df2 = pd.read_csv("input/2016.csv")
df1.columns
df1.head(2)
sns.regplot(x='Standard Error',y='Happiness Score' ,data=df1)
sns.regplot(x='Economy (GDP per Capita)',y='Happiness Score' ,data=df1)

fr=['Standard Error', 'Economy (GDP per Capita)', 'Family','Health (Life    Expectancy)', 'Freedom', 'Trust (Government Corruption)','Generosity', 'DystopiaResidual']

plt.figure(figsize=(12,28*4))
gs = gridspec.GridSpec(28, 1)
for i, cn in enumerate(fr):
  ax = plt.subplot(gs[i])
  #sns.distplot(df1[cn], bins=50)
  sns.regplot(x=df1[cn],y='Happiness Score' ,data=df1)
  ax.set_xlabel('')
  ax.set_title('Regrassion of feature: ' + str(cn))
plt.show()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexes/base.py",
line 2522, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'DystopiaResidual'
</code>```

I don't understand what the problem is.

答:
It appears you are using the World Happiness Report as a sample data set.

You have a typo in your code. The field reference should be

fr=['Standard Error', 'Economy (GDP per Capita)', 'Family','Health (Life    Expectancy)', 'Freedom', 'Trust (Government Corruption)','Generosity', 'Dystopia Residual']

You're missing the space.

Body:
I'm learning python and linear regression. As I am a beginner, I cannot solve a problem.

My code:

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.utils import shuffle
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from sklearn.preprocessing import StandardScaler
from sklearn.manifold import TSNE

from subprocess import check_output

print(check_output(["ls", "input"]).decode("utf8"))
df1 = pd.read_csv("input/2015.csv")
df2 = pd.read_csv("input/2016.csv")
df1.columns
df1.head(2)
sns.regplot(x='Standard Error',y='Happiness Score' ,data=df1)
sns.regplot(x='Economy (GDP per Capita)',y='Happiness Score' ,data=df1)

fr=['Standard Error', 'Economy (GDP per Capita)', 'Family','Health (Life    Expectancy)', 'Freedom', 'Trust (Government Corruption)','Generosity', 'DystopiaResidual']

plt.figure(figsize=(12,28*4))
gs = gridspec.GridSpec(28, 1)
for i, cn in enumerate(fr):
  ax = plt.subplot(gs[i])
  #sns.distplot(df1[cn], bins=50)
  sns.regplot(x=df1[cn],y='Happiness Score' ,data=df1)
  ax.set_xlabel('')
  ax.set_title('Regrassion of feature: ' + str(cn))
plt.show()

Error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexes/base.py",
line 2522, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'DystopiaResidual'

I don't understand what the problem is.


问:
jquery selector doesn't work when html is replaced!
Please, help me with following problem:

```<code><!-- this is the visible code -->
<div id="divid">{some default content}<img class="img" src="GoNextArrow.jpg" alt=""></div>

<!-- this is a hidden list of contents -->
<div style="display: none;">
    <div id="divid1">{some content 1}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid2">{some content 2}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid3">{some content 3}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid4">{some content 4}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid5">{some content 5}<img class="img" src="GoNextArrow.jpg" alt=""></div>
</div>

<!-- this is an jquery script which replace the #divid with any of divid1-divid5 -->
$('#divid').hide().html(elem.html()).fadeIn();
<!-- elem is a variable, divid1 to divid5, e.g. var elem = $j('#divid'+id);  -->

<!-- I need a rollover effect, I made it so: -->
$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});
</code>```

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!

答:
Instead of re-binding .hover() every time, just use .live() and it will work for all current and future elements that match your selector, example...

```<code>$('.hoverme').live('hover', function(event) {
    if (event.type == 'mouseenter') {
        $(this).attr('src', 'GoNextArrowHover.jpg');
    }
    else {
        $(this).attr('src', 'GoNextArrow.jpg');
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Please, help me with following problem:

{some default content}

{some content 1}

{some content 2}

{some content 3}

{some content 4}

{some content 5}

$('#divid').hide().html(elem.html()).fadeIn();

$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!

Body:
Instead of re-binding .hover() every time, just use .live() and it will work for all current and future elements that match your selector, example...

$('.hoverme').live('hover', function(event) {
    if (event.type == 'mouseenter') {
        $(this).attr('src', 'GoNextArrowHover.jpg');
    }
    else {
        $(this).attr('src', 'GoNextArrow.jpg');
    }
});


问:
Why is my method with array parameter not working properly? (C++)
I'm new with c++ and I've been meaning to implement vector calculations via operator overloading.
The code that's not functioning as I intended is this.

First, main.cpp

```<code>#include <iostream>
#include "MyVector.h"
#include "MyVector.cpp"

int main() {
double forvector1[] = {0.1,0.2,0.3};
double forvector2[] = {0.2,0.3,0.5};
MyVector vector1(forvector1,3);
MyVector vector2(forvector2,3);
MyVector temp = vector1 + vector2;
temp.print();
return 0;
}
</code>```

Then, MyVector.cpp

```<code>#include "MyVector.h"
#include <iostream>
using namespace std;

MyVector::MyVector(double numList[], int size) : numList(numList), size(size) {
}

MyVector::MyVector(){   //empty vector;
}

void MyVector::print(){
cout<<"("<<numList[0];
for(int i=1;i<size;i++){
    cout<<", "<<numList[i];
}
cout<<")"<<endl;
}

MyVector MyVector:: operator+(MyVector vec){
if(vec.size != size){
    cout<<"+ cannot be applied to ";
    cout<<"("<<numList[0];
    for(int i=1;i<size;i++){
        cout<<", "<<numList[i];
    }
    cout<<") and ";
    vec.print();
    return MyVector();
}
double tempList[size];
for(int i=0;i<size;i++)
{
    tempList[i]=numList[i]+vec.numList[i];
}
MyVector result(tempList,size);
return result;
}
</code>```

Finally, this is my MyVector.h

```<code>class MyVector{
private:
int size;
double * numList;

public:
MyVector(double numList[], int size);  //size>=1
MyVector();  //empty Vector
void print();  //print its content e.g.  (1, 2, 3, 4)
MyVector operator-(MyVector vec);
MyVector operator+(MyVector vec);
double operator*(MyVector vec);
MyVector operator/(MyVector vec);

//You may add more member functions as well
};

#endif // MYVECTOR_H_INCLUDED
</code>```

According to the main.cpp, I should be getting (0.3, 0.5, 0.8) for the output. However, I keep getting (0.3, 0, 2.12199e-314), which means probably only the first element of the result array was right. I'm guessing it's because of the pointer I used to point at the array, so that's why only the first element was correct. Is there any way I could make the operator+ work? Any help would be appreciated. Thanks!

答:
My guess would be that there is a dangling pointer.

```<code>double tempList[size];
for(int i=0;i<size;i++)
{
    tempList[i]=numList[i]+vec.numList[i];
}
MyVector result(tempList,size);
return result;
</code>```

tempList points to data that are local to the function, but result uses it. In your constructor, you should copy the data in the array into another array owned by the object.

Body:
I'm new with c++ and I've been meaning to implement vector calculations via operator overloading.
The code that's not functioning as I intended is this.

First, main.cpp

#include <iostream>
#include "MyVector.h"
#include "MyVector.cpp"

int main() {
double forvector1[] = {0.1,0.2,0.3};
double forvector2[] = {0.2,0.3,0.5};
MyVector vector1(forvector1,3);
MyVector vector2(forvector2,3);
MyVector temp = vector1 + vector2;
temp.print();
return 0;
}

Then, MyVector.cpp

#include "MyVector.h"
#include <iostream>
using namespace std;

MyVector::MyVector(double numList[], int size) : numList(numList), size(size) {
}

MyVector::MyVector(){   //empty vector;
}

void MyVector::print(){
cout<<"("<<numList[0];
for(int i=1;i<size;i++){
    cout<<", "<<numList[i];
}
cout<<")"<<endl;
}

MyVector MyVector:: operator+(MyVector vec){
if(vec.size != size){
    cout<<"+ cannot be applied to ";
    cout<<"("<<numList[0];
    for(int i=1;i<size;i++){
        cout<<", "<<numList[i];
    }
    cout<<") and ";
    vec.print();
    return MyVector();
}
double tempList[size];
for(int i=0;i<size;i++)
{
    tempList[i]=numList[i]+vec.numList[i];
}
MyVector result(tempList,size);
return result;
}

Finally, this is my MyVector.h

class MyVector{
private:
int size;
double * numList;

public:
MyVector(double numList[], int size);  //size>=1
MyVector();  //empty Vector
void print();  //print its content e.g.  (1, 2, 3, 4)
MyVector operator-(MyVector vec);
MyVector operator+(MyVector vec);
double operator*(MyVector vec);
MyVector operator/(MyVector vec);

//You may add more member functions as well
};

#endif // MYVECTOR_H_INCLUDED

According to the main.cpp, I should be getting (0.3, 0.5, 0.8) for the output. However, I keep getting (0.3, 0, 2.12199e-314), which means probably only the first element of the result array was right. I'm guessing it's because of the pointer I used to point at the array, so that's why only the first element was correct. Is there any way I could make the operator+ work? Any help would be appreciated. Thanks!

Body:
My guess would be that there is a dangling pointer.

double tempList[size];
for(int i=0;i<size;i++)
{
    tempList[i]=numList[i]+vec.numList[i];
}
MyVector result(tempList,size);
return result;

tempList points to data that are local to the function, but result uses it. In your constructor, you should copy the data in the array into another array owned by the object.


问:
Send a POST request with vb.net gives 400 bad request error
I am not familiar a lot with Vb.Net, but I try to tweak something on an existent project. I have a cURL that try to implement on Vb.Net. I found different answers here and in other forums, but this way is the one I managed to reach

```<code>Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
    Dim req As WebRequest = WebRequest.Create(uri)
    req.ContentType = contentType
    req.Method = method
    req.ContentLength = jsonDataBytes.Length

    Dim stream = req.GetRequestStream()
    stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
    stream.Close()

    Dim response = req.GetResponse().GetResponseStream()

    Dim reader As New IO.StreamReader(response)
    Dim res = reader.ReadToEnd()
    reader.Close()
    response.Close()

    Return res
End Function

Dim postData As String = String.Format("text={0}", title)
Dim data = Encoding.UTF8.GetBytes(postData)
Dim uri = New Uri("https://.....")
Dim slackResponse = SendRequest(uri, data, "application/json", "POST")
</code>```

And this is the error I get:

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

If I comment out the SendRequest function, I got an error during calling that, so I guess it is on that part.

Not able to debug more. Any ideas?

答:
In order to debug more, you need to catch the WebException.  WebExceptions have a response object that may contain more information.  </p>

```<code>Dim response as WebResponse

Try
   response = req.GetResponse().GetResponseStream()
Catch ex As Net.WebException
   If ex.Response IsNot Nothing Then
      response = ex.Response
   End If
End Try
</code>```

<p>This could be a problem with your URL parameters but many sites also return this class of error when there is a problem in the json content of the request.  </p>

Body:
I am not familiar a lot with Vb.Net, but I try to tweak something on an existent project. I have a cURL that try to implement on Vb.Net. I found different answers here and in other forums, but this way is the one I managed to reach

Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
    Dim req As WebRequest = WebRequest.Create(uri)
    req.ContentType = contentType
    req.Method = method
    req.ContentLength = jsonDataBytes.Length

    Dim stream = req.GetRequestStream()
    stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
    stream.Close()

    Dim response = req.GetResponse().GetResponseStream()

    Dim reader As New IO.StreamReader(response)
    Dim res = reader.ReadToEnd()
    reader.Close()
    response.Close()

    Return res
End Function

Dim postData As String = String.Format("text={0}", title)
Dim data = Encoding.UTF8.GetBytes(postData)
Dim uri = New Uri("https://.....")
Dim slackResponse = SendRequest(uri, data, "application/json", "POST")

And this is the error I get:

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

If I comment out the SendRequest function, I got an error during calling that, so I guess it is on that part.

Not able to debug more. Any ideas?

Body:
In order to debug more, you need to catch the WebException.  WebExceptions have a response object that may contain more information.

Dim response as WebResponse

Try
   response = req.GetResponse().GetResponseStream()
Catch ex As Net.WebException
   If ex.Response IsNot Nothing Then
      response = ex.Response
   End If
End Try

This could be a problem with your URL parameters but many sites also return this class of error when there is a problem in the json content of the request.


问:
Unix file processing:How can I sum values in column based on the value in another column
I have encountered a problem that exceeds my basic knowledge in UNIX.
I have a file in the following format:

```<code>A AA     234
B BB     5
C CC     56
C CA     92
B CB     35
C CD     36
</code>```

I want to sum up the values in 3rd column based on values in first column and second column values as list.

I am expecting the results in below format.

```<code>A AA        234
B BB,CB     40
C CC,CA,CD  184
</code>```

Kindly help me to get the above results using UNIX functions.

答:
You can use the following awk command after sorting your file:

```<code>sort agglo.txt | awk '{if(prev==$1){sum+=$3; buffer=buffer","$2;}else{print prev" "buffer" "sum; prev=$1; sum=$3; buffer=$2}}END{print prev" "buffer" "sum;}'
</code>```

where agglo.txt is your input file.

This will give you the following input for your input file:

```<code>A AA     234
B BB     5
C CC     56
C CA     92
B CB     35
C CD     36
</code>```

Body:
I have encountered a problem that exceeds my basic knowledge in UNIX.
I have a file in the following format:

A AA     234
B BB     5
C CC     56
C CA     92
B CB     35
C CD     36

I want to sum up the values in 3rd column based on values in first column and second column values as list.

I am expecting the results in below format.

A AA        234
B BB,CB     40
C CC,CA,CD  184

Kindly help me to get the above results using UNIX functions.

Body:
You can use the following awk command after sorting your file:

sort agglo.txt | awk '{if(prev==$1){sum+=$3; buffer=buffer","$2;}else{print prev" "buffer" "sum; prev=$1; sum=$3; buffer=$2}}END{print prev" "buffer" "sum;}'

where agglo.txt is your input file.

This will give you the following input for your input file:

A AA     234
B BB     5
C CC     56
C CA     92
B CB     35
C CD     36


问:
Textfield issue in IOS
I have a textfield in my view controller under the textfield I have used a table view to show data in it and when we click any data from table view it shows in the textfield. Now when I press any cell of table view to show that data in text field it shows fine but textfield do not catch the data from table view it only send data manually written on the textfield. it shows me this in console,

```<code><UITableViewCell: 0x7f9dad0a1000; frame = (0 132; 342 44); text = '2014'; autoresize = W; layer = <CALayer: 0x60400022ec20>>
</code>```

My code is this,

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView==_year01) {
    return [year1Array count];
}else if (tableView == _carTable){
    return [carArray count];
}
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == _year01){
    cell.textLabel.text=[year1Array objectAtIndex:indexPath.row];
}else if (tableView == _carTable){
    cell.textLabel.text=[carArray objectAtIndex:indexPath.row];
}

cell.backgroundColor=[UIColor darkGrayColor];
cell.textLabel.textColor=[UIColor whiteColor];

 return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell %@",selectedCell);
if (tableView == _year01){
    self.year1.text=[year1Array objectAtIndex:indexPath.row];
    self.year01.hidden=YES;
}else{
    self.carName.text=[carArray objectAtIndex:indexPath.row];
    _carTable.hidden=YES;
    [_carName resignFirstResponder];
}
}
</code>```

Code to manage spaces in textfield is this,

```<code>-(void)textFieldDidChanges :(UITextField *)theTextField{
result=self.carName.text;
result=[result stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSLog(@"RRR %@",result);
//just use this result where you want
}
</code>```

Sending data to the next view,

```<code>- (IBAction)okay:(id)sender {

if ([_carName.text isEqualToString:@""] || [_year1.text isEqualToString:@""] || [_year2.text isEqualToString:@""] ) {

    NSString *message = @"Fill all the fields";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Data"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];

    [self presentViewController:alert animated:YES completion:nil];

    int duration = 2; // duration in seconds

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });

    _guideView.hidden=YES;
}else{

NSString *strAppend = [NSString stringWithFormat:@"%@-%@",_year1.text,_year2.text];
NSLog(@"%@",strAppend);

[[NSUserDefaults standardUserDefaults] setObject:result forKey:@"name"];
[[NSUserDefaults standardUserDefaults] setObject:strAppend forKey:@"year"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

}
</code>```

答:
Empty your text field before assigning a new value in didSelectRow.

```<code>if (tableView == _year01)
{
   self.year1.text=@"";

   self.year1.text=[year1Array objectAtIndex:indexPath.row];
   self.year01.hidden=YES;
}
else
{
   self.carName.text=@"";

   self.carName.text=[carArray objectAtIndex:indexPath.row];
   _carTable.hidden=YES;
  [_carName resignFirstResponder];
</code>```

}

Title: Textfield issue in IOS

Body:
I have a textfield in my view controller under the textfield I have used a table view to show data in it and when we click any data from table view it shows in the textfield. Now when I press any cell of table view to show that data in text field it shows fine but textfield do not catch the data from table view it only send data manually written on the textfield. it shows me this in console,

<UITableViewCell: 0x7f9dad0a1000; frame = (0 132; 342 44); text = '2014'; autoresize = W; layer = <CALayer: 0x60400022ec20>>

My code is this,

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView==_year01) {
    return [year1Array count];
}else if (tableView == _carTable){
    return [carArray count];
}
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == _year01){
    cell.textLabel.text=[year1Array objectAtIndex:indexPath.row];
}else if (tableView == _carTable){
    cell.textLabel.text=[carArray objectAtIndex:indexPath.row];
}

cell.backgroundColor=[UIColor darkGrayColor];
cell.textLabel.textColor=[UIColor whiteColor];

 return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell %@",selectedCell);
if (tableView == _year01){
    self.year1.text=[year1Array objectAtIndex:indexPath.row];
    self.year01.hidden=YES;
}else{
    self.carName.text=[carArray objectAtIndex:indexPath.row];
    _carTable.hidden=YES;
    [_carName resignFirstResponder];
}
}

Code to manage spaces in textfield is this,

-(void)textFieldDidChanges :(UITextField *)theTextField{
result=self.carName.text;
result=[result stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSLog(@"RRR %@",result);
//just use this result where you want
}

Sending data to the next view,

- (IBAction)okay:(id)sender {

if ([_carName.text isEqualToString:@""] || [_year1.text isEqualToString:@""] || [_year2.text isEqualToString:@""] ) {

    NSString *message = @"Fill all the fields";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Data"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];

    [self presentViewController:alert animated:YES completion:nil];

    int duration = 2; // duration in seconds

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });

    _guideView.hidden=YES;
}else{

NSString *strAppend = [NSString stringWithFormat:@"%@-%@",_year1.text,_year2.text];
NSLog(@"%@",strAppend);

[[NSUserDefaults standardUserDefaults] setObject:result forKey:@"name"];
[[NSUserDefaults standardUserDefaults] setObject:strAppend forKey:@"year"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

}

Body:
Empty your text field before assigning a new value in didSelectRow.

if (tableView == _year01)
{
   self.year1.text=@"";

   self.year1.text=[year1Array objectAtIndex:indexPath.row];
   self.year01.hidden=YES;
}
else
{
   self.carName.text=@"";

   self.carName.text=[carArray objectAtIndex:indexPath.row];
   _carTable.hidden=YES;
  [_carName resignFirstResponder];

}


问:
svg bbox() always returns a value where x and y are 0 when they shouldn't be
I'm using SVG.js to draw shapes. One of the shapes needs to be a circle with a radius line so so get that behavior, I'm using an ellipse and a line inside of a "g" element.

The trouble is, whenever I reference that g element and try to get the bbox, I always get a value like this:

```<code>{
 x: 0,
 y: 0,
 width: widthOfBox,
 height: heightOfBox,
 cx: widthOfBox/2,
 cy: heightOfBox/2
}
</code>```

x and y should NOT be 0.

Below is the element in question that is clearly not at (0,0) but seems to be reporting that it is.

```<code><g id="MLG1008" stroke="#000000" stroke-width="2" fill="#000000" transform="translate(100 200)" width="993.3559281546569" height="993.3559281546569" x="12.963409423828125" y="-290.0365905761719">
    <ellipse id="MLEllipse1009" rx="496.67796407732845" ry="496.67796407732845" cx="496.67796407732845" cy="496.67796407732845" stroke="#000000" stroke-width="2"></ellipse>
    <line id="MLLine1010" x1="496.67796407732845" y1="496.67796407732845" x2="801.6779640773284" y2="888.6779640773284" stroke="#000000" stroke-width="2"></line>
</g>
</code>```

Is there a way to define the values that bbox should have? Or a way to set the values that bbox() looks at?

答:
From W3 specs on getBBox

SVGRect getBBox()

      Returns the tight bounding box in current user space (i.e., after application of the ‘transform’ attribute, if any) on the geometry of all contained graphics elements, exclusive of stroking, clipping, masking and filter effects). [...]

Emphasis mine

As you can see in this definition, the SVGRect returned by getBBox is calculated against the contained graphics elements, this means that the translation you applied on your <g> element will not be taken into account in this SVGRect, since the transformation is applied on the element itself, and not on its graphic content.

You could get these x and y values by wrapping your transformed <g> element inside an other <g> from which you would call its getBBox() method,

console.log(document.getElementById("wrapper").getBBox());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 1500 1500" width="300" height="300">
  <g id="wrapper">
    <g id="MLG1008" stroke="#000000" stroke-width="2" fill="#000000" transform="translate(100 200)">
        <ellipse id="MLEllipse1009" rx="496.67796407732845" ry="496.67796407732845" cx="496.67796407732845" cy="496.67796407732845" stroke="#000000" stroke-width="2"></ellipse>
        <line id="MLLine1010" x1="496.67796407732845" y1="496.67796407732845" x2="801.6779640773284" y2="888.6779640773284" stroke="#000000" stroke-width="2"></line>
    </g>
  </g>
</svg></code>```

or even on the parent <svg> if all its graphic elements are inside this <g>:

console.log(document.querySelector("svg").getBBox());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 1500 1500" width="300" height="300">
  <g id="MLG1008" stroke="#000000" stroke-width="2" fill="#000000" transform="translate(100 200)">
      <ellipse id="MLEllipse1009" rx="496.67796407732845" ry="496.67796407732845" cx="496.67796407732845" cy="496.67796407732845" stroke="#000000" stroke-width="2"></ellipse>
      <line id="MLLine1010" x1="496.67796407732845" y1="496.67796407732845" x2="801.6779640773284" y2="888.6779640773284" stroke="#000000" stroke-width="2"></line>
  </g>
</svg></code>```

Also, even if unrelated with your issue, note that <g> element doesn't have width, height, x nor y attributes.

Body:
I'm using SVG.js to draw shapes. One of the shapes needs to be a circle with a radius line so so get that behavior, I'm using an ellipse and a line inside of a "g" element.

The trouble is, whenever I reference that g element and try to get the bbox, I always get a value like this:

{
 x: 0,
 y: 0,
 width: widthOfBox,
 height: heightOfBox,
 cx: widthOfBox/2,
 cy: heightOfBox/2
}

x and y should NOT be 0.

Below is the element in question that is clearly not at (0,0) but seems to be reporting that it is.

<g id="MLG1008" stroke="#000000" stroke-width="2" fill="#000000" transform="translate(100 200)" width="993.3559281546569" height="993.3559281546569" x="12.963409423828125" y="-290.0365905761719">
    <ellipse id="MLEllipse1009" rx="496.67796407732845" ry="496.67796407732845" cx="496.67796407732845" cy="496.67796407732845" stroke="#000000" stroke-width="2"></ellipse>
    <line id="MLLine1010" x1="496.67796407732845" y1="496.67796407732845" x2="801.6779640773284" y2="888.6779640773284" stroke="#000000" stroke-width="2"></line>
</g>

Is there a way to define the values that bbox should have? Or a way to set the values that bbox() looks at?

Body:
From W3 specs on getBBox

SVGRect getBBox()

      Returns the tight bounding box in current user space (i.e., after application of the ‘transform’ attribute, if any) on the geometry of all contained graphics elements, exclusive of stroking, clipping, masking and filter effects). [...]

Emphasis mine

As you can see in this definition, the SVGRect returned by getBBox is calculated against the contained graphics elements, this means that the translation you applied on your <g> element will not be taken into account in this SVGRect, since the transformation is applied on the element itself, and not on its graphic content.

You could get these x and y values by wrapping your transformed <g> element inside an other <g> from which you would call its getBBox() method,

console.log(document.getElementById("wrapper").getBBox());

<svg viewBox="0 0 1500 1500" width="300" height="300">
  <g id="wrapper">
    <g id="MLG1008" stroke="#000000" stroke-width="2" fill="#000000" transform="translate(100 200)">
        <ellipse id="MLEllipse1009" rx="496.67796407732845" ry="496.67796407732845" cx="496.67796407732845" cy="496.67796407732845" stroke="#000000" stroke-width="2"></ellipse>
        <line id="MLLine1010" x1="496.67796407732845" y1="496.67796407732845" x2="801.6779640773284" y2="888.6779640773284" stroke="#000000" stroke-width="2"></line>
    </g>
  </g>
</svg>

or even on the parent <svg> if all its graphic elements are inside this <g>:

console.log(document.querySelector("svg").getBBox());

<svg viewBox="0 0 1500 1500" width="300" height="300">
  <g id="MLG1008" stroke="#000000" stroke-width="2" fill="#000000" transform="translate(100 200)">
      <ellipse id="MLEllipse1009" rx="496.67796407732845" ry="496.67796407732845" cx="496.67796407732845" cy="496.67796407732845" stroke="#000000" stroke-width="2"></ellipse>
      <line id="MLLine1010" x1="496.67796407732845" y1="496.67796407732845" x2="801.6779640773284" y2="888.6779640773284" stroke="#000000" stroke-width="2"></line>
  </g>
</svg>

Also, even if unrelated with your issue, note that <g> element doesn't have width, height, x nor y attributes.


问:
no operator ">>" matches these operands operand types are: std::istream >> double*

I'm trying to dynamically allocate an array from a structure. I've look on a couple of other pages on stackoverflow and tried some some code, but none seems to work for my case. The closest I've found to what I'm doing is here:

C++ dynamic memory allocation with arrays in a structure

For some reason when I use this line of code:

```<code>cin >> testsPtr[i].students;
</code>```

I get the error in the title. I've also tried using:

```<code>cin >> testsPtr[i]->students;
</code>```

How can I have the user enter the data for my program?

Here are the specifications for the programming challenge:

Modify the program of Programming Challenge 1 to allow the user to enter name-score pairs. For each student taking a test, the user types a string representing the name of the student, followed by an integer representing the students score. Modify both the sorting and average-calculating functions so they take arrays of structures, with each structure containing the name and score of a single student. In traversing the arrays, use pointers rather than array indices.

```<code>#include <iostream>
#include <iomanip>

using namespace std;

int main() {

void averageScore(double*, int);
void sort(double*, int);

int numScores;

struct studentScores {
    double *scores;
    string *students;
};

cout << "How many test scores will you be entering?" << endl;
cin >> numScores;

studentScores *testsPtr = new studentScores[numScores];

for (int i = 0; i < numScores; i++) {

    cout << "What is the #" << i + 1 << " students name?" << endl;
    cin >> testsPtr[i].students;
    for (int j = 0; j < numScores; j++) {

        cout << "Please enter test score #" << j + 1 << endl;

        do {
            cin >> testsPtr[j].scores;
            if (testsPtr[i].scores < 0) {
                cout << "A test score can't be less than 0. Re-enter test score #" << i + 1 << endl;
            }

        } while (testsPtr[i].scores < 0);
    }
}

cout << endl;

/*sort(testsPtr.scores, numScores);
cout << endl;

averageScore(testScores, numScores);
cout << endl;*/
for (int i = 0; i <= numScores; i++) {
    cout << testsPtr->students << " test scores are: " << endl;
    for (int j = 0; j <= numScores; j++) {
        cout << testsPtr->scores;
    }
}

delete[] testsPtr;
testsPtr = nullptr;

return 0;
}
</code>```

答:
Dereference pointer before reading value:

```<code>cin >> *(testsPtr[i].students);
</code>```

But before you have to create object string and reference pointer to it:

```<code>testsPtr[i].students = new string;
</code>```

Body:
I'm trying to dynamically allocate an array from a structure. I've look on a couple of other pages on stackoverflow and tried some some code, but none seems to work for my case. The closest I've found to what I'm doing is here:

C++ dynamic memory allocation with arrays in a structure

For some reason when I use this line of code:

cin >> testsPtr[i].students;

I get the error in the title. I've also tried using:

cin >> testsPtr[i]->students;

How can I have the user enter the data for my program?

Here are the specifications for the programming challenge:

Modify the program of Programming Challenge 1 to allow the user to enter name-score pairs. For each student taking a test, the user types a string representing the name of the student, followed by an integer representing the students score. Modify both the sorting and average-calculating functions so they take arrays of structures, with each structure containing the name and score of a single student. In traversing the arrays, use pointers rather than array indices.

#include <iostream>
#include <iomanip>

using namespace std;

int main() {

void averageScore(double*, int);
void sort(double*, int);

int numScores;

struct studentScores {
    double *scores;
    string *students;
};

cout << "How many test scores will you be entering?" << endl;
cin >> numScores;

studentScores *testsPtr = new studentScores[numScores];

for (int i = 0; i < numScores; i++) {

    cout << "What is the #" << i + 1 << " students name?" << endl;
    cin >> testsPtr[i].students;
    for (int j = 0; j < numScores; j++) {

        cout << "Please enter test score #" << j + 1 << endl;

        do {
            cin >> testsPtr[j].scores;
            if (testsPtr[i].scores < 0) {
                cout << "A test score can't be less than 0. Re-enter test score #" << i + 1 << endl;
            }

        } while (testsPtr[i].scores < 0);
    }
}

cout << endl;

/*sort(testsPtr.scores, numScores);
cout << endl;

averageScore(testScores, numScores);
cout << endl;*/
for (int i = 0; i <= numScores; i++) {
    cout << testsPtr->students << " test scores are: " << endl;
    for (int j = 0; j <= numScores; j++) {
        cout << testsPtr->scores;
    }
}

delete[] testsPtr;
testsPtr = nullptr;

return 0;
}

Body:
Dereference pointer before reading value:

cin >> *(testsPtr[i].students);

But before you have to create object string and reference pointer to it:

testsPtr[i].students = new string;


问:
Microsoft Reporting: Setting subreport parameters in code
How can I set a parameter of a sub-report? I have successfully hooked myself up to the SubreportProcessing event, I can find the correct sub-report through e.ReportPath, and I can add datasources through e.DataSources.Add. But I find no way of adding report parameters??

I have found people suggesting to add them to the master report, but I don't really want to do that, since the master report shouldn't have to be connected to the sub-report at all, other than that it is wrapping the sub-report.

I am using one report as a master template, printing name of the report, page numbers etc. And the subreport is going to be the report itself. And if I could only find a way to set those report parameters of the sub-report I would be good to go...

Clarification: Creating/Defining the parameters is not the problem. The problem is to set their values. I thought the natural thing to do was to do it in the SubreportProcessing event. And the SubreportProcessingEventArgs do in fact have a Parameters property. But it is read only! So how do you use that? How can I set their value?

答:
It does work but it sure is persnickety.

First thing I recommend is to develop your reports as .rdl. Much easier to test the reports this way. You can also get the subreport parameters set up and tested as rdl, making sure each parameter of the subreport is also defined as a parameter of the parent report. Once you get the reports - including the subreports - working that way you can rename the .rdl to rdlc and add the rdlc files to your ReportViewer Project. No further changes required. Use the names of the rdl datasources as the data source names in your code to provide data to the report in the SubreportProcessing event handler.

You don't assign values to the passed parameter. The subreport will use them as is. (Sounds like the step you are missing is adding the parameters to the parent report as well as the the subreport as mentioned above.)  You can evaluate the parameters and use them as query parameters to get the datasource you will add.
You have to think about the datasource like its on an undiscovered dimension for a subreport. You will have to poke around while debugging in the event handler to see what I mean. Some of the values in your application will be readily available, others that you use easily elsewhere will throw object not found exceptions. For example I create a dataset in a instance of a class created on my applications main form. I use the data set throughout my application. In the SubreportProcessing event handler I cannot use the common dataset, so I must create a new instance of the table I need for the report and populate it. In the main report I would be able to access the common dataset. There are other limitations like this. Just have to wade your way through.

Here is the SubreportProcessing event handler from a working VB.NET ReportViewer application. Shows a few different ways to get the datasource for a subreport. subreport1 builds a one row datatable from application business objects, subreport2 provides data the report requires without a parameter, subreport3 is lie subreport2 but evaluates one of the parameters passed to the subreport for use in date value required by the query that creates the ReportDataSource.

```<code>    Public Sub SubreportProcessingEventHandler(ByVal sender As Object, _
                                               ByVal e As SubreportProcessingEventArgs)
    Select Case e.ReportPath
        Case "subreport1"
            Dim tbl As DataTable = New DataTable("TableName")
            Dim Status As DataColumn = New DataColumn
            Status.DataType = System.Type.GetType("System.String")
            Status.ColumnName = "Status"
            tbl.Columns.Add(Status)
            Dim Account As DataColumn = New DataColumn
            Account.DataType = System.Type.GetType("System.String")
            Account.ColumnName = "Account"
            tbl.Columns.Add(Account)
            Dim rw As DataRow = tbl.NewRow()
            rw("Status") = core.GetStatus
            rw("Account") = core.Account
            tbl.Rows.Add(rw)
            e.DataSources.Add(New ReportDataSource("ReportDatasourceName", tbl))
        Case "subreport2"
            core.DAL.cnStr = My.Settings.cnStr
            core.DAL.LoadSchedule()
            e.DataSources.Add(New ReportDataSource("ScheduledTasks", _
                                                   My.Forms.Mother.DAL.dsSQLCfg.tSchedule))
        Case "subreport3"
            core.DAL.cnStr = My.Settings.cnStr
            Dim dt As DataTable = core.DAL.GetNodesForDateRange(DateAdd("d", _
                                                                          -1 * CInt(e.Parameters("NumberOfDays").Values(0)), _
                                                                          Today), _
                                                                  Now)
            e.DataSources.Add(New ReportDataSource("Summary", dt))
    End Select
End Sub
</code>```

OwnerDisplayName: Svish

LastEditorDisplayName: Svish

Body:
It does work but it sure is persnickety.

First thing I recommend is to develop your reports as .rdl. Much easier to test the reports this way. You can also get the subreport parameters set up and tested as rdl, making sure each parameter of the subreport is also defined as a parameter of the parent report. Once you get the reports - including the subreports - working that way you can rename the .rdl to rdlc and add the rdlc files to your ReportViewer Project. No further changes required. Use the names of the rdl datasources as the data source names in your code to provide data to the report in the SubreportProcessing event handler.

You don't assign values to the passed parameter. The subreport will use them as is. (Sounds like the step you are missing is adding the parameters to the parent report as well as the the subreport as mentioned above.)  You can evaluate the parameters and use them as query parameters to get the datasource you will add.
You have to think about the datasource like its on an undiscovered dimension for a subreport. You will have to poke around while debugging in the event handler to see what I mean. Some of the values in your application will be readily available, others that you use easily elsewhere will throw object not found exceptions. For example I create a dataset in a instance of a class created on my applications main form. I use the data set throughout my application. In the SubreportProcessing event handler I cannot use the common dataset, so I must create a new instance of the table I need for the report and populate it. In the main report I would be able to access the common dataset. There are other limitations like this. Just have to wade your way through.

Here is the SubreportProcessing event handler from a working VB.NET ReportViewer application. Shows a few different ways to get the datasource for a subreport. subreport1 builds a one row datatable from application business objects, subreport2 provides data the report requires without a parameter, subreport3 is lie subreport2 but evaluates one of the parameters passed to the subreport for use in date value required by the query that creates the ReportDataSource.

    Public Sub SubreportProcessingEventHandler(ByVal sender As Object, _
                                               ByVal e As SubreportProcessingEventArgs)
    Select Case e.ReportPath
        Case "subreport1"
            Dim tbl As DataTable = New DataTable("TableName")
            Dim Status As DataColumn = New DataColumn
            Status.DataType = System.Type.GetType("System.String")
            Status.ColumnName = "Status"
            tbl.Columns.Add(Status)
            Dim Account As DataColumn = New DataColumn
            Account.DataType = System.Type.GetType("System.String")
            Account.ColumnName = "Account"
            tbl.Columns.Add(Account)
            Dim rw As DataRow = tbl.NewRow()
            rw("Status") = core.GetStatus
            rw("Account") = core.Account
            tbl.Rows.Add(rw)
            e.DataSources.Add(New ReportDataSource("ReportDatasourceName", tbl))
        Case "subreport2"
            core.DAL.cnStr = My.Settings.cnStr
            core.DAL.LoadSchedule()
            e.DataSources.Add(New ReportDataSource("ScheduledTasks", _
                                                   My.Forms.Mother.DAL.dsSQLCfg.tSchedule))
        Case "subreport3"
            core.DAL.cnStr = My.Settings.cnStr
            Dim dt As DataTable = core.DAL.GetNodesForDateRange(DateAdd("d", _
                                                                          -1 * CInt(e.Parameters("NumberOfDays").Values(0)), _
                                                                          Today), _
                                                                  Now)
            e.DataSources.Add(New ReportDataSource("Summary", dt))
    End Select
End Sub

OwnerDisplayName: bwunder


问:
Issue with changing date format inline with PHP
I am pulling a date from a database and it is in the format 2017-12-07.  That is how I was displaying the date, however, I would like to display is like Dec 7, 17.

What I tried.

```<code>echo "<td>" . date_format($row['returndate'],'M d, y') . "</td>";
</code>```

My results end up empty.  I have successfully changed the date format with in the MYSQLI line, however, I was wanting to do it with PHP.

UPDATE

I apologize, it seems I over looked something simple.  Below fixed it.

```<code>date('M d, y', strtotime($row['returndate']))
</code>```

I guess you have to do strtotime before date.

答:
Try this

```<code>echo "<td>" . date('M d, y', strtotime($row['returndate'])) . "</td>";
</code>```

Output

```<code>Dec 07, 17
</code>```

Body:
I am pulling a date from a database and it is in the format 2017-12-07.  That is how I was displaying the date, however, I would like to display is like Dec 7, 17.

What I tried.

echo "" . date_format($row['returndate'],'M d, y') . "	";

My results end up empty.  I have successfully changed the date format with in the MYSQLI line, however, I was wanting to do it with PHP.

UPDATE

I apologize, it seems I over looked something simple.  Below fixed it.

date('M d, y', strtotime($row['returndate']))

I guess you have to do strtotime before date.

Body:
Try this

echo "<td>" . date('M d, y', strtotime($row['returndate'])) . "</td>";

Output

Dec 07, 17


问:
How can I use an 'update' function to 'open' and update if the object is not yet open?
My example is a progress bar

In its simplest form a progress bar is

```<code>bar = ProgressBar.Open()
for item in list:
    bar.Update(count, len(list))
</code>```

I would instead like my calling code to be

```<code>for item in list:
    bar.Update(count, len(list))
</code>```

I want my Update() function to Open() a bar for the caller if one is not open.  The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle.

How can I retain state to tell if the Update had been previously called?

I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it.

Trying again, but in a way that has no application to stumble on.

The base question is:
I have a function that will be called multiple times.
I want to do something different the first time it is called.
How can a function in Python do that?

In C, that of course would be a...
static variable

I'm just now kinda figuring it out as I type, sorry.

========================

I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies.

Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact.

What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress?

That's the underlying motivation.  Slide in 1-line, get something cool for the trouble.

This progress meter was added to my otherwise boring file de-duplicator by adding just the single call:

```<code>msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)
</code>```

答:
To avoid using global variables, you can use decorator. Here's a simple example:

```<code>def open():
    print 'open'

def update():
    print 'update'

def call_once(func1, *args1, **kwargs1):
    def decorator(func2):
        called = [False]

        def wrapper(*args2 ,**kwargs2):
            if not called[0]:
                func1(*args1, **kwargs1)
                called[0] = True
            return func2(*args2, **kwargs2)
        return wrapper
    return decorator

@call_once(open)
def my_update():
    update()

for i in xrange(5):
    my_update()
</code>```

which give the result:

```<code>open
update
update
update
update
update
</code>```

For more information about decorator, please visit: https://wiki.python.org/moin/PythonDecorators

Body:
My example is a progress bar

In its simplest form a progress bar is

bar = ProgressBar.Open()
for item in list:
    bar.Update(count, len(list))

I would instead like my calling code to be

for item in list:
    bar.Update(count, len(list))

I want my Update() function to Open() a bar for the caller if one is not open.  The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle.

How can I retain state to tell if the Update had been previously called?

I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it.

Trying again, but in a way that has no application to stumble on.

The base question is:
I have a function that will be called multiple times.
I want to do something different the first time it is called.
How can a function in Python do that?

In C, that of course would be a...
static variable

I'm just now kinda figuring it out as I type, sorry.

========================

I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies.

Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact.

What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress?

That's the underlying motivation.  Slide in 1-line, get something cool for the trouble.

This progress meter was added to my otherwise boring file de-duplicator by adding just the single call:

msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)

Body:
To avoid using global variables, you can use decorator. Here's a simple example:

def open():
    print 'open'

def update():
    print 'update'

def call_once(func1, *args1, **kwargs1):
    def decorator(func2):
        called = [False]

        def wrapper(*args2 ,**kwargs2):
            if not called[0]:
                func1(*args1, **kwargs1)
                called[0] = True
            return func2(*args2, **kwargs2)
        return wrapper
    return decorator

@call_once(open)
def my_update():
    update()

for i in xrange(5):
    my_update()

which give the result:

open
update
update
update
update
update

For more information about decorator, please visit: https://wiki.python.org/moin/PythonDecorators


问:
Why can't I access FileName of uploaded file in ASP.NET MVC when uploaded using Microsoft Edge?
I have a simple file upload page and an ASP.NET MVC Controller to process the uploaded file. In Chrome and Firefox, everything works as expected. But it seems that Edge uploads the file differently, such that the Controller sees that a file has been uploaded, but shows FileName as "" and ContentLength as 0.

Here is the cshtml:

```<code>@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <h3>Upload File</h3>
    File:
    <input type="file" name="UploadedFile" />
    <input type="submit">Submit</button>
}
</code>```

And in the controller I have:

```<code>HttpPostedFileBase file = Request.Files["UploadedFile"];
</code>```

Afterward the file object is not null, but its ContentLength is 0 and FileName is an empty string. With Chrome and Firefox, these values contain the correct data.

What is different about how Edge handles file uploads?

答: The problem was not with my code. I was uploading an Excel spreadsheet that was also open in Excel at the same time, and Edge uploads Word and Excel files as 0 bytes when the file is open.</p>

Body:
I have a simple file upload page and an ASP.NET MVC Controller to process the uploaded file. In Chrome and Firefox, everything works as expected. But it seems that Edge uploads the file differently, such that the Controller sees that a file has been uploaded, but shows FileName as "" and ContentLength as 0.

Here is the cshtml:

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

Upload File

    File:
    <input type="file" name="UploadedFile" />
    <input type="submit">Submit</button>
}

And in the controller I have:

HttpPostedFileBase file = Request.Files["UploadedFile"];

Afterward the file object is not null, but its ContentLength is 0 and FileName is an empty string. With Chrome and Firefox, these values contain the correct data.

What is different about how Edge handles file uploads?


问:
while installing node.js getting permission denied error
I downloaded the file for version 8.9.2 of node js and I am using lubuntu. I extracted the tar.xz file of nodejs I downloaded into a folder I made, and then in my command line entered

```<code>cd /usr/src
wget http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz
</code>```

But then this shows up.

```<code>--2017-12-07 22:08:56--  http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz
Resolving nodejs.org (nodejs.org)... 2400:cb00:2048:1::6814:172e, 2400:cb00:2048:1::6814:162e, 104.20.22.46, ...
Connecting to nodejs.org (nodejs.org)|2400:cb00:2048:1::6814:172e|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31109143 (30M) [application/gzip]
node-v8.9.2.tar.gz: Permission denied

Cannot write to ‘node-v8.9.2.tar.gz’ (Permission denied).
</code>```

So how do I install it properly?

答:
As Kishor Pawar already mentionet:

The folder /usr/src belongs to the user root and your current user does not have write access (you can see that by using ls -al /usr/src)

In order to install it you have multiple Options:

use linux package-manager.
Install it via sudo apt-get install package=version (example)

use a wrapper like nvm (https://github.com/creationix/nvm)

installing it manually: the user that uses npm needs to have write access to all folder that are used by npm. So in case you want to install it to /usr/src  your user needs to be a sudoer. Else install it into your homefolder(i am not sure if this is sufficient)

Option 2 is my preferred option for a developing machine. You can easily install specific version and have them in parallel and switch versions as you need. Easy to use and easy to upgrade. No hassle on access privileges, as it puts all dependencies to the users home folder.

Body:
I downloaded the file for version 8.9.2 of node js and I am using lubuntu. I extracted the tar.xz file of nodejs I downloaded into a folder I made, and then in my command line entered

cd /usr/src
wget http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz

But then this shows up.

--2017-12-07 22:08:56--  http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz
Resolving nodejs.org (nodejs.org)... 2400:cb00:2048:1::6814:172e, 2400:cb00:2048:1::6814:162e, 104.20.22.46, ...
Connecting to nodejs.org (nodejs.org)|2400:cb00:2048:1::6814:172e|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31109143 (30M) [application/gzip]
node-v8.9.2.tar.gz: Permission denied

Cannot write to ‘node-v8.9.2.tar.gz’ (Permission denied).

So how do I install it properly?


问:
MongoDB not move chunks to new shard in sharding cluster
I am running mongodb for storage data. The MongoDB cluster have 3 shards, each shard have 3 server replica-set, 2 mongos and 3 config server. Each server have 1TB for storage. Now, all 2 of 3 shards have data about 90% capacity. When I add a new shard, MongoDB not move any chunks from olds shard to new one. I checked mongos sharding status. It shows that. MongoDB baclancer is running.

mongos> db.printShardingStatus()
--- Sharding Status ---
  sharding version: {
 "_id" : 1,
 "minCompatibleVersion" : 5,
 "currentVersion" : 6,
 "clusterId" : ObjectId("59c0ef31619ac70cb8ac5f5c")
}
  shards:
 {  "_id" : "rs0",  "host" : "rs0/10.5.36.88:27017,10.5.36.92:27017,10.5.36.93:27017",  "state" : 1,  "maxSize" : 990000 }
 {  "_id" : "rs1",  "host" : "rs1/10.5.36.101:27017,10.5.36.103:27017,10.5.36.97:27017",  "state" : 1,  "maxSize" : 990000 }
 {  "_id" : "rs2",  "host" : "rs2/10.5.36.100:27017,10.5.36.117:27017,10.5.36.126:27017",  "state" : 1,  "maxSize" : 990000 }
 {  "_id" : "rs3",  "host" : "rs3/10.5.36.152:27017,10.5.36.156:27017,10.5.36.164:27017",  "state" : 1,  "maxSize" : 990000 }
  active mongoses:
 "3.4.9" : 1
 autosplit:
 Currently enabled: yes
  balancer:
 Currently enabled:  yes
 Currently running:  yes
  Balancer lock taken at Wed Sep 20 2017 09:21:43 GMT+0700 by ConfigServer:Balancer
 Collections with active migrations:
  fbgroups.comments started at Wed Nov 22 2017 22:36:15 GMT+0700
 Failed balancer rounds in last 5 attempts:  0
 Migration Results for the last 24 hours:
  No recent migrations
  databases:
 {  "_id" : "fbpages",  "primary" : "rs0",  "partitioned" : true }
  fbpages.comments
   shard key: { "CommentFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 6263
    rs1 6652
    rs2 6175
   too many chunks to print, use verbose if you want to force print
  fbpages.links
   shard key: { "PageFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 23
    rs1 23
    rs2 23
   too many chunks to print, use verbose if you want to force print
  fbpages.posts
   shard key: { "PostFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 11931
    rs1 11847
    rs2 5043
   too many chunks to print, use verbose if you want to force print
 {  "_id" : "fbgroups",  "primary" : "rs0",  "partitioned" : true }
  fbgroups.comments
   shard key: { "CommentFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 6451
    rs1 6451
    rs2 4742
   too many chunks to print, use verbose if you want to force print
  fbgroups.links
   shard key: { "GroupId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 3
    rs1 3
    rs2 3
   { "GroupId" : { "$minKey" : 1 } } -->> { "GroupId" : "1391082767860588" } on : rs2 Timestamp(7, 0)
   { "GroupId" : "1391082767860588" } -->> { "GroupId" : "1564129037230139" } on : rs0 Timestamp(7, 1)
   { "GroupId" : "1564129037230139" } -->> { "GroupId" : "172020656162023" } on : rs0 Timestamp(4, 0)
   { "GroupId" : "172020656162023" } -->> { "GroupId" : "244621675585655" } on : rs0 Timestamp(5, 0)
   { "GroupId" : "244621675585655" } -->> { "GroupId" : "375231932588613" } on : rs2 Timestamp(6, 0)
   { "GroupId" : "375231932588613" } -->> { "GroupId" : "506856652708047" } on : rs2 Timestamp(8, 0)
   { "GroupId" : "506856652708047" } -->> { "GroupId" : "67046218160" } on : rs1 Timestamp(8, 1)
   { "GroupId" : "67046218160" } -->> { "GroupId" : "878610618830881" } on : rs1 Timestamp(1, 7)
   { "GroupId" : "878610618830881" } -->> { "GroupId" : { "$maxKey" : 1 } } on : rs1 Timestamp(1, 8)
  fbgroups.postdata
   shard key: { "_id" : 1 }
   unique: false
   balancing: true
   chunks:
    rs0 91
    rs1 482
    rs2 91
   too many chunks to print, use verbose if you want to force print
  fbgroups.posts
   shard key: { "PostFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 26015
    rs1 26092
    rs2 6526
   too many chunks to print, use verbose if you want to force print
 {  "_id" : "test",  "primary" : "rs1",  "partitioned" : true }
 {  "_id" : "intership",  "primary" : "rs1",  "partitioned" : false }
 {  "_id" : "fbhashtags",  "primary" : "rs2",  "partitioned" : true }
  fbhashtags.postdata
   shard key: { "_id" : 1 }
   unique: false
   balancing: true
   chunks:
    rs0 2
    rs1 2
    rs2 2
   { "_id" : { "$minKey" : 1 } } -->> { "_id" : ObjectId("58f122ff7fe5fb4520b4185a") } on : rs0 Timestamp(2, 0)
   { "_id" : ObjectId("58f122ff7fe5fb4520b4185a") } -->> { "_id" : ObjectId("58fac0537fe5fb051d0749de") } on : rs1 Timestamp(3, 0)
   { "_id" : ObjectId("58fac0537fe5fb051d0749de") } -->> { "_id" : ObjectId("5906119e7fe5fb2c7d9d41e9") } on : rs0 Timestamp(4, 0)
   { "_id" : ObjectId("5906119e7fe5fb2c7d9d41e9") } -->> { "_id" : ObjectId("591012257fe5fb70dc9e49bf") } on : rs1 Timestamp(5, 0)
   { "_id" : ObjectId("591012257fe5fb70dc9e49bf") } -->> { "_id" : ObjectId("5918b5d77fe5fb2feb06338a") } on : rs2 Timestamp(5, 1)
   { "_id" : ObjectId("5918b5d77fe5fb2feb06338a") } -->> { "_id" : { "$maxKey" : 1 } } on : rs2 Timestamp(1, 5)
  fbhashtags.posts
   shard key: { "_id" : 1 }
   unique: false
   balancing: true
   chunks:
    rs2 1
   { "_id" : { "$minKey" : 1 } } -->> { "_id" : { "$maxKey" : 1 } } on : rs2 Timestamp(1, 0)
 {  "_id" : "fbprofiles",  "primary" : "rs2",  "partitioned" : true }
  fbprofiles.fbcomments
   shard key: { "commentFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 18
    rs1 18
    rs2 19
   too many chunks to print, use verbose if you want to force print
  fbprofiles.fbposts
   shard key: { "postFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 7
    rs1 7
    rs2 3144
   too many chunks to print, use verbose if you want to force print
  fbprofiles.fbprofiles
   shard key: { "baseUrl" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 2
    rs1 2
    rs2 141
   too many chunks to print, use verbose if you want to force print
 {  "_id" : "testnewfb",  "primary" : "rs2",  "partitioned" : false }
 {  "_id" : "news_images",  "primary" : "rs2",  "partitioned" : false }
 {  "_id" : "social_index",  "primary" : "rs2",  "partitioned" : false }
 {  "_id" : "twitter",  "primary" : "rs2",  "partitioned" : true }
 {  "_id" : "techmeme",  "primary" : "rs2",  "partitioned" : false }```

Why MongoDB does not move data to new shard (rs3)
Thanks!

答: I found my problem in my case. That is 1 of three Mongo config servers does not configure correctly all host. I changed /etc/hosts and stepDown() the primary config server and I see it working correctly. It consume lots of time. I abuse that when the server crash by electric, it cannot recover from previous state.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am running mongodb for storage data. The MongoDB cluster have 3 shards, each shard have 3 server replica-set, 2 mongos and 3 config server. Each server have 1TB for storage. Now, all 2 of 3 shards have data about 90% capacity. When I add a new shard, MongoDB not move any chunks from olds shard to new one. I checked mongos sharding status. It shows that. MongoDB baclancer is running.

mongos> db.printShardingStatus()
--- Sharding Status ---
  sharding version: {
 "_id" : 1,
 "minCompatibleVersion" : 5,
 "currentVersion" : 6,
 "clusterId" : ObjectId("59c0ef31619ac70cb8ac5f5c")
}
  shards:
 {  "_id" : "rs0",  "host" : "rs0/10.5.36.88:27017,10.5.36.92:27017,10.5.36.93:27017",  "state" : 1,  "maxSize" : 990000 }
 {  "_id" : "rs1",  "host" : "rs1/10.5.36.101:27017,10.5.36.103:27017,10.5.36.97:27017",  "state" : 1,  "maxSize" : 990000 }
 {  "_id" : "rs2",  "host" : "rs2/10.5.36.100:27017,10.5.36.117:27017,10.5.36.126:27017",  "state" : 1,  "maxSize" : 990000 }
 {  "_id" : "rs3",  "host" : "rs3/10.5.36.152:27017,10.5.36.156:27017,10.5.36.164:27017",  "state" : 1,  "maxSize" : 990000 }
  active mongoses:
 "3.4.9" : 1
 autosplit:
 Currently enabled: yes
  balancer:
 Currently enabled:  yes
 Currently running:  yes
  Balancer lock taken at Wed Sep 20 2017 09:21:43 GMT+0700 by ConfigServer:Balancer
 Collections with active migrations:
  fbgroups.comments started at Wed Nov 22 2017 22:36:15 GMT+0700
 Failed balancer rounds in last 5 attempts:  0
 Migration Results for the last 24 hours:
  No recent migrations
  databases:
 {  "_id" : "fbpages",  "primary" : "rs0",  "partitioned" : true }
  fbpages.comments
   shard key: { "CommentFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 6263
    rs1 6652
    rs2 6175
   too many chunks to print, use verbose if you want to force print
  fbpages.links
   shard key: { "PageFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 23
    rs1 23
    rs2 23
   too many chunks to print, use verbose if you want to force print
  fbpages.posts
   shard key: { "PostFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 11931
    rs1 11847
    rs2 5043
   too many chunks to print, use verbose if you want to force print
 {  "_id" : "fbgroups",  "primary" : "rs0",  "partitioned" : true }
  fbgroups.comments
   shard key: { "CommentFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 6451
    rs1 6451
    rs2 4742
   too many chunks to print, use verbose if you want to force print
  fbgroups.links
   shard key: { "GroupId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 3
    rs1 3
    rs2 3
   { "GroupId" : { "$minKey" : 1 } } -->> { "GroupId" : "1391082767860588" } on : rs2 Timestamp(7, 0)
   { "GroupId" : "1391082767860588" } -->> { "GroupId" : "1564129037230139" } on : rs0 Timestamp(7, 1)
   { "GroupId" : "1564129037230139" } -->> { "GroupId" : "172020656162023" } on : rs0 Timestamp(4, 0)
   { "GroupId" : "172020656162023" } -->> { "GroupId" : "244621675585655" } on : rs0 Timestamp(5, 0)
   { "GroupId" : "244621675585655" } -->> { "GroupId" : "375231932588613" } on : rs2 Timestamp(6, 0)
   { "GroupId" : "375231932588613" } -->> { "GroupId" : "506856652708047" } on : rs2 Timestamp(8, 0)
   { "GroupId" : "506856652708047" } -->> { "GroupId" : "67046218160" } on : rs1 Timestamp(8, 1)
   { "GroupId" : "67046218160" } -->> { "GroupId" : "878610618830881" } on : rs1 Timestamp(1, 7)
   { "GroupId" : "878610618830881" } -->> { "GroupId" : { "$maxKey" : 1 } } on : rs1 Timestamp(1, 8)
  fbgroups.postdata
   shard key: { "_id" : 1 }
   unique: false
   balancing: true
   chunks:
    rs0 91
    rs1 482
    rs2 91
   too many chunks to print, use verbose if you want to force print
  fbgroups.posts
   shard key: { "PostFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 26015
    rs1 26092
    rs2 6526
   too many chunks to print, use verbose if you want to force print
 {  "_id" : "test",  "primary" : "rs1",  "partitioned" : true }
 {  "_id" : "intership",  "primary" : "rs1",  "partitioned" : false }
 {  "_id" : "fbhashtags",  "primary" : "rs2",  "partitioned" : true }
  fbhashtags.postdata
   shard key: { "_id" : 1 }
   unique: false
   balancing: true
   chunks:
    rs0 2
    rs1 2
    rs2 2
   { "_id" : { "$minKey" : 1 } } -->> { "_id" : ObjectId("58f122ff7fe5fb4520b4185a") } on : rs0 Timestamp(2, 0)
   { "_id" : ObjectId("58f122ff7fe5fb4520b4185a") } -->> { "_id" : ObjectId("58fac0537fe5fb051d0749de") } on : rs1 Timestamp(3, 0)
   { "_id" : ObjectId("58fac0537fe5fb051d0749de") } -->> { "_id" : ObjectId("5906119e7fe5fb2c7d9d41e9") } on : rs0 Timestamp(4, 0)
   { "_id" : ObjectId("5906119e7fe5fb2c7d9d41e9") } -->> { "_id" : ObjectId("591012257fe5fb70dc9e49bf") } on : rs1 Timestamp(5, 0)
   { "_id" : ObjectId("591012257fe5fb70dc9e49bf") } -->> { "_id" : ObjectId("5918b5d77fe5fb2feb06338a") } on : rs2 Timestamp(5, 1)
   { "_id" : ObjectId("5918b5d77fe5fb2feb06338a") } -->> { "_id" : { "$maxKey" : 1 } } on : rs2 Timestamp(1, 5)
  fbhashtags.posts
   shard key: { "_id" : 1 }
   unique: false
   balancing: true
   chunks:
    rs2 1
   { "_id" : { "$minKey" : 1 } } -->> { "_id" : { "$maxKey" : 1 } } on : rs2 Timestamp(1, 0)
 {  "_id" : "fbprofiles",  "primary" : "rs2",  "partitioned" : true }
  fbprofiles.fbcomments
   shard key: { "commentFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 18
    rs1 18
    rs2 19
   too many chunks to print, use verbose if you want to force print
  fbprofiles.fbposts
   shard key: { "postFbId" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 7
    rs1 7
    rs2 3144
   too many chunks to print, use verbose if you want to force print
  fbprofiles.fbprofiles
   shard key: { "baseUrl" : 1 }
   unique: true
   balancing: true
   chunks:
    rs0 2
    rs1 2
    rs2 141
   too many chunks to print, use verbose if you want to force print
 {  "_id" : "testnewfb",  "primary" : "rs2",  "partitioned" : false }
 {  "_id" : "news_images",  "primary" : "rs2",  "partitioned" : false }
 {  "_id" : "social_index",  "primary" : "rs2",  "partitioned" : false }
 {  "_id" : "twitter",  "primary" : "rs2",  "partitioned" : true }
 {  "_id" : "techmeme",  "primary" : "rs2",  "partitioned" : false }

Why MongoDB does not move data to new shard (rs3)
Thanks!


问:
Run Android Emulator with custom build kernel
I try to run android emulator with custom build kernel from Ubuntu 16.04.
The steps for build kernel:

```<code>git clone https://android.googlesource.com/kernel/goldfish/ -b android-goldfish-3.18
git clone https://android.googlesource.com/platform/prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9
cd goldfish
export CROSS_COMPILE=x86_64-linux-android-
export ARCH=x86_64
export PATH=$PATH:/path/to/x86_64-linux-android-4.9/bin
make x86_64_ranchu_defconfig
make -j4
</code>```

Then, when I try to run emulator with this image:

```<code>emulator -avd Nexus_5_API_24 -kernel /path/to/goldfish/arch/x86/boot/bzImage -show-kernel
</code>```

Emulator window starts, I see "Android" logo, but nothing else happens. It is bootloop and in console I see this message again and again:

```<code>[   22.396836] init: Starting service 'netd'...
[   22.397460] init: Starting service 'media'...
[   22.397919] init: Starting service 'zygote'...
[   22.808059] zygote[2021]: segfault at bf833000 ip afba292a sp bf8528f0 error 4 in libart.so[af66d000+745000]
[   22.809470] init: Service 'zygote' (pid 2021) killed by signal 11
[   22.809940] init: Service 'zygote' (pid 2021) killing any children in process group
[   22.810545] init: write_file: Unable to open '/sys/android_power/request_state': No such file or directory
[   22.811288] init: write_file: Unable to write to '/sys/power/state': Invalid argument
[   22.811881] init: Service 'media' is being killed...
[   22.812608] init: Service 'netd' is being killed...
[   22.813030] init: Service 'media' (pid 2020) killed by signal 9
[   22.813482] init: Service 'media' (pid 2020) killing any children in process group
[   22.814085] init: Service 'netd' (pid 2019) killed by signal 9
[   22.814533] init: Service 'netd' (pid 2019) killing any children in process group
[   22.815129] init: Untracked pid 2129 killed by signal 9
</code>```

I found some answer here:
https://gist.github.com/yan12125/78a9004acb1bed5faf2ffd442163e2ef

But I don't want build ASOP and add fix to thread.cc, because I need only custom kernel and official images from Google.

How I can build kernel to avoid this error or, maybe, it is some option when run emulator?

P.S. I also tried another branches for goldfish (android-goldfish-3.10), but with the same result.

Thank you for your answers!

答:
I have same problem, I switch to the branch "origin/android-goldfish-3.10-n-dev",  use Android 7.0 x86_64 image, emulator works well.</p>

```<code>cd goldfish
git checkout -b mybranch origin/android-goldfish-3.10-n-dev
</code>```

Body:
I try to run android emulator with custom build kernel from Ubuntu 16.04.
The steps for build kernel:

git clone https://android.googlesource.com/kernel/goldfish/ -b android-goldfish-3.18
git clone https://android.googlesource.com/platform/prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9
cd goldfish
export CROSS_COMPILE=x86_64-linux-android-
export ARCH=x86_64
export PATH=$PATH:/path/to/x86_64-linux-android-4.9/bin
make x86_64_ranchu_defconfig
make -j4

Then, when I try to run emulator with this image:

emulator -avd Nexus_5_API_24 -kernel /path/to/goldfish/arch/x86/boot/bzImage -show-kernel

Emulator window starts, I see "Android" logo, but nothing else happens. It is bootloop and in console I see this message again and again:

[   22.396836] init: Starting service 'netd'...
[   22.397460] init: Starting service 'media'...
[   22.397919] init: Starting service 'zygote'...
[   22.808059] zygote[2021]: segfault at bf833000 ip afba292a sp bf8528f0 error 4 in libart.so[af66d000+745000]
[   22.809470] init: Service 'zygote' (pid 2021) killed by signal 11
[   22.809940] init: Service 'zygote' (pid 2021) killing any children in process group
[   22.810545] init: write_file: Unable to open '/sys/android_power/request_state': No such file or directory
[   22.811288] init: write_file: Unable to write to '/sys/power/state': Invalid argument
[   22.811881] init: Service 'media' is being killed...
[   22.812608] init: Service 'netd' is being killed...
[   22.813030] init: Service 'media' (pid 2020) killed by signal 9
[   22.813482] init: Service 'media' (pid 2020) killing any children in process group
[   22.814085] init: Service 'netd' (pid 2019) killed by signal 9
[   22.814533] init: Service 'netd' (pid 2019) killing any children in process group
[   22.815129] init: Untracked pid 2129 killed by signal 9

I found some answer here:
https://gist.github.com/yan12125/78a9004acb1bed5faf2ffd442163e2ef

But I don't want build ASOP and add fix to thread.cc, because I need only custom kernel and official images from Google.

How I can build kernel to avoid this error or, maybe, it is some option when run emulator?

P.S. I also tried another branches for goldfish (android-goldfish-3.10), but with the same result.

Thank you for your answers!

Body:
I have same problem, I switch to the branch "origin/android-goldfish-3.10-n-dev",  use Android 7.0 x86_64 image, emulator works well.

cd goldfish
git checkout -b mybranch origin/android-goldfish-3.10-n-dev


问:
Algorithm for fairly assigning tasks to workers based on skills
(Before anyone asks, this is not homework.)

I have a set of workers with interests, i.e.:

Bob: Java, XML, Ruby

Susan: Java, HTML, Python

Fred: Python, Ruby

Sam: Java, Ruby

etc.

(There are actually somewhere in the range of 10-25 "interests" for each worker, and I have around 40-50 workers)

At the same time, I have a very large set of tasks that need to be distributed among the workers. Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests:

Task 1: Ruby, XML
Task 2: XHTML, Python

and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2.

This is all stored in a database thusly:

```<code>Task
    id integer primary key
    name varchar

TaskInterests
    task_id integer
    interest_id integer

Workers
    id integer primary key
    name varchar
    max_assignments integer

WorkerInterests
    worker_id
    interest_id

Assignments
    task_id
    worker_id
    date_assigned
</code>```

Each worker has a maximum number of assignments they will do, around 10. Some interests are more rare than others (i.e. only 1 or 2 workers have listed them as a interest), some interests are more common (i.e. half of the workers list them).

The algorithm must:

Assign every task to 3 workers (it is
assumed that at least 3 of the
workers are interested in one of the
interests of the task).

Assign every worker 1 or more tasks

Ideally, the algorithm will:

Assign each worker a number of tasks proportional to their maximum assignments and the total number of tasks. For example, if Susan says she will do 20 tasks and most people will only do 10 tasks and there are 50 workers and 300 tasks, she should be assigned 12 tasks (20/10*(300/50)).

Assign a variety of tasks to each worker, so if Susan lists 4 interests she gets tasks that include 4 interests (rather than getting 10 tasks all with the same interest)

The most difficult aspect so far has been dealing with theses issues:

tasks having interests with few corresponding workers

workers who have few interests, especially

workers who have a few interests, for which there are relatively few tasks

答:
So I gave this problem some thought and I think that you can get a good solution (for some definition of "good") by reducing it to an instance of min-cost max-flow (see this, for example).  The idea is as follows.  Suppose you are given as input a set of jobs J, each of which has a set of skills necessary, along with a set of workers W, each of whom has a set of talents.  You are also given for each worker a constant k_i saying how many jobs you'd like them to do, as well as a constant m_i saying the maximum number of jobs you can allocate to them.  Your goal is to assign the jobs to the workers in such a way that each job is done by a worker who has the skills, no worker does more than m_i jobs, and the number of the "excess" jobs done by the workers is minimized.  For example, if the re are five workers who each want to do four tasks and the load is balanced so that two workers do four jobs, one does three, and one does five, the total excess is one, since one worker did one more job than was expected.

The reduction is as follows.  For now, we'll ignore the balancing requirement and just see how tom reduce this to max-flow; we'll add load balancing at the end.  Construct a graph G with a designated start node s and sink node t.  Add to this graph a node for each job j and each worker w.  There will be an edge from s to each of these j nodes of cost zero and capacity one.  There will also be an edge from each w node to t with cost zero and capacity m_i.  Finally, for each job j and worker w, if worker w has the talents necessary to complete job j, there is an edge from j to w with cost zero and capacity one.

The idea is that we want to push flow from s to t through the j and w nodes such that each flow path going through some j node to a w node means that job j should be given to worker w.  The capacity restrictions on the edges from s to j nodes ensures that at most one unit of flow enters the j node, so the job is only assigned at most once. The capacity restriction on the edges from the w nodes to the node t prevent each worker from being assigned too many times.  Since all capacities are integral, an integral max flow exists from s to t, and so a max-flow in this graph corresponds to an assignments of jobs to workers that is legal and doesn't exceed any worker's maximum load.  You can check whether all jobs are assigned by looking at the total flow in the graph; if it's equal to the number of jobs, they've all been assigned.

This above construction, however, does nothing to balance worker loads.  To fix this, we'll modify the construction a bit.  Rather than having an edge from each w node to t, instead, for each w node, add two nodes to the graph, c and e, and connect them as follows.  There is an edge from w_i to c_i with capacity k_i and cost zero, and an identical edge from c_i to t.  There is also an edge from w_i to e_i with cost 1 and capacity m_i - k_i.  There is also an edge from e_i to t with equal capacity and zero cost.

Intuitively, we haven't changed the amount of flow that leaves any w node, but we have changed how much that flow costs.  Flow shunted to t via the c node is free, and so the worker can take on k_i jobs without incurring cost.  Any jobs after that have to be routed through e, which costs one for each unit of flow crossing it.  Finding a max-flow in this new graph still determines an assignment, but finding the min-cost max-flow in the graph finds the assignment that minimizes the excess jobs divvied up to workers.

Min-cost max flows can be solved in polynomial time with a few somewhat-well-known algorithms, so hopefully this is a useful answer!

Body:
(Before anyone asks, this is not homework.)

I have a set of workers with interests, i.e.:

Bob: Java, XML, Ruby

Susan: Java, HTML, Python

Fred: Python, Ruby

Sam: Java, Ruby

etc.

(There are actually somewhere in the range of 10-25 "interests" for each worker, and I have around 40-50 workers)

At the same time, I have a very large set of tasks that need to be distributed among the workers. Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests:

Task 1: Ruby, XML
Task 2: XHTML, Python

and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2.

This is all stored in a database thusly:

Task
    id integer primary key
    name varchar

TaskInterests
    task_id integer
    interest_id integer

Workers
    id integer primary key
    name varchar
    max_assignments integer

WorkerInterests
    worker_id
    interest_id

Assignments
    task_id
    worker_id
    date_assigned

Each worker has a maximum number of assignments they will do, around 10. Some interests are more rare than others (i.e. only 1 or 2 workers have listed them as a interest), some interests are more common (i.e. half of the workers list them).

The algorithm must:

Assign every task to 3 workers (it is
assumed that at least 3 of the
workers are interested in one of the
interests of the task).

Assign every worker 1 or more tasks

Ideally, the algorithm will:

Assign each worker a number of tasks proportional to their maximum assignments and the total number of tasks. For example, if Susan says she will do 20 tasks and most people will only do 10 tasks and there are 50 workers and 300 tasks, she should be assigned 12 tasks (20/10*(300/50)).

Assign a variety of tasks to each worker, so if Susan lists 4 interests she gets tasks that include 4 interests (rather than getting 10 tasks all with the same interest)

The most difficult aspect so far has been dealing with theses issues:

tasks having interests with few corresponding workers

workers who have few interests, especially

workers who have a few interests, for which there are relatively few tasks