问:
Thread issue updating state of second level component in React
I have the following structure for a part of my app, I'm trying to resemble a board game. A tile is an object { color1, color2, key }, and a HexTile is the React component that shows the tile.

```<code>class HexTile extends Component{
  constructor(props) {
    super(props);
    let { color1, color2, key } = props.tile;
    let tile = [color1, color2];

    // Initialize hexagons with some color
    const hexagons = GridGenerator.orientedRectangle(2, 1).map((hexagon, index) => {
      return Object.assign({}, hexagon, {
        color: tile[index],
        tile: key
      });
    });

    this.state = {
      hexagons,
      ...
    };
  }

  static propTypes = {
    ...,
    tile: PropTypes.object.isRequired,
    ...
  };

  render() {
    const { hexagons } = this.state;
    return (
      <Layout className="tile" size={{ x: 3, y: 3 }} flat={false} spacing={1.01}
              origin={{ x: this.props.x, y: this.props.y }}>
        {
          hexagons.map((hex, i) => (
            <Hexagon
              key={i}
              ...
              data={hex}
            >
            </Hexagon>
          ))
        }
      </Layout>
    );
  }
</code>```

TileList is a component that receives a list of tiles as props, saves it in its state and renders each tile:

```<code>class TileList extends Component{
  constructor(props){
    super(props);

    this.onDragEnd = this.onDragEnd.bind(this);

    const { tiles } = props;
    this.state = {
      ...,
      tiles: tiles
    };
  }

  render() {
    const { tiles } = this.state;
    return (
      <g>
        {
          tiles.map((tile, i) => (
            <HexTile key={i}
                     ...
                     tile={tile}
                     onDragEnd={this.onDragEnd}
                     ...
            />
          ))
        }
      </g>
    );
  }
</code>```

The app is the main component, it saves the list of tiles in its state and renders the TileList, also it updates when a tile has been used and changes it for a new Tile.

```<code>class App extends Component {
  constructor(props){
    super(props);

    // Event where the tile list is updated, this is working
    this.onDragEnd = this.onDragEnd.bind(this);
    ...
    const playerTiles = App.generateTiles(6);

    this.state = {
      ...
      playerTiles,
    };
  }

  render() {
    const { playerTiles, ... } = this.state;

    return (
      <div className="app">
        <HexGrid width={1200} height={800} viewBox="-50 -30 50 100">
          ...
          <TileList className={'tiles'}
                    tiles={playerTiles}
                    onDragEnd={this.onDragEnd}
                    ...
          />
        </HexGrid>
        ...
      </div>
    );
  }
</code>```

The state update between App and TileList is working, but the tile on the HexTile that should be updated is the same of the beginning and I don't know how to make it update. I don't include the event that generates the update because it includes another functionality, but I will add it if it's required. Nonetheless, I think the problem is in the initialization of HexTiles, but I haven't figure it out how to fix it.

答:
You need to update the hexagons with your new prop data. Try updating your state in componentWillReceiveProps:

```<code>componentWillReceiveProps(prevProps, nextProps){
    const { color1, color2, key } = nextProps.tile;
    const tile = [color1, color2];
    // Initialize hexagons with some color
    const hexagons = GridGenerator.orientedRectangle(2, 1).map((hexagon, index) => {
      return Object.assign({}, hexagon, {
        color: tile[index],
        tile: key
      });
    });

    this.state = {
      hexagons,
      ...
    };
}
</code>```

Body:
I have the following structure for a part of my app, I'm trying to resemble a board game. A tile is an object { color1, color2, key }, and a HexTile is the React component that shows the tile.

class HexTile extends Component{
  constructor(props) {
    super(props);
    let { color1, color2, key } = props.tile;
    let tile = [color1, color2];

    // Initialize hexagons with some color
    const hexagons = GridGenerator.orientedRectangle(2, 1).map((hexagon, index) => {
      return Object.assign({}, hexagon, {
        color: tile[index],
        tile: key
      });
    });

    this.state = {
      hexagons,
      ...
    };
  }

  static propTypes = {
    ...,
    tile: PropTypes.object.isRequired,
    ...
  };

  render() {
    const { hexagons } = this.state;
    return (
      <Layout className="tile" size={{ x: 3, y: 3 }} flat={false} spacing={1.01}
              origin={{ x: this.props.x, y: this.props.y }}>
        {
          hexagons.map((hex, i) => (
            <Hexagon
              key={i}
              ...
              data={hex}
            >
            </Hexagon>
          ))
        }
      </Layout>
    );
  }

TileList is a component that receives a list of tiles as props, saves it in its state and renders each tile:

class TileList extends Component{
  constructor(props){
    super(props);

    this.onDragEnd = this.onDragEnd.bind(this);

    const { tiles } = props;
    this.state = {
      ...,
      tiles: tiles
    };
  }

  render() {
    const { tiles } = this.state;
    return (
      <g>
        {
          tiles.map((tile, i) => (
            <HexTile key={i}
                     ...
                     tile={tile}
                     onDragEnd={this.onDragEnd}
                     ...
            />
          ))
        }
      </g>
    );
  }

The app is the main component, it saves the list of tiles in its state and renders the TileList, also it updates when a tile has been used and changes it for a new Tile.

class App extends Component {
  constructor(props){
    super(props);

    // Event where the tile list is updated, this is working
    this.onDragEnd = this.onDragEnd.bind(this);
    ...
    const playerTiles = App.generateTiles(6);

    this.state = {
      ...
      playerTiles,
    };
  }

  render() {
    const { playerTiles, ... } = this.state;

    return (

        <HexGrid width={1200} height={800} viewBox="-50 -30 50 100">
          ...
          <TileList className={'tiles'}
                    tiles={playerTiles}
                    onDragEnd={this.onDragEnd}
                    ...
          />
        </HexGrid>
        ...

    );
  }

The state update between App and TileList is working, but the tile on the HexTile that should be updated is the same of the beginning and I don't know how to make it update. I don't include the event that generates the update because it includes another functionality, but I will add it if it's required. Nonetheless, I think the problem is in the initialization of HexTiles, but I haven't figure it out how to fix it.

Body:
You need to update the hexagons with your new prop data. Try updating your state in componentWillReceiveProps:

componentWillReceiveProps(prevProps, nextProps){
    const { color1, color2, key } = nextProps.tile;
    const tile = [color1, color2];
    // Initialize hexagons with some color
    const hexagons = GridGenerator.orientedRectangle(2, 1).map((hexagon, index) => {
      return Object.assign({}, hexagon, {
        color: tile[index],
        tile: key
      });
    });

    this.state = {
      hexagons,
      ...
    };
}


来源: stackexchange

问:
Cast base class to derived class python (or more pythonic way of extending classes)
I need to extend the Networkx python package and add a few methods to the Graph class for my particular need

The way I thought about doing this is simplying deriving a new class say NewGraph, and adding the required methods.

However there are several other functions in networkx which create and return Graph objects (e.g. generate a random graph).  I now need to turn these Graph objects into NewGraph objects so that I can use my new methods.

What is the best way of doing this?  Or should I be tackling the problem in a completely different manner?

答:
You could simply create a new NewGraph derived from Graph object and have the __init__ function include something like self.__dict__.update(vars(incoming_graph)) as the first line, before you define your own properties. In this way you basically copy all the properties from the Graph you have onto a new object, derived from Graph, but with your special sauce.

```<code>class NewGraph(Graph):
  def __init__(self, incoming_graph):
    self.__dict__.update(vars(incoming_graph))

    # rest of my __init__ code, including properties and such
</code>```

Usage:

```<code>graph = function_that_returns_graph()
new_graph = NewGraph(graph)
cool_result = function_that_takes_new_graph(new_graph)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You could simply create a new NewGraph derived from Graph object and have the __init__ function include something like self.__dict__.update(vars(incoming_graph)) as the first line, before you define your own properties. In this way you basically copy all the properties from the Graph you have onto a new object, derived from Graph, but with your special sauce.

class NewGraph(Graph):
  def __init__(self, incoming_graph):
    self.__dict__.update(vars(incoming_graph))

    # rest of my __init__ code, including properties and such

Usage:

graph = function_that_returns_graph()
new_graph = NewGraph(graph)
cool_result = function_that_takes_new_graph(new_graph)

ContentLicense: CC BY-SA 3.0


问:
Upload to S3 database config in JS
I'm quite new at AWS, so what I am doing is probably very wrong. I'm working on an app which uses an S3 bucket for data storage. The users will have no access to this, so there is no need for user authentification. I just want to send a file from my code to the server. I use the following code to attempt this, but I cannot escape credential errors. Any advice would be greatly appreciated!

```<code>var bucketName = 'my-bucket-name';
    var bucketRegion = 'us-west-2';
    function send(){

      var bucket = new AWS.S3({
          params: {
              Bucket: bucketName
          }
      });

      AWS.config.update({
        region: bucketRegion,
        accessKeyId: "my-access-key",
        secretAccessKey: "my-secret-key"
        //credentials: new AWS.CognitoIdentityCredentials({
        //  IdentityPoolId: poolID
        //})
      });

      var timestamp = new Date().getTime()/1000;
      var canvas = document.getElementById('canvas');
      var data = canvas.toDataURL();
      if (data) {
            //Object key will be facebook-USERID#/FILE_NAME
            var objKey = "test-"+timestamp;
            var params = {
                Key: objKey,
                ContentType: data.type,
                Body: data,
                ACL: 'public-read'
            };
          bucket.putObject(params, function (err, data) {
              if (err) {
                  console.log('ERROR: ' + err);
              } else {
                  listObjs();
              }
          });
      } else {
          console.log('Nothing to upload.');
      }
  }
</code>```

edit: the exact text of the error I get:

ERROR: CredentialsError: Missing credentials in config

答:
If your code is being hosted in Lambda, it's possible that you haven't set up a policy that allows the two services to speak to each other.

I would look into managing these policies here:

http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html

Title: Upload to S3 database config in JS

Body:
I'm quite new at AWS, so what I am doing is probably very wrong. I'm working on an app which uses an S3 bucket for data storage. The users will have no access to this, so there is no need for user authentification. I just want to send a file from my code to the server. I use the following code to attempt this, but I cannot escape credential errors. Any advice would be greatly appreciated!

var bucketName = 'my-bucket-name';
    var bucketRegion = 'us-west-2';
    function send(){

      var bucket = new AWS.S3({
          params: {
              Bucket: bucketName
          }
      });

      AWS.config.update({
        region: bucketRegion,
        accessKeyId: "my-access-key",
        secretAccessKey: "my-secret-key"
        //credentials: new AWS.CognitoIdentityCredentials({
        //  IdentityPoolId: poolID
        //})
      });

      var timestamp = new Date().getTime()/1000;
      var canvas = document.getElementById('canvas');
      var data = canvas.toDataURL();
      if (data) {
            //Object key will be facebook-USERID#/FILE_NAME
            var objKey = "test-"+timestamp;
            var params = {
                Key: objKey,
                ContentType: data.type,
                Body: data,
                ACL: 'public-read'
            };
          bucket.putObject(params, function (err, data) {
              if (err) {
                  console.log('ERROR: ' + err);
              } else {
                  listObjs();
              }
          });
      } else {
          console.log('Nothing to upload.');
      }
  }

edit: the exact text of the error I get:

ERROR: CredentialsError: Missing credentials in config


问:
Unable to upload file from Wordpress plugin to symfony backend server over the API?
My project have two Parts

wordpress frontend

Symfony backend

I am trying to calling the API of may backend symfony project from Wordpress plugin to store some data in the backend. all the text data is being saved but when I am trying to send image files they are not being saved in the backend. I know its a tricky business but I am really looking for the solution.

for uploading images we are doing following steps

we are temporarily uploading images to our Wordpress upload folder

then we are sending those files in our request in calling api

symfony backend API is getting the request and uploading the images accordingly

here is my Wordpress front end code and its request variable:

```<code>$localUploadPath  = dirname(__DIR__).DIRECTORY_SEPARATOR.'uploads';
$randomDir  = Helper::randomDirName();
$uploadedAssets = Files::uploadPassAssets( $localUploadPath , $randomDir );
$request = new Request();
$submitedValues = $request->all();
$request->files($uploadedAssets);
$groupArray = $request->getGroups();

//remote files upload
$remoteFiles = array();
foreach($uploadedAssets as $fieldName => $imageFiles){
    $imageWithPath = $localUploadPath.'/'.$randomDir.'/'.$imageFiles;
    $remoteFiles[$fieldName.'File'] = '@'.realpath($imageWithPath);
}
$client = new ClientApi(PASSBUILDER_ADDPASS_UPLOAD_URL);
$client->setFiles($remoteFiles);
$uploadResponse = $client->getResponse();
$this->rrmdir($localUploadPath.'/'.$randomDir);
</code>```

request for the api is:

```<code>{ ["appearance_logoNameFile"]=> string(149) "@/home/public_html/ads/wp-content/plugins/passbook-app/uploads/4e1020ee2b0dda294c746b5bb5acc0bd/26f27e532c874b63dca651dec4553b20ca237a44.png" ["appearance_eventTicketStripFile"]=> string(149) "@/home/public_html/ads/wp-content/plugins/passbook-app/uploads/4e1020ee2b0dda294c746b5bb5acc0bd/7354f12e6d185eee8142268b32eea6a055036d35.png" ["generalid"]=> string(32) "4ba11ffe3f2b8a46626632b48b38fcaf" ["pass_id"]=> int(198) ["email"]=> string(17) "sample@unknown.com" }
</code>```

images are physically saved in the Wordpress upload folder and also being sent through api but our backend is not picking up the images and are not uploading them

here is our backend code of symfony:

```<code>public function createpassuploadAction(Request $request){

    $data = $request->request->all();
    $helper = $this->get('passbook.passhelper');
    $webDir = $helper->webDir;

    $passId = $data['pass_id'];
    $userEmail = $data['email'];
    $generalid = $data['generalid'];

    $filesResult = array();
    $filesBag = $request->files->all();
    foreach ($filesBag as $file){
        $filename = $file->getClientOriginalName();
        $filesResult []=  array(
            'path' => $file->getPathname(),
            'url'  => 'ddd'
        );
        $src    =  $webDir.'/upload/'.$passId.'/';
        $file->move( $src ,$filename );
    }
}
</code>```

For the record this code was perfectly running 2 years ago but it suddenly stoped working:

I am getting this error

```<code>request.INFO: Matched route "curd.api.pass.create.uploads" (parameters: "_format": "json", "_controller": "Cogilent\PassbookBundle\Controller\ApiController::createpassuploadAction", "_route": "curd.api.pass.create.uploads") [] []
[2017-06-04 04:57:07] security.INFO: Populated SecurityContext with an anonymous Token [] []
</code>```

答: there was an error at '@'.realpath($path) from php 5.5 and above this is used curl_file_create(realpath($path)) instead of '@'. problem solved

Body:
My project have two Parts

wordpress frontend

Symfony backend

I am trying to calling the API of may backend symfony project from Wordpress plugin to store some data in the backend. all the text data is being saved but when I am trying to send image files they are not being saved in the backend. I know its a tricky business but I am really looking for the solution.

for uploading images we are doing following steps

we are temporarily uploading images to our Wordpress upload folder

then we are sending those files in our request in calling api

symfony backend API is getting the request and uploading the images accordingly

here is my Wordpress front end code and its request variable:

$localUploadPath  = dirname(__DIR__).DIRECTORY_SEPARATOR.'uploads';
$randomDir  = Helper::randomDirName();
$uploadedAssets = Files::uploadPassAssets( $localUploadPath , $randomDir );
$request = new Request();
$submitedValues = $request->all();
$request->files($uploadedAssets);
$groupArray = $request->getGroups();

//remote files upload
$remoteFiles = array();
foreach($uploadedAssets as $fieldName => $imageFiles){
    $imageWithPath = $localUploadPath.'/'.$randomDir.'/'.$imageFiles;
    $remoteFiles[$fieldName.'File'] = '@'.realpath($imageWithPath);
}
$client = new ClientApi(PASSBUILDER_ADDPASS_UPLOAD_URL);
$client->setFiles($remoteFiles);
$uploadResponse = $client->getResponse();
$this->rrmdir($localUploadPath.'/'.$randomDir);

request for the api is:

{ ["appearance_logoNameFile"]=> string(149) "@/home/public_html/ads/wp-content/plugins/passbook-app/uploads/4e1020ee2b0dda294c746b5bb5acc0bd/26f27e532c874b63dca651dec4553b20ca237a44.png" ["appearance_eventTicketStripFile"]=> string(149) "@/home/public_html/ads/wp-content/plugins/passbook-app/uploads/4e1020ee2b0dda294c746b5bb5acc0bd/7354f12e6d185eee8142268b32eea6a055036d35.png" ["generalid"]=> string(32) "4ba11ffe3f2b8a46626632b48b38fcaf" ["pass_id"]=> int(198) ["email"]=> string(17) "sample@unknown.com" }

images are physically saved in the Wordpress upload folder and also being sent through api but our backend is not picking up the images and are not uploading them

here is our backend code of symfony:

public function createpassuploadAction(Request $request){

    $data = $request->request->all();
    $helper = $this->get('passbook.passhelper');
    $webDir = $helper->webDir;

    $passId = $data['pass_id'];
    $userEmail = $data['email'];
    $generalid = $data['generalid'];

    $filesResult = array();
    $filesBag = $request->files->all();
    foreach ($filesBag as $file){
        $filename = $file->getClientOriginalName();
        $filesResult []=  array(
            'path' => $file->getPathname(),
            'url'  => 'ddd'
        );
        $src    =  $webDir.'/upload/'.$passId.'/';
        $file->move( $src ,$filename );
    }
}

For the record this code was perfectly running 2 years ago but it suddenly stoped working:

I am getting this error

request.INFO: Matched route "curd.api.pass.create.uploads" (parameters: "_format": "json", "_controller": "Cogilent\PassbookBundle\Controller\ApiController::createpassuploadAction", "_route": "curd.api.pass.create.uploads") [] []
[2017-06-04 04:57:07] security.INFO: Populated SecurityContext with an anonymous Token [] []


问:
Alter Table Distribution (Azure Data warehouse)
In rushing to get off work I ran a large insert on a new table that has a Round Robin distribution. I know it is unlikely, but is there a way to alter the table's distribution from Round Robin to a Hash Distribution?</p>

答:
Unfortunately ALTER TABLE does not support changing the distribution of a table in Azure SQL Data Warehouse.  The next best thing you could do is create a copy of the table using CTAS, drop the original table, then rename the new one, something like this:

```<code>CREATE TABLE dbo.yourTable2
WITH (
    CLUSTERED COLUMNSTORE INDEX,
    DISTRIBUTION = HASH ( yourColumn )
    )
AS
SELECT *
FROM dbo.yourTable
OPTION ( LABEL = 'CTAS: Change distribution on dbo.yourTable' );
GO

DROP TABLE dbo.yourTable
GO
RENAME OBJECT dbo.yourTable2 TO yourTable;
GO
</code>```

Body:
Unfortunately ALTER TABLE does not support changing the distribution of a table in Azure SQL Data Warehouse.  The next best thing you could do is create a copy of the table using CTAS, drop the original table, then rename the new one, something like this:

CREATE TABLE dbo.yourTable2
WITH (
    CLUSTERED COLUMNSTORE INDEX,
    DISTRIBUTION = HASH ( yourColumn )
    )
AS
SELECT *
FROM dbo.yourTable
OPTION ( LABEL = 'CTAS: Change distribution on dbo.yourTable' );
GO

DROP TABLE dbo.yourTable
GO
RENAME OBJECT dbo.yourTable2 TO yourTable;
GO


问:
C Variadic Macro to simplify calls to fprintf
I have defined a clunky macro to give myself a reduced probability of making mistakes in a project with a large amount of unique logging situations...

```<code>#define BANG(...) {fprintf(stderr, "in %s(), ", __func__);\
                   fprintf(stderr, ##__VA_ARGS__);}
</code>```

And I can call this quite successfully like this...

```<code>BANG("Something went wrong\n");
</code>```

But the following (obviously) breaks in frightening ways...

```<code>if(emulatorExitCode == 1)
    BANG("emulatorExitCode: %d (an error)\n", emulatorExitCode);
else
    everythingIsWonderful = 1;
</code>```

I know the reason of course, it's the semicolon I accidentally left on the end of the call to BANG();

That rogue semicolon causes the if/else construct to separate into two fragments, disassociated from eachother.  Here's the compiler error...

```<code>main.c:74:3: error: ‘else’ without a previous ‘if’
</code>```

So far so good, the workaround is to have -Wall -Werror -Wextra -Wpedantic in my compiler arguments so I cannot accidentally cause a horrible mess of my logic.

And as long as I always leave out the semicolon on the end of the BANG() macro calls I'll be OK because the macro definition uses braces around the two fprintf(); calls.  But I'm worried that other people maintaining my code later will not realise that this is a problem (it's really not obvious) and get in a mess.

Question

Can this macro #define be rewritten to either reduce the danger posed by the problematic semicolon OR can it be rewritten to roll these two calls to fprintf into a single call?  The latter is complicated by the fact that it's variadic AND has the famously head-scratchy printf-family semantics to deal with.

答:
A multi-statement should be wrapped in a do..while block to avoid exactly this type of issue.

```<code>#define BANG(...) do{ \
                     fprintf(stderr, "in %s(), ", __func__);\
                     fprintf(stderr, ##__VA_ARGS__);\
                  } while (0)
</code>```

So your if block then expands to:

```<code>if(emulatorExitCode == 1)
    do{
      fprintf(stderr, "in %s(), ", __func__);   // ignoring the __func__ expansion
      fprintf(stderr, "emulatorExitCode: %d (an error)\n", emulatorExitCode);
    } while (0);
else
    everythingIsWonderful = 1;
</code>```

The fact that you're using a variadic macro doesn't matter in this case.

Body:
I have defined a clunky macro to give myself a reduced probability of making mistakes in a project with a large amount of unique logging situations...

#define BANG(...) {fprintf(stderr, "in %s(), ", __func__);\
                   fprintf(stderr, ##__VA_ARGS__);}

And I can call this quite successfully like this...

BANG("Something went wrong\n");

But the following (obviously) breaks in frightening ways...

if(emulatorExitCode == 1)
    BANG("emulatorExitCode: %d (an error)\n", emulatorExitCode);
else
    everythingIsWonderful = 1;

I know the reason of course, it's the semicolon I accidentally left on the end of the call to BANG();

That rogue semicolon causes the if/else construct to separate into two fragments, disassociated from eachother.  Here's the compiler error...

main.c:74:3: error: ‘else’ without a previous ‘if’

So far so good, the workaround is to have -Wall -Werror -Wextra -Wpedantic in my compiler arguments so I cannot accidentally cause a horrible mess of my logic.

And as long as I always leave out the semicolon on the end of the BANG() macro calls I'll be OK because the macro definition uses braces around the two fprintf(); calls.  But I'm worried that other people maintaining my code later will not realise that this is a problem (it's really not obvious) and get in a mess.

Question

Can this macro #define be rewritten to either reduce the danger posed by the problematic semicolon OR can it be rewritten to roll these two calls to fprintf into a single call?  The latter is complicated by the fact that it's variadic AND has the famously head-scratchy printf-family semantics to deal with.

Body:
A multi-statement should be wrapped in a do..while block to avoid exactly this type of issue.

#define BANG(...) do{ \
                     fprintf(stderr, "in %s(), ", __func__);\
                     fprintf(stderr, ##__VA_ARGS__);\
                  } while (0)

So your if block then expands to:

if(emulatorExitCode == 1)
    do{
      fprintf(stderr, "in %s(), ", __func__);   // ignoring the __func__ expansion
      fprintf(stderr, "emulatorExitCode: %d (an error)\n", emulatorExitCode);
    } while (0);
else
    everythingIsWonderful = 1;

The fact that you're using a variadic macro doesn't matter in this case.


问:
ReactJS: How to I create selectable Child Form that passes data back to Parent form?
My Apologies for being vague, but I do not know how better I can explain this situation. I am learning ReactJS and JS as well. I am working on a project where I have following Requirement.

There is a Form where user can add text, numbers

There is a DropDown Menu (I am using Material UI - http://www.material-ui.com/#/components/dropdown-menu) which once clicked opens a new Page/component

This Child Page/Component has List Data and user must be able to pick one of the items in it.

Once clicked, the data goes back to Parent Component and Child Page disappears.

Visually, I found an example of how it should work  http://recordit.co/GIDxCbD28X

I am looking for guidance on how to build this workflow. Again, apologies for open-ended question, but I hope to get help on this. Thanks

答:
You keep the selection from DropDown Menu in your Form component state. Form component has a method that sets this state to a new value. You pass this method down to DropDown Menu as a prop. DropDown menu calls this method when the user selects an item.

You should probably also keep the boolean that tells you whether DropDown Menu page/modal/whatever is visible or not, so the method that handles selection of an item can both set that flag to false and set the selected item to a new value with one setState() call.


问:
laravel 5 ERR_TOO_MANY_REDIRECTS
I'm creating a laravel website, when I put in the server and start to test the website after a time I get the ERR_TOO_MANY_REDIRECTS, and I don't know why this happen. Someone know why?

```<code>Route::group(['middleware'=>'auth'], function(){

    Route::get('/', 'Usuario\FuncionarioCtrl@index');
    Route::get('/home', 'Usuario\FuncionarioCtrl@index');

    Route::get('/login/sair', ['as'=>'login.sair', 'uses'=>'Login\LoginCtrl@sair']);

    Route::resource('admin', 'Admin\AdminCtrl');
    Route::resource('ajudas', 'Ajuda\AjudaCtrl');
    Route::resource('brindes', 'Brinde\BrindeCtrl');
    Route::resource('configuracoes', 'Configuracoes\AppCtrl');
    Route::resource('csv', 'Configuracoes\CsvCtrl');
    Route::resource('destinos', 'Destino\DestinoCtrl');
    Route::resource('funcionarios', 'Usuario\FuncionarioCtrl');
    Route::resource('mensagens', 'Mensagem\MensagemCtrl');
    Route::resource('midias', 'Multimidia\multimidiaCtrl');
    Route::resource('noticias', 'Noticia\NoticiaCtrl');
    Route::resource('suportes', 'Suporte\SuporteCtrl');
    Route::resource('regulamentos', 'Regulamento\RegulamentoCtrl');
    Route::resource('retirar', 'Brinde\Retira_brindeCtrl');
    Route::resource('revendas', 'TiposUsuarios\RevendaCtrl');

    Route::resource('vendas', 'TiposUsuarios\VendaCtrl');
    Route::resource('familias', 'TiposUsuarios\FamiliaCtrl');
    Route::resource('outros', 'TiposUsuarios\OutroCtrl');

});

Route::group(['middleware'=>'guest'], function(){
    Route::get('/login', ['as'=>'login.index',

'uses'=>'Login\LoginCtrl@index']);
        Route::get('/login/entrar', ['as'=>'login.entrar', 'uses'=>'Login\LoginCtrl@entrar']);
});
</code>```

答:
I had a very similar problem. It happens when you load your site on port 443 and you are on port 80.

You probably need to comment out HSTS in your servers config file. Like this.

```<code>#add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
</code>```

Title: laravel 5 ERR_TOO_MANY_REDIRECTS

Body:
I'm creating a laravel website, when I put in the server and start to test the website after a time I get the ERR_TOO_MANY_REDIRECTS, and I don't know why this happen. Someone know why?

Route::group(['middleware'=>'auth'], function(){

    Route::get('/', 'Usuario\FuncionarioCtrl@index');
    Route::get('/home', 'Usuario\FuncionarioCtrl@index');

    Route::get('/login/sair', ['as'=>'login.sair', 'uses'=>'Login\LoginCtrl@sair']);

    Route::resource('admin', 'Admin\AdminCtrl');
    Route::resource('ajudas', 'Ajuda\AjudaCtrl');
    Route::resource('brindes', 'Brinde\BrindeCtrl');
    Route::resource('configuracoes', 'Configuracoes\AppCtrl');
    Route::resource('csv', 'Configuracoes\CsvCtrl');
    Route::resource('destinos', 'Destino\DestinoCtrl');
    Route::resource('funcionarios', 'Usuario\FuncionarioCtrl');
    Route::resource('mensagens', 'Mensagem\MensagemCtrl');
    Route::resource('midias', 'Multimidia\multimidiaCtrl');
    Route::resource('noticias', 'Noticia\NoticiaCtrl');
    Route::resource('suportes', 'Suporte\SuporteCtrl');
    Route::resource('regulamentos', 'Regulamento\RegulamentoCtrl');
    Route::resource('retirar', 'Brinde\Retira_brindeCtrl');
    Route::resource('revendas', 'TiposUsuarios\RevendaCtrl');

    Route::resource('vendas', 'TiposUsuarios\VendaCtrl');
    Route::resource('familias', 'TiposUsuarios\FamiliaCtrl');
    Route::resource('outros', 'TiposUsuarios\OutroCtrl');

});

Route::group(['middleware'=>'guest'], function(){
    Route::get('/login', ['as'=>'login.index',

'uses'=>'Login\LoginCtrl@index']);
        Route::get('/login/entrar', ['as'=>'login.entrar', 'uses'=>'Login\LoginCtrl@entrar']);
});

Body:
I had a very similar problem. It happens when you load your site on port 443 and you are on port 80.

You probably need to comment out HSTS in your servers config file. Like this.

#add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";


问:
Library to recognize Dutch dates in text?
I have a series of strings (in Dutch) that contain a date in either a DD-MM-YYYY format or in a textual format DD month YYYY. See an example selection here: https://paste.ee/p/XZLha. I'm looking for a Python (2.7) library that is able to recognize the date from these text strings.

dateutil is not able to properly parse Dutch

dateparser is not able to parse fuzzy strings - it only accepts strings with dates and days. It can handle Dutch dates though.

I'd like to get your input on possible solutions. I'm considering stripping the text around the dates away and working with dateparser.

答:
Below is an example using regular expressions as @Shiva recommended.  It will probably need some refinement but the concept is there:

```<code>import re

SOURCE_DATA_SAMPLE = """gedaan te Amsterdam, op 13-4-2010, door
gedaan te Amsterdam, op 13 april 2010, door
gedaan te Amsterdam, op 12 juni 2003, door
gedaan te Amsterdam, op 12 juni 2002, door
Aldus gedaan op 24 oktober 2003 door
Aldus gedaan op 5 december 2003 door
Aldus gedaan op 5 december 2003 door
Aldus gedaan op 8 april 2004 door
Aldus gedaan op 16 april 2004 door
Aldus gedaan op 23 april 2004 door
Aldus gedaan op 10 september 2004 door
Aldus gedaan op 30 september 2004 door"""

DATE_REGEX = re.compile("(\d{1,2}-\d{1,2}-\d{4})|(\d{1,2} \w.*? \d{4})")

def find_date(line):
    matched = DATE_REGEX.search(line)
    if (matched):
        return matched.group(0)
    else:
        return None

for line in SOURCE_DATA_SAMPLE.split("\n"):
    date = find_date(line)
    print(date)
</code>```

There's a great site called Regex101 that can help writing expressions; the sample I used for the above is here: https://regex101.com/r/wMFfx4/2

Body:
Below is an example using regular expressions as @Shiva recommended.  It will probably need some refinement but the concept is there:

import re

SOURCE_DATA_SAMPLE = """gedaan te Amsterdam, op 13-4-2010, door
gedaan te Amsterdam, op 13 april 2010, door
gedaan te Amsterdam, op 12 juni 2003, door
gedaan te Amsterdam, op 12 juni 2002, door
Aldus gedaan op 24 oktober 2003 door
Aldus gedaan op 5 december 2003 door
Aldus gedaan op 5 december 2003 door
Aldus gedaan op 8 april 2004 door
Aldus gedaan op 16 april 2004 door
Aldus gedaan op 23 april 2004 door
Aldus gedaan op 10 september 2004 door
Aldus gedaan op 30 september 2004 door"""

DATE_REGEX = re.compile("(\d{1,2}-\d{1,2}-\d{4})|(\d{1,2} \w.*? \d{4})")

def find_date(line):
    matched = DATE_REGEX.search(line)
    if (matched):
        return matched.group(0)
    else:
        return None

for line in SOURCE_DATA_SAMPLE.split("\n"):
    date = find_date(line)
    print(date)

There's a great site called Regex101 that can help writing expressions; the sample I used for the above is here: https://regex101.com/r/wMFfx4/2


问:
Getting value of specific column for each row
I need to write script which allows me import data in xml format. It generates block of code I need for every order except variables. I need to go through all rows in range and get values from column "G". Problem is it gets only value of first row in range.

```<code>Dim rng As Range, row As Range
Set rng = Range(Range("G11"), Range("G11").End(xlDown))
For Each row In rng.Rows
Dim partner_id As String
partner_id = Cells(rng.row, 7).Value
line9 = "<typ:id>" & partner_id & "</typ:id>" & vbNewLine

...
</code>```

I'm not a programmer as you can see, but I really need to get that partner_id. I would appreciate any suggestions.

答:
You really should avoid using variable names which are the same as the common Methods used by Excel objects so, for instance, change row to be myRow perhaps.  That would then highlight what I think was causing your issue - the use of rng.row which, with a renamed variable, you would probably have written as rng.myRow - which would then give a compile error.

rng.row is simply returning the row number of the first cell in rng, and has nothing to do with your variable called row.

```<code>Dim rng As Range, myRow As Range
Set rng = Range(Range("G11"), Range("G11").End(xlDown))
'There's no need to use "rng.Rows" when each row is a single cell anyway
For Each myRow In rng
    Dim partner_id As String
    'because myRow is a single cell, we can just use its Value
    partner_id = myRow.Value
    line9 = "<typ:id>" & partner_id & "</typ:id>" & vbNewLine

    ...
</code>```

FWIW - leaving your variable names and coding style unchanged, you could have fixed the code by using row.Row instead of rng.Row, i.e.

```<code>Dim rng As Range, row As Range
Set rng = Range(Range("G11"), Range("G11").End(xlDown))
For Each row In rng.Rows
Dim partner_id As String
partner_id = Cells(row.Row, 7).Value
line9 = "<typ:id>" & partner_id & "</typ:id>" & vbNewLine

...
</code>```

Body:
I need to write script which allows me import data in xml format. It generates block of code I need for every order except variables. I need to go through all rows in range and get values from column "G". Problem is it gets only value of first row in range.

Dim rng As Range, row As Range
Set rng = Range(Range("G11"), Range("G11").End(xlDown))
For Each row In rng.Rows
Dim partner_id As String
partner_id = Cells(rng.row, 7).Value
line9 = "<typ:id>" & partner_id & "</typ:id>" & vbNewLine

...

I'm not a programmer as you can see, but I really need to get that partner_id. I would appreciate any suggestions.

Body:
You really should avoid using variable names which are the same as the common Methods used by Excel objects so, for instance, change row to be myRow perhaps.  That would then highlight what I think was causing your issue - the use of rng.row which, with a renamed variable, you would probably have written as rng.myRow - which would then give a compile error.

rng.row is simply returning the row number of the first cell in rng, and has nothing to do with your variable called row.

Dim rng As Range, myRow As Range
Set rng = Range(Range("G11"), Range("G11").End(xlDown))
'There's no need to use "rng.Rows" when each row is a single cell anyway
For Each myRow In rng
    Dim partner_id As String
    'because myRow is a single cell, we can just use its Value
    partner_id = myRow.Value
    line9 = "<typ:id>" & partner_id & "</typ:id>" & vbNewLine

    ...

FWIW - leaving your variable names and coding style unchanged, you could have fixed the code by using row.Row instead of rng.Row, i.e.

Dim rng As Range, row As Range
Set rng = Range(Range("G11"), Range("G11").End(xlDown))
For Each row In rng.Rows
Dim partner_id As String
partner_id = Cells(row.Row, 7).Value
line9 = "<typ:id>" & partner_id & "</typ:id>" & vbNewLine

...


问:
Why can I not click on this element in this code?
Actions action = new Actions(driver);
IWebElement we = driver.FindElement(By.XPath(".//*[@class='ms-crm-CommandBar-Button ms-crm-Menu-Label']"));

action.MoveToElement(driver.FindElement(By.XPath(".//*[@class='ms-crm-CommandBar-Button ms-crm-Menu-Label-Hovered']"))).Click().Build().Perform();

expect element as followings:

            New

            Create a new Lead record.

Note that this class "ms-crm-CommandBar-Button ms-crm-Menu-Label" turns to be "ms-crm-CommandBar-Button ms-crm-Menu-Label-Hovered" when mouseover.

Many thanks.

答:
When you search for the hovered element it doesn't exist.
So you need to hover element first, then you'll be able to find and click hovered element.
action.MoveToElement(driver.FindElement(By.XPath("//*[@class='ms-crm-CommandBar-Button ms-crm-Menu-Label']"))).Build().Perform().MoveToElement(driver.FindElement(By.XPath("//*[@class='ms-crm-CommandBar-Button ms-crm-Menu-Label-Hovered']"))).Click().Build().Perform();


问:
Merging text files line for line batch file
I began with an excel spreadsheet with a couple of columns (a Date of Birth, and a Last Name column). I extrapolated and used a batch file to modify just the date of birth column so that I now have a text file with the following (to be used in a SQL query):

```<code>BirthDateTime = '01/01/2017' AND Name LIKE '
BirthDateTime = '01/01/2016' AND Name LIKE '
</code>```

I now want to take the second column (by creating a separate lastname.txt file) and concatonate it into the output file above line for line so that my last name file, which looks like:

```<code>SMITH
JONES
</code>```

Will merge to a new output file that will look like:

```<code>(BirthDateTime = '01/01/2017' AND Name LIKE '%SMITH%') OR
(BirthDateTime = '01/01/2016' AND Name LIKE '%JONES%') OR
</code>```

Unfortunately I'm a newbie on batch files and I just don't know where to start. I'm including the batch file I used to create the first part below.

Batch File:

```<code>@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo BirthDateTime = '%%a' AND Name LIKE '>>output.txt
)
</code>```

答:
Per @Stephan's comment I just set out to do this in Excel and used the following formula:

="(BirthDateTime = '"&A2&"' AND Name LIKE '%"&B2&"%') OR" which worked fine. Since I asked specifically about batch files I'm not sure it's appropriate for me to accept this as an answer. If somebody has some code, or if Stephan wants to post his link as an answer with some explanation into his code I will accept that, otherwise I will accept this as the answer in 2 days.

Body:
I began with an excel spreadsheet with a couple of columns (a Date of Birth, and a Last Name column). I extrapolated and used a batch file to modify just the date of birth column so that I now have a text file with the following (to be used in a SQL query):

BirthDateTime = '01/01/2017' AND Name LIKE '
BirthDateTime = '01/01/2016' AND Name LIKE '

I now want to take the second column (by creating a separate lastname.txt file) and concatonate it into the output file above line for line so that my last name file, which looks like:

SMITH
JONES

Will merge to a new output file that will look like:

(BirthDateTime = '01/01/2017' AND Name LIKE '%SMITH%') OR
(BirthDateTime = '01/01/2016' AND Name LIKE '%JONES%') OR

Unfortunately I'm a newbie on batch files and I just don't know where to start. I'm including the batch file I used to create the first part below.

Batch File:

@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo BirthDateTime = '%%a' AND Name LIKE '>>output.txt
)


问:
The 'xmlns' attribute is bound to the reserved namespace 'http://www.w3.org/2000/xmlns/'
I'm using a terminal application a predecessor wrote, using Infragistics to process some SQL data into excel report templates.

It works fine for some sets of data, but it throws the following: The 'xmlns' attribute is bound to the reserved namespace 'http://www.w3.org/2000/xmlns/'

Nowhere in the App config is any xmlns defined, and I'm at a loss. I can share code, please help me figure out what's relevant.

答:
In a comment you state

This project doesn't have an XML file

But in your question you state

SQL data into excel report templates

Modern Excel files are XML based...

Just navigate to any related Excel file and open it with a ZIP application. You can change the file extension to .zip and just double click this.

I'm, prette sure, that your application is generating such a XML formatted Excel file...


问:
Downloading files based on timestamp in Python
I'm trying to create a method that allows me to download files from a server (using HTTP) only if the file is newest than the version already downloaded to my computer.

I found a way to get the last time that the file was modified on the server (at least the last time that the server thinks that it was modified):

```<code>u = urllib2.urlopen(url)
meta = u.info()
print("Last Modified: " + str(meta.getheaders("Last-Modified")))
</code>```

The problem now is how to use this information to compare with the files that I already have on my computer and see if that version located on the server is newer than the version saved on my computer.

I tried to use python-wget library; however, it didn't help. It is downloading everything and not even is overwriting the files (it is creating new ones), so I realized that that    library doesn't check the timestamp.

What is the best way to solve that?

答:
I don't have enough reputation yet to add a comment to an answer so I just added my own answer.

I am using Python 2.7 and had to modify the answer given by @parfait to get this to work.

1) I had to convert the list you get from meta.getheaders("Last-Modified") to a string.

2) When you convert a time to seconds, a higher number of seconds will be a newer date, since more seconds means more time has passed since some date. So I also changed the > to < in the if statement.

The result is as follows:

```<code>import os, datetime, time

u = urllib2.urlopen(url)
meta = u.info()
print("Last Modified: " + str(meta.getheaders("Last-Modified")))

# CONVERTING HEADER TIME TO UTC TIMESTAMP
# ASSUMING 'Sun, 28 Jun 2015 06:30:17 GMT' FORMAT
# Remember datetime.datetime.strptime() takes a string as the first param...
meta_modifiedtime = time.mktime(datetime.datetime.strptime( \
                    ''.join(meta.getheaders("Last-Modified")), "%a, %d %b %Y %X GMT").timetuple())

file = 'C:\Path\ToFile\somefile.xml'
if os.path.getmtime(file) < meta_modifiedtime: #change > to <
   print("CPU file is older than server file.")
else:
   print("CPU file is NOT older than server file.")
</code>```

Body:
I'm trying to create a method that allows me to download files from a server (using HTTP) only if the file is newest than the version already downloaded to my computer.

I found a way to get the last time that the file was modified on the server (at least the last time that the server thinks that it was modified):

u = urllib2.urlopen(url)
meta = u.info()
print("Last Modified: " + str(meta.getheaders("Last-Modified")))

The problem now is how to use this information to compare with the files that I already have on my computer and see if that version located on the server is newer than the version saved on my computer.

I tried to use python-wget library; however, it didn't help. It is downloading everything and not even is overwriting the files (it is creating new ones), so I realized that that    library doesn't check the timestamp.

What is the best way to solve that?

Body:
I don't have enough reputation yet to add a comment to an answer so I just added my own answer.

I am using Python 2.7 and had to modify the answer given by @parfait to get this to work.

1) I had to convert the list you get from meta.getheaders("Last-Modified") to a string.

2) When you convert a time to seconds, a higher number of seconds will be a newer date, since more seconds means more time has passed since some date. So I also changed the > to < in the if statement.

The result is as follows:

import os, datetime, time

u = urllib2.urlopen(url)
meta = u.info()
print("Last Modified: " + str(meta.getheaders("Last-Modified")))

# CONVERTING HEADER TIME TO UTC TIMESTAMP
# ASSUMING 'Sun, 28 Jun 2015 06:30:17 GMT' FORMAT
# Remember datetime.datetime.strptime() takes a string as the first param...
meta_modifiedtime = time.mktime(datetime.datetime.strptime( \
                    ''.join(meta.getheaders("Last-Modified")), "%a, %d %b %Y %X GMT").timetuple())

file = 'C:\Path\ToFile\somefile.xml'
if os.path.getmtime(file) < meta_modifiedtime: #change > to <
   print("CPU file is older than server file.")
else:
   print("CPU file is NOT older than server file.")


问:
Send http request in Ionic with Angular http
I have an ionic app that I am trying to send my Stripe token to, for payment processing. When I send the request to the node server with curl it is receiving the request. However, when I try to send the request via Angular's http module, it isn't registering at all. All of this is currently being tested locally, so that might be part of the issue?

HTML

```<code><button (click)="testPost()" ion-button full>TEST POST</button>
</code>```

cart.ts

```<code>...
import {Http, Headers, RequestOptions} from '@angular/http';
import { Stripe } from '@ionic-native/stripe';

@Component({
 selector: 'page-cart',
 templateUrl: 'cart.html',
})
export class Cart {

  constructor(
    ...
    private http: Http,
    private stripe: Stripe
    ) {
      //
    });
  }

  testPost() {
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      body: {
        token: 'axqrexample123tokenbasdflkjo3',
        amount: 225
      }
    }

    this.http.post("http://11.1.1.7:3100/charge", postParams, options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });
  }

}
</code>```

NODE SERVER

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var stripe = require("stripe")("sk_test_abcTAdefgn1oDexamplex");

app.use(bodyParser.json());

app.post('/charge', function (req, res) {

  var token = req.body.token;
  var amount = req.body.amount;
  stripe.charges.create({
    amount: amount,
    currency: "usd",
    source: token, // obtained with Stripe.js
    description: "Charge for jones@example.com"
  }, function(err, charge) {
    // asynchronously called
  });
  res.send('Hello World!')
});

app.listen(3100, function () {
  console.log('Example app listening on port 3100!')
})
</code>```

答:
I would try this in the stripe.charges.create callback and see what happens:

```<code>}, function(err, charge) {
  if (err) throw err;

  console.log('Charge ID:', charge.id);

  res.send('Hello World!');
});
</code>```

Body:
I have an ionic app that I am trying to send my Stripe token to, for payment processing. When I send the request to the node server with curl it is receiving the request. However, when I try to send the request via Angular's http module, it isn't registering at all. All of this is currently being tested locally, so that might be part of the issue?

HTML

<button (click)="testPost()" ion-button full>TEST POST</button>

cart.ts

...
import {Http, Headers, RequestOptions} from '@angular/http';
import { Stripe } from '@ionic-native/stripe';

@Component({
 selector: 'page-cart',
 templateUrl: 'cart.html',
})
export class Cart {

  constructor(
    ...
    private http: Http,
    private stripe: Stripe
    ) {
      //
    });
  }

  testPost() {
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      body: {
        token: 'axqrexample123tokenbasdflkjo3',
        amount: 225
      }
    }

    this.http.post("http://11.1.1.7:3100/charge", postParams, options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });
  }

}

NODE SERVER

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var stripe = require("stripe")("sk_test_abcTAdefgn1oDexamplex");

app.use(bodyParser.json());

app.post('/charge', function (req, res) {

  var token = req.body.token;
  var amount = req.body.amount;
  stripe.charges.create({
    amount: amount,
    currency: "usd",
    source: token, // obtained with Stripe.js
    description: "Charge for jones@example.com"
  }, function(err, charge) {
    // asynchronously called
  });
  res.send('Hello World!')
});

app.listen(3100, function () {
  console.log('Example app listening on port 3100!')
})

Body:
I would try this in the stripe.charges.create callback and see what happens:

}, function(err, charge) {
  if (err) throw err;

  console.log('Charge ID:', charge.id);

  res.send('Hello World!');
});


问:
Using ReactJS to create print page
There has got to be a less brute force way of making a print page then the way I have been doing it. (See below code).  Maybe with ReactJS and DOM insertions in some manner since the rest of my website is written with ReactJS? (See second example below)  I have tried using the CSS @media print, but it does not work well on very complex websites in all the browser flavors.  More recently, I have been making an entirely separate ReactJS website just for the print page and then passing it query strings for some of the information required on the print page.  What a mess that makes!

```<code>  var html: string = '<!DOCTYPE html>';

  html += '<html lang="en">';

  html += '<head>';
  html += '<meta charset="utf-8">';
  html += '<title>Title</title>';
  html += '</head>';

  html += '<body style="background-color: white;">';
  html += '<div">';
  html += getContent();
  html += '</div>';
  html += '</body>';
  html += '</html>';

  var newWin = window.open();
  newWin.document.write(html);
  newWin.document.close();
</code>```

Second example:

```<code>  var sNew = document.createElement("script");
  sNew.async = true;
  sNew.src = "Bundle.js?ver=" + Date.now();
  var s0 = document.getElementsByTagName('script')[0];
  s0.parentNode.insertBefore(sNew, s0);
</code>```

答:
Yeah there is, checkout react-print.</p>

```<code>var React = require('react');
var ReactDOM = require('react-dom');
var PrintTemplate = require ('react-print');

class MyTemplate extends React.Component {
  render() {
    return (
          <PrintTemplate>
             <div>
                  <h3>All markup for showing on print</h3>
                  <p>Write all of your "HTML" (really JSX) that you want to show
                  on print, in here</p>
                  <p>If you need to show different data, you could grab that data
                  via AJAX on componentWill/DidMount or pass it in as props</p>
                  <p>The CSS will hide the original content and show what is in your
                  Print Template.</p>
             </div>
           </PrintTemplate>
       )
  }
}

ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));
</code>```

Title: Using ReactJS to create print page

Body:
There has got to be a less brute force way of making a print page then the way I have been doing it. (See below code).  Maybe with ReactJS and DOM insertions in some manner since the rest of my website is written with ReactJS? (See second example below)  I have tried using the CSS @media print, but it does not work well on very complex websites in all the browser flavors.  More recently, I have been making an entirely separate ReactJS website just for the print page and then passing it query strings for some of the information required on the print page.  What a mess that makes!

  var html: string = '<!DOCTYPE html>';

  html += '';

  html += '';
  html += '<meta charset="utf-8">';
  html += '<title>Title</title>';
  html += '';

  html += '';
  html += '
';
  html += getContent();
  html += '
';
  html += '';
  html += '';

  var newWin = window.open();
  newWin.document.write(html);
  newWin.document.close();

Second example:

  var sNew = document.createElement("script");
  sNew.async = true;
  sNew.src = "Bundle.js?ver=" + Date.now();
  var s0 = document.getElementsByTagName('script')[0];
  s0.parentNode.insertBefore(sNew, s0);

Body:
Yeah there is, checkout react-print.

var React = require('react');
var ReactDOM = require('react-dom');
var PrintTemplate = require ('react-print');

class MyTemplate extends React.Component {
  render() {
    return (
          <PrintTemplate>
             <div>
                  <h3>All markup for showing on print</h3>
                  <p>Write all of your "HTML" (really JSX) that you want to show
                  on print, in here</p>
                  <p>If you need to show different data, you could grab that data
                  via AJAX on componentWill/DidMount or pass it in as props</p>
                  <p>The CSS will hide the original content and show what is in your
                  Print Template.</p>
             </div>
           </PrintTemplate>
       )
  }
}

ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));


问:
AngularFire2 update and delete profile of other user
I have angular2 app and I try to allow the admin to update profile of the others users.

But I don't know how to find the user to update or delete its data profile...

How can I do ?

答:
Without using the Admin SDK, you cannot manipulate any user account from inside an app.  In order to use the Admin SDK you would have to initialize it from within the app, which would make your Admin token available in the browser, which is unwise.

So one way to do this would be to create a node app that you could run securely somewhere (not available to the public) that connects to your Firebase app and is able to manipulate users that way.

The only "user manipulation" that's possible from inside a Firebase app for any given user is updating their own information and the ability to create a new user.

It should be noted that the user authentication and any "user information" you may or may not store in your database are separate and unrelated unless maintained by you and your app.


问:
How to avoid Java OutofMemoryError Heap Space in loop with StringBuilder?
Here is my code that throws java.lang.OutOfMemoryError: Java heap space:

```<code>StringBuilder sb = new StringBuilder();
    for (int i = 0; i< ranks.size(); i++) {
        Map<String, String> map = ranks.get(i);
        sb.append("SELECT ");
        int iter = 0;
        for (String key : map.keySet()) {
            if (key.equals("ware_md5")) {
                sb.append("'").append(map.get(key)).append(" ' AS ").append(key);
            }
            else {
                sb.append(map.get(key)).append(" AS ").append(key);
            }
            if (iter < map.keySet().size() - 1) {
                sb.append(",");
            }
            iter++;
        }
        if (i < ranks.size() - 1) {
            sb.append(" UNION ALL ");
        }

    }
    return sb.toString();
</code>```

'ranks' ArrayList contains about 30 000 values

Is there any way to rewrite this peace of code to avoid this error ?

答:
More memory is the easiest solution, already given

new StringBuilder(100_000) - at least faster

AS key is not needed but for the first union.

Note that SortedMap is what you need: the keys always in the same order.

consume ranks.get(i)

Body:
Here is my code that throws java.lang.OutOfMemoryError: Java heap space:

StringBuilder sb = new StringBuilder();
    for (int i = 0; i< ranks.size(); i++) {
        Map<String, String> map = ranks.get(i);
        sb.append("SELECT ");
        int iter = 0;
        for (String key : map.keySet()) {
            if (key.equals("ware_md5")) {
                sb.append("'").append(map.get(key)).append(" ' AS ").append(key);
            }
            else {
                sb.append(map.get(key)).append(" AS ").append(key);
            }
            if (iter < map.keySet().size() - 1) {
                sb.append(",");
            }
            iter++;
        }
        if (i < ranks.size() - 1) {
            sb.append(" UNION ALL ");
        }

    }
    return sb.toString();

'ranks' ArrayList contains about 30 000 values

Is there any way to rewrite this peace of code to avoid this error ?


问:
How to thru char into TextBox?
I have some TextBox on focus ( cursor is blinking on him ).
Now, from other usercontrol ( that contain buttons ) i want to send event that will insert char into the TextBox when pressing any of the buttons that are on the usercontrol.

This need to be without lose the focus from the TextBox ... ( blinking cursor on the TextBox )

How can i do it ?
( i try to raise key down event - but its does not work )

答:
Do you want to use this virtual keyboard with other applications, or is it something that's only going on in your application? Beyond that, if it is only your application, do you only ever want to insert characters into one particular TextBox, or potentially any TextBox?

If it's a virtual keyboard intended to work with any application, then you'll want to use a Win32 API method like SendKeys. WinForms has an extremely easy interface for using SendKeys.

If it only ever needs to add characters to the one TextBox, then it's much more easy to modify the TextBox's Text property rather than trying to raise events on it to get the desired behavior. There's a CaretIndex property that will tell you where to insert the character. Beyond that, it's simple string concatenation.

Title: How to thru char into TextBox?


问:
Terminal path is not an actual place
When I opened terminal today, all commands (ls,touch, python ...) don't work. I look up online and find out it is because the path in terminal gets replaced. So I open the .bash_profile and find this below. I comment out the last line and terminal gets normal again.

So I have this question, where does the last line come from? And what are those special characters?

(The day before, I installed pygames. Is it possible cause?)

```<code> #added by Anaconda3 4.3.1 installer
export PATH="/Users/test/anaconda/bin:$PATH"
export PATH=‚Äô/usr/local/bin:Äô
</code>```

答:
It seems like there was either an issue during the install or a file encoding error, but as a fix instead of commenting out the last line you should change it to:

export PATH="/usr/local/bin:$PATH"

as that seems like what Anaconda was trying to do there.

Title: Terminal path is not an actual place

Body:
When I opened terminal today, all commands (ls,touch, python ...) don't work. I look up online and find out it is because the path in terminal gets replaced. So I open the .bash_profile and find this below. I comment out the last line and terminal gets normal again.

So I have this question, where does the last line come from? And what are those special characters?

(The day before, I installed pygames. Is it possible cause?)

 #added by Anaconda3 4.3.1 installer
export PATH="/Users/test/anaconda/bin:$PATH"
export PATH=‚Äô/usr/local/bin:Äô


问:
Move to the previous/next function in AndroidStudio (Vim Emulator)
I'm a vim user and recently I started learning writing apps for Android.

I use Android Studio 2.3.2 with Vim emulator.

As it comes to Vim- I usually use it for C++ programming and one of the features I use on a daily basis is ]] to move to the next function and [[ to get to the previous function.

When I use that in Android Studio it just moves me to the beginning/end of the file.

My guess is that it is related with opening function scope in the same line instead of in the new line.

Question:

Is that possible to jump to next/previous function using Android Studio Vim emulator just as I used to do in C++ code (even though I use Java coding style, a.k.a. "egyptian brackets")?

答:
From the docs :help ]]

```<code>                            *]]*
]]          [count] sections forward or to the next '{' in the
            first column.  When used after an operator, then also
            stops below a '}' in the first column.  |exclusive|
            Note that |exclusive-linewise| often applies.
</code>```

Which means it just goes to the next statement that has '{' as the first character of the line, which happens to be the case C and C++ functions (at least in some styleguides), as methods and functions start with a {, without any type of nesting.

However, when writing Java, methods are nested inside of classes, which means they usually have a level of indentation.

According to this answer, Vim has the builtin [m and ]m mappings, to navigate methods.

```<code>                        *]m*
]m          Go to [count] next start of a method (for Java or
            similar structured language).  When not before the
            start of a method, jump to the start or end of the
            class.  When no '{' is found after the cursor, this is
            an error.  |exclusive| motion.
</code>```

So, if you wish to use [[ and ]] for navigating methods, you could remap these in your ~/.ideavimrc.

```<code>nnoremap [[ [m
nnoremap ]] ]m
</code>```

Body:
From the docs :help ]]

                            *]]*
]]          [count] sections forward or to the next '{' in the
            first column.  When used after an operator, then also
            stops below a '}' in the first column.  |exclusive|
            Note that |exclusive-linewise| often applies.

Which means it just goes to the next statement that has '{' as the first character of the line, which happens to be the case C and C++ functions (at least in some styleguides), as methods and functions start with a {, without any type of nesting.

However, when writing Java, methods are nested inside of classes, which means they usually have a level of indentation.

According to this answer, Vim has the builtin [m and ]m mappings, to navigate methods.

                        *]m*
]m          Go to [count] next start of a method (for Java or
            similar structured language).  When not before the
            start of a method, jump to the start or end of the
            class.  When no '{' is found after the cursor, this is
            an error.  |exclusive| motion.

So, if you wish to use [[ and ]] for navigating methods, you could remap these in your ~/.ideavimrc.

nnoremap [[ [m
nnoremap ]] ]m


问:
How to automatically convert strongly typed enum into int?
```<code>#include <iostream>

struct a {
  enum LOCAL_A { A1, A2 };
};
enum class b { B1, B2 };

int foo(int input) { return input; }

int main(void) {
  std::cout << foo(a::A1) << std::endl;
  std::cout << foo(static_cast<int>(b::B2)) << std::endl;
}
</code>```

The a::LOCAL_A is what the strongly typed enum is trying to achieve, but there is a small difference : normal enums can be converted into integer type, while strongly typed enums can not do it without a cast.

So, is there a way to convert a strongly typed enum value into an integer type without a cast? If yes, how?

答:
This seems impossible with the native enum class, but probably you can mock a enum class with a class:

In this case,

```<code>enum class b
{
    B1,
    B2
};
</code>```

would be equivalent to:

```<code>class b {
 private:
  int underlying;
 public:
  static constexpr int B1 = 0;
  static constexpr int B2 = 1;
  b(int v) : underlying(v) {}
  operator int() {
      return underlying;
  }
};
</code>```

This is mostly equivalent to the original enum class. You can directly return b::B1 for in a function with return type b. You can do switch case with it, etc.

And in the spirit of this example you can use templates (possibly together with other things) to generalize and mock any possible object defined by the enum class syntax.

ContentLicense: CC BY-SA 4.0

Body:
#include <iostream>

struct a {
  enum LOCAL_A { A1, A2 };
};
enum class b { B1, B2 };

int foo(int input) { return input; }

int main(void) {
  std::cout << foo(a::A1) << std::endl;
  std::cout << foo(static_cast<int>(b::B2)) << std::endl;
}

The a::LOCAL_A is what the strongly typed enum is trying to achieve, but there is a small difference : normal enums can be converted into integer type, while strongly typed enums can not do it without a cast.

So, is there a way to convert a strongly typed enum value into an integer type without a cast? If yes, how?

Body:
This seems impossible with the native enum class, but probably you can mock a enum class with a class:

In this case,

enum class b
{
    B1,
    B2
};

would be equivalent to:

class b {
 private:
  int underlying;
 public:
  static constexpr int B1 = 0;
  static constexpr int B2 = 1;
  b(int v) : underlying(v) {}
  operator int() {
      return underlying;
  }
};

This is mostly equivalent to the original enum class. You can directly return b::B1 for in a function with return type b. You can do switch case with it, etc.

And in the spirit of this example you can use templates (possibly together with other things) to generalize and mock any possible object defined by the enum class syntax.


问:
Node.JS - nodemon + webpack not detecting file change over NFS
I need some help with nodemone and webpack. My team and I are working on a project, we are still in the early stage, but I've been fighting this issue for three days.
We are working on a remote physical host that runs multiple VMs. Each VM is serving different purpose. I have setup an NFS share between the VM and the host. We all work from home so we upload the files via FTP to the host (actually we use Visual Studio Code with ftp-sync plugin, so when I hit the save button, the file automatically uploads to the remote folder). However, nodemon and webpack are not detecting the change in the file.

I have mounted the nfs share with the following options:

```<code>mount -o noac,sync <host IP address>:/path/to/folder
</code>```

I have checked the ctime and mtime and they are in perfect sync. However, for some reason the change in the file is never detected by webpack and nodemon. If I hit touch  within the guest, it works.
Can anyone suggest any solution to this issue?

答:
I actually managed to find a solution literally few minutes after I posted my answer. So basically the issue was fixed by adding "--watch-poll" argument to my package.json scripts.

```<code>"scripts": {
"dev:build": "webpack -w --watch-poll",
"dev": "cross-env NODE_ENV=development nodemon dist/index.bundle.js" }
</code>```

Right now, when I save the file within Visual Studio Code, it is automatically uploaded to the host, synced with the VM development environment and automatically re-compiled and the server restarted with nodemon.

Body:
I need some help with nodemone and webpack. My team and I are working on a project, we are still in the early stage, but I've been fighting this issue for three days.
We are working on a remote physical host that runs multiple VMs. Each VM is serving different purpose. I have setup an NFS share between the VM and the host. We all work from home so we upload the files via FTP to the host (actually we use Visual Studio Code with ftp-sync plugin, so when I hit the save button, the file automatically uploads to the remote folder). However, nodemon and webpack are not detecting the change in the file.

I have mounted the nfs share with the following options:

mount -o noac,sync <host IP address>:/path/to/folder

I have checked the ctime and mtime and they are in perfect sync. However, for some reason the change in the file is never detected by webpack and nodemon. If I hit touch  within the guest, it works.
Can anyone suggest any solution to this issue?

Body:
I actually managed to find a solution literally few minutes after I posted my answer. So basically the issue was fixed by adding "--watch-poll" argument to my package.json scripts.

"scripts": {
"dev:build": "webpack -w --watch-poll",
"dev": "cross-env NODE_ENV=development nodemon dist/index.bundle.js" }

Right now, when I save the file within Visual Studio Code, it is automatically uploaded to the host, synced with the VM development environment and automatically re-compiled and the server restarted with nodemon.


问:
What's the theoretically fastest access to member of nullable type in C#?
I have a field of a nullable type with a value other than null.
Which of the methods below is the fastest, in theory:

Null conditional member access

```<code>ThisCantBeNull?.SomeMember
</code>```

Cast to non-nullable

```<code>((MyType)ThisCantBeNull).SomeMember
</code>```

Use of the Value member of nullable types

```<code>ThisCantBeNull.Value.SomeMember
</code>```

Note that this is only a theoretical question, such minor differences do not matter, I'm only interested in how the language works and what goes on in the background.

答:
Since you've already checked for null elsewhere, just get the Value, your third option.

The other two options include an extra check.

But, as noted in the comments, the performance improvement is probably minimal.

Body:
I have a field of a nullable type with a value other than null.
Which of the methods below is the fastest, in theory:

Null conditional member access

ThisCantBeNull?.SomeMember

Cast to non-nullable

((MyType)ThisCantBeNull).SomeMember

Use of the Value member of nullable types

ThisCantBeNull.Value.SomeMember

Note that this is only a theoretical question, such minor differences do not matter, I'm only interested in how the language works and what goes on in the background.


问:
Exception in thread "main" java.lang.NumberFormatException: For input string: "8/3/2012"
Why I'm getting these error message.</p>

```<code>Exception in thread "main" java.lang.NumberFormatException: For input string: "8/3/2012"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
    at java.lang.Double.parseDouble(Double.java:510)
    at com.exel.raf.seeit.ExecuteImport.excelDtToString(ExecuteImport.java:713)
    at com.exel.raf.seeit.ExecuteImport.generateItemHistorySql(ExecuteImport.java:649)
    at com.exel.raf.seeit.ExecuteImport.execute(ExecuteImport.java:56)
    at com.exel.raf.seeit.ExecuteImport.main(ExecuteImport.java:38)
    Process exited with exit code 1.
</code>```

答:
If you are trying to convert String to Number. In the above case I think your String is "8/3/2012". For converting to any number, you must not have any characters other than numbers or you can have double if you want decimals.

This looks like a date, please explore the Date class and see how you can convert it to a date.

Body:
Why I'm getting these error message.

Exception in thread "main" java.lang.NumberFormatException: For input string: "8/3/2012"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
    at java.lang.Double.parseDouble(Double.java:510)
    at com.exel.raf.seeit.ExecuteImport.excelDtToString(ExecuteImport.java:713)
    at com.exel.raf.seeit.ExecuteImport.generateItemHistorySql(ExecuteImport.java:649)
    at com.exel.raf.seeit.ExecuteImport.execute(ExecuteImport.java:56)
    at com.exel.raf.seeit.ExecuteImport.main(ExecuteImport.java:38)
    Process exited with exit code 1.


问:
ItemizedOverlay Issues (HelloMapView Tutorial)
I am having trouble with the Hello Map Views tutorial from the Android Developer website: http://developer.android.com/resources/tutorials/views/hello-mapview.html

My first problem was that upon clicking the overlay item, the application would crash.  This problem was solved by making sure to pass the context to the ItemizedOverlay class that I created...

After I fixed this problem, the icon for the overlay does not display in the map.  I am able to click on the map where the overlay is located and the dialog box displays.  Unfortunately, I cannot see the icon.  I have made sure that the image that I reference is an object located in the R.java resources file.  In fact my exact problem is asked by the poster of the following thread after going through the same issues.  Unfortunately his second question was never answered. Context null Pointer

Here is my MapView class:

```<code>package com.mapsExample;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class HelloMaps extends MapActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
        HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
        GeoPoint point = new GeoPoint(19240000,-99120000);
        OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
        itemizedoverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlay);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}
</code>```

And my ItemizedOverlay class:

```<code>package com.mapsExample;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class HelloItemizedOverlay extends ItemizedOverlay {

 private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
 Context mContext;

 public HelloItemizedOverlay(Drawable defaultMarker) {
   super(boundCenterBottom(defaultMarker));
 }

 public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
  super(defaultMarker);
  mContext = context;
 }

 public void addOverlay(OverlayItem overlay) {
     mOverlays.add(overlay);
     populate();
 }

 @Override
 protected OverlayItem createItem(int i) {
   return mOverlays.get(i);
 }

 @Override
 public int size() {
   return mOverlays.size();
 }

 @Override
 protected boolean onTap(int index) {
   OverlayItem item = mOverlays.get(index);
   AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
   dialog.setTitle(item.getTitle());
   dialog.setMessage(item.getSnippet());
   dialog.show();
   return true;
 }

}
</code>```

Again, If I do not pass 'this' to the ItemizedOverlay constructor, the icon displays but cannot be clicked.  Any help is much appreciated.  Thanks in advance!

答:
change the super call in your second constructor to:

super(boundCenterBottom(defaultMarker));

that should work!

Body:
I am having trouble with the Hello Map Views tutorial from the Android Developer website: http://developer.android.com/resources/tutorials/views/hello-mapview.html

My first problem was that upon clicking the overlay item, the application would crash.  This problem was solved by making sure to pass the context to the ItemizedOverlay class that I created...

After I fixed this problem, the icon for the overlay does not display in the map.  I am able to click on the map where the overlay is located and the dialog box displays.  Unfortunately, I cannot see the icon.  I have made sure that the image that I reference is an object located in the R.java resources file.  In fact my exact problem is asked by the poster of the following thread after going through the same issues.  Unfortunately his second question was never answered. Context null Pointer

Here is my MapView class:

package com.mapsExample;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class HelloMaps extends MapActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
        HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
        GeoPoint point = new GeoPoint(19240000,-99120000);
        OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
        itemizedoverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlay);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

And my ItemizedOverlay class:

package com.mapsExample;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class HelloItemizedOverlay extends ItemizedOverlay {

 private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
 Context mContext;

 public HelloItemizedOverlay(Drawable defaultMarker) {
   super(boundCenterBottom(defaultMarker));
 }

 public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
  super(defaultMarker);
  mContext = context;
 }

 public void addOverlay(OverlayItem overlay) {
     mOverlays.add(overlay);
     populate();
 }

 @Override
 protected OverlayItem createItem(int i) {
   return mOverlays.get(i);
 }

 @Override
 public int size() {
   return mOverlays.size();
 }

 @Override
 protected boolean onTap(int index) {
   OverlayItem item = mOverlays.get(index);
   AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
   dialog.setTitle(item.getTitle());
   dialog.setMessage(item.getSnippet());
   dialog.show();
   return true;
 }

}

Again, If I do not pass 'this' to the ItemizedOverlay constructor, the icon displays but cannot be clicked.  Any help is much appreciated.  Thanks in advance!


问:
Matrix columns zeroing, C language
I need to make a little project but I completely don't know how. Im giving matrix A of size n, and it have to return me matrix B which is matrix A with zeroed first and penultimate column. All I did is

```<code>#include<stdio.h>
#include<math.h>
int main()
{
int i,n,j,;
int tab[n][n];
printf("Size of matrix:");
scanf("%d",&n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
    printf("A[%d][%d]=",i,j);
    scanf("%lf",&tab[i][j]);
}
printf("Data:");
printf("Matrix A[%d][%d]",n,m);
}
</code>```

Which I think should let me to type my matrix. What I should do next? Please help me.

答:
There are a lot of errors in your code, the variable m is not declared, the double array is declared with n non-initialized. As the size of matrix is only known at runtime (entered by user), you need to use dynamic memory allocation functions to allocate memory for your matrix.

Try this code:

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i, j, n;
    printf("Size of matrix: ");
    scanf("%d", &n);

    int *tab = (int*)malloc(sizeof(int)*n*n);

    for (i = 0; i < n; i++)
    {
         for (j = 0; j < n; j++)
         {
             printf("A[%d][%d]=",i,j);
             scanf("%d",(tab+i*n+j));
         }
    }

    for (i = 0; i < n; i++)
    {
        *(tab+i*n) = 0;
        *(tab+i*n+n-2) = 0;
    }

    //Print tab
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
             printf("%d ", *(tab+i*n+j));
        }
        printf("\n");
    }

    return 0;
}
</code>```

Title: Matrix columns zeroing, C language

Body:
I need to make a little project but I completely don't know how. Im giving matrix A of size n, and it have to return me matrix B which is matrix A with zeroed first and penultimate column. All I did is

#include<stdio.h>
#include<math.h>
int main()
{
int i,n,j,;
int tab[n][n];
printf("Size of matrix:");
scanf("%d",&n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
    printf("A[%d][%d]=",i,j);
    scanf("%lf",&tab[i][j]);
}
printf("Data:");
printf("Matrix A[%d][%d]",n,m);
}

Which I think should let me to type my matrix. What I should do next? Please help me.

Body:
There are a lot of errors in your code, the variable m is not declared, the double array is declared with n non-initialized. As the size of matrix is only known at runtime (entered by user), you need to use dynamic memory allocation functions to allocate memory for your matrix.

Try this code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i, j, n;
    printf("Size of matrix: ");
    scanf("%d", &n);

    int *tab = (int*)malloc(sizeof(int)*n*n);

    for (i = 0; i < n; i++)
    {
         for (j = 0; j < n; j++)
         {
             printf("A[%d][%d]=",i,j);
             scanf("%d",(tab+i*n+j));
         }
    }

    for (i = 0; i < n; i++)
    {
        *(tab+i*n) = 0;
        *(tab+i*n+n-2) = 0;
    }

    //Print tab
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
             printf("%d ", *(tab+i*n+j));
        }
        printf("\n");
    }

    return 0;
}


问:
MVC ViewModel HttpPost return value has null values
I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.

View model UserRightViewModel

```<code>public class UserRightViewModel
{
    public string SelectedItemId { get; set; }

    public SelectList Users;

    public List<RightViewModel> Rights { get; set; }
}
</code>```

View model RightsViewModel

```<code>public class RightsViewModel
{
    public int ID { get; set; }

    public string Name{ get; set; }

    public bool isSelected { get; set; }
}
</code>```

Controller Post

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
   UserRightsViewModel viewModel = _viewModel;
   /*value _viewModel = null for Users and Rights
   /* code stuff */
   return View(viewModel);
}
</code>```

View

```<code>@model Web.ViewModels.UserRightsViewModel
     @using (Html.BeginForm())
     {
         @Html.AntiForgeryToken()

    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <h1>
                @ViewBag.Title
            </h1>
            @*<ol class="breadcrumb">
                    <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
                    <li><a href="#">Examples</a></li>
                    <li class="active">Blank page</li>
                </ol>*@
        </section>

        <!-- Main content -->
        <section class="content">

            <!-- Default box -->
            <div class="box">
                <div class="box-header with-border">

                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
                            <i class="fa fa-minus"></i>
                        </button>
                        <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>

        <br />
                <div class="form-group">
                    @Html.LabelFor(model => model.SelectedItemId, "User", new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.SelectedItemId)
                    </div>
                </div>
                <br />

          <div class="box-body">

                    @for (int i = 0; i < Model.Rights.Count(); i += 2)
                    {
                        <div class="row form-group">
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="col-md-6">

                                        </div>
                                        <div class="col-md-6">
                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                    <div class="col-md-8">

                                        @Model.Rights.ElementAt(i).Denumire
                                    </div>
                                </div>

                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="col-md-6">

                                        </div>
                                        <div class="col-md-6">
                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                    <div class="col-md-8">
                                        @Model.Rights.ElementAt(i + 1).Name
                                    </div>
                                </div>
                            </div>
                        </div>

                    }
                    <br />
                    <br />
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="col-md-9">

                                </div>
                                <div class="col-md-3">
                                    <input type="submit" value="Save" class="btn btn-primary" />
                                </div>
                            </div>
                            <div class="col-md-6">
                                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-danger" })
                            </div>
                        </div>
                    </div>
                </div>
               </div>
        </section>
    </div>
}
</code>```

I have no idea why some values are null. Why some of values are sent and some not?

答: I can see you put submit button outside form. so form not submitting property.</p>

Body:
I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.

View model UserRightViewModel

public class UserRightViewModel
{
    public string SelectedItemId { get; set; }

    public SelectList Users;

    public List<RightViewModel> Rights { get; set; }
}

View model RightsViewModel

public class RightsViewModel
{
    public int ID { get; set; }

    public string Name{ get; set; }

    public bool isSelected { get; set; }
}

Controller Post

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
   UserRightsViewModel viewModel = _viewModel;
   /*value _viewModel = null for Users and Rights
   /* code stuff */
   return View(viewModel);
}

View

@model Web.ViewModels.UserRightsViewModel
     @using (Html.BeginForm())
     {
         @Html.AntiForgeryToken()

                @ViewBag.Title

            @*

 Home

Examples

Blank page

*@

                        <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">

                        </button>
                        <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">

                        </button>

                    @Html.LabelFor(model => model.SelectedItemId, "User", new { @class = "control-label col-md-2" })

                        @Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.SelectedItemId)

                    @for (int i = 0; i < Model.Rights.Count(); i += 2)
                    {

                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { @class = "text-danger" })

                                        @Model.Rights.ElementAt(i).Denumire

                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { @class = "text-danger" })

                                        @Model.Rights.ElementAt(i + 1).Name

                    }

                                    <input type="submit" value="Save" class="btn btn-primary" />

                                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-danger" })

}

I have no idea why some values are null. Why some of values are sent and some not?


问:
R apply KS Test to 2 Matrices Row by Row
I have two matrices A & B in R with equal number of rows, but different number of columns.

I want to run a Kolomogrov-Smirnov test with row by row with each matrix. That is, the first test would be ks.test(as.vector(A[1,]), as.vector(B[1,]), the second would be ks.test(as.vector(A[2,]), as.vector(B[2,]) and so on. Ideally, storing the resulting of each test in a vector or dataframe.

I figured mapply would be appropriate but it keeps giving me way more results than expected. I think it is performing the tests element by element instead of row by row. This is my code chunk:
mapply(ks.test, x=A, y=B)

Just testing the first row does not work as expected when I simply run:
mapply(ks.test, x=as.vector(A[1,]), y=as.vector(B[1,]))

How can I get the desired output of N p-values where N is the number of rows of my original matrices.?

This is what the first rows of each of my matrices looks like:

> A[1,]

```<code>[1] 0 0 0 0 0 0 0 0 0
</code>```

> B[1,]

```<code> V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36
  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
</code>```

答:
We can use Map/mapply.  While using Map/mapply we need to understand that it is applying the function on corresponding elements of the input data.  If the input data are vectors, then the corresponding elements will be each element of the vector, similarly a matrix is a vector with dimensions.  It will apply the function on each element.  Therefore, we can split the matrix by row and then apply the function on corresponding list element

```<code>unlist(mapply(ks.test, split(A, row(A)), split(B, row(B)))[2,], use.names = FALSE)
#[1] 0.3571429 0.8730159 0.8730159 0.3571429 0.8730159
</code>```

Or using a for loop

```<code>r1 <- numeric(nrow(A))
for(i in seq_len(nrow(A))){
    r1[i] <- ks.test(A[i,], B[i,])$p.value
 }
r1
#[1] 0.3571429 0.8730159 0.8730159 0.3571429 0.8730159
</code>```

data

```<code>set.seed(24)
A <- matrix(rnorm(25), 5, 5)
set.seed(42)
B <- matrix(rnorm(25), 5, 5)
</code>```

Body:
I have two matrices A & B in R with equal number of rows, but different number of columns.

I want to run a Kolomogrov-Smirnov test with row by row with each matrix. That is, the first test would be ks.test(as.vector(A[1,]), as.vector(B[1,]), the second would be ks.test(as.vector(A[2,]), as.vector(B[2,]) and so on. Ideally, storing the resulting of each test in a vector or dataframe.

I figured mapply would be appropriate but it keeps giving me way more results than expected. I think it is performing the tests element by element instead of row by row. This is my code chunk:
mapply(ks.test, x=A, y=B)

Just testing the first row does not work as expected when I simply run:
mapply(ks.test, x=as.vector(A[1,]), y=as.vector(B[1,]))

How can I get the desired output of N p-values where N is the number of rows of my original matrices.?

This is what the first rows of each of my matrices looks like:

> A[1,]

[1] 0 0 0 0 0 0 0 0 0

> B[1,]

 V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36
  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Body:
We can use Map/mapply.  While using Map/mapply we need to understand that it is applying the function on corresponding elements of the input data.  If the input data are vectors, then the corresponding elements will be each element of the vector, similarly a matrix is a vector with dimensions.  It will apply the function on each element.  Therefore, we can split the matrix by row and then apply the function on corresponding list element

unlist(mapply(ks.test, split(A, row(A)), split(B, row(B)))[2,], use.names = FALSE)
#[1] 0.3571429 0.8730159 0.8730159 0.3571429 0.8730159

Or using a for loop

r1 <- numeric(nrow(A))
for(i in seq_len(nrow(A))){
    r1[i] <- ks.test(A[i,], B[i,])$p.value
 }
r1
#[1] 0.3571429 0.8730159 0.8730159 0.3571429 0.8730159

data

set.seed(24)
A <- matrix(rnorm(25), 5, 5)
set.seed(42)
B <- matrix(rnorm(25), 5, 5)


问:
Re Order List Numbering VSTO
I am working on hiding 2 bullets of numbered list in Microsoft word document using VSTO(C#).
I am successful in hiding the bullets but i want to re arrange the bullets numbering after hiding.
Does someone has any idea how to do this?</p>

答: My recommendation is to use some library where you can apply conditional content. So if you have a document, which would be your template, you can define parts of this document to either be displayed or not in your final document. You can see some examples here. Your final document is plain .docx and will contain only those conditional contents that match the criterion. It will therefore not hide some content but it will simply not include it, if it doesn't match - and thus the numbering of list items will be correct.</p>

Title: Re Order List Numbering VSTO


问:
Upload secret file credentials to Jenkins with REST / CLI
How can I create a Jenkins Credential via REST API or Jenkins CLI? The credential should be of type "secret file", instead of a username / password combination.

The question is similar to this question, but not the same or a duplicate.

答:
To create Jenkins credentials via the CLI you can use the create-credentials-by-xml command:

```<code>java -jar jenkins-cli.jar -s <JENKINS_URL> create-credentials-by-xml  system::system::jenkins _ < credential-name.xml
</code>```

The best way to know the syntax of this is to create a credential manually, and then dump it:

```<code>java -jar jenkins-cli.jar -s <JENKINS_URL> get-credentials-as-xml system::system::jenkins _ credential-name > credential-name.xml
</code>```

Then you can use this XML example as a template, it should be self-explanatory.

Body:
To create Jenkins credentials via the CLI you can use the create-credentials-by-xml command:

java -jar jenkins-cli.jar -s <JENKINS_URL> create-credentials-by-xml  system::system::jenkins _ < credential-name.xml

The best way to know the syntax of this is to create a credential manually, and then dump it:

java -jar jenkins-cli.jar -s <JENKINS_URL> get-credentials-as-xml system::system::jenkins _ credential-name > credential-name.xml

Then you can use this XML example as a template, it should be self-explanatory.