问:
Save submitted form values in a JSON file using React
I'm trying to create a form in react which will update a JSON file with the values in the form upon submit. (The endgame is that this will create an array of data in the JSON file each time the form is submitted which can then be used to populate a "list" of the submitted results elsewhere in the app)

The form itself works OK but every time I press submit I get the error: "TypeError: fs.writeFile is not a function"

```<code>import React, { Component } from "react";
import { Form, Button } from 'semantic-ui-react';
import jsonfile from'jsonfile';

var file = 'data.json'

var obj = {name: 'JP'}

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      name: "",
      email: ""
    }

    this.handleChange = this.handleChange.bind(this);
    this.sendDataSomewhere = this.sendDataSomewhere.bind(this);
}

handleChange = (e, {name, value}) => {
  this.setState({[name]: value})
}

sendDataSomewhere = function jsonfile(file){
jsonfile.writeFile(file, obj, function (err) {
  console.error(err);
});
};

  render() {
    return (
     <div>
      <Form onSubmit={this.sendDataSomewhere}>
        <Form.Field>
          <Form.Input name="name" value={this.state.name} onChange={this.handleChange}/>
        </Form.Field>
        <Form.Field>
          <Form.Input name="email" value={this.state.email} onChange={this.handleChange}/>
        </Form.Field>
        <Button type="submit">Submit</Button>
       </Form>
     </div>
    );
  }
}
</code>```

If anyone could let me know what I'm doing wrong or provide an example of something similar I would greatly appreciate it.

Thanks

答:
Client-side solution is:</p>

```<code>const handleSaveToPC = (jsonData,filename) => {
  const fileData = JSON.stringify(jsonData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = `${filename}.json`;
  link.href = url;
  link.click();
}
</code>```

Body:
I'm trying to create a form in react which will update a JSON file with the values in the form upon submit. (The endgame is that this will create an array of data in the JSON file each time the form is submitted which can then be used to populate a "list" of the submitted results elsewhere in the app)

The form itself works OK but every time I press submit I get the error: "TypeError: fs.writeFile is not a function"

import React, { Component } from "react";
import { Form, Button } from 'semantic-ui-react';
import jsonfile from'jsonfile';

var file = 'data.json'

var obj = {name: 'JP'}

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      name: "",
      email: ""
    }

    this.handleChange = this.handleChange.bind(this);
    this.sendDataSomewhere = this.sendDataSomewhere.bind(this);
}

handleChange = (e, {name, value}) => {
  this.setState({[name]: value})
}

sendDataSomewhere = function jsonfile(file){
jsonfile.writeFile(file, obj, function (err) {
  console.error(err);
});
};

  render() {
    return (

      <Form onSubmit={this.sendDataSomewhere}>
        <Form.Field>
          <Form.Input name="name" value={this.state.name} onChange={this.handleChange}/>
        </Form.Field>
        <Form.Field>
          <Form.Input name="email" value={this.state.email} onChange={this.handleChange}/>
        </Form.Field>
        <Button type="submit">Submit</Button>
       </Form>

    );
  }
}

If anyone could let me know what I'm doing wrong or provide an example of something similar I would greatly appreciate it.

Thanks

Body:
Client-side solution is:

const handleSaveToPC = (jsonData,filename) => {
  const fileData = JSON.stringify(jsonData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = `${filename}.json`;
  link.href = url;
  link.click();
}


来源: stackexchange

问:
TF - ValueError: The two structures don't have the same number of elements
I am trying to run the code for a research paper Learned Optimizers that Scale and Generalize
When I run the metarun.py file (which is the main file), I get the following error:

```<code>Traceback (most recent call last):
File "metarun.py", line 394, in
tf.app.run()
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "metarun.py", line 388, in main
callbacks=[])
File "/home/rvl224/models/research/metaopt.py", line 184, in train_optimizer
train_output = opt.train(problem, dataset)
File "/home/rvl224/models/research/learned_optimizer/optimizer/trainable_optimizer.py", line 347, in train
swap_memory=True, shape_invariants=invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2816, in while_loop
result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2640, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2597, in _BuildLoop
nest.assert_same_structure(list(packed_vars_for_body), list(body_result))
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/util/nest.py", line 222, in assert_same_structure
% (len_nest1, nest1, len_nest2, nest2))
ValueError: The two structures don't have the same number of elements.

First structure (120 elements):
[<tf.Tensor 'while/Identity:0' shape=() dtype=int32>, <tf.Tensor 'while/Identity_1:0' shape=() dtype=float32>, [<tf.Tensor 'while/Identity_2:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_3:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_4:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_5:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_6:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_7:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_8:0' shape=(12, 1) dtype=float32>], [<tf.Tensor 'while/Identity_9:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_10:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_11:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_12:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_13:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_14:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_15:0' shape=(12, 1) dtype=float32>], [[<tf.Tensor 'while/Identity_16:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_17:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_18:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_19:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_20:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_21:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_22:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_23:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_24:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_25:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_26:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_27:0' shape=(11, 10) dtype=float32>, <tf.Tensor 'while/Identity_28:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_29:0' shape=(11, 1) dtype=float32>], [<tf.Tensor 'while/Identity_30:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_31:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_32:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_33:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_34:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_35:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_36:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_37:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_38:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_39:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_40:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_41:0' shape=(3, 10) dtype=float32>, <tf.Tensor 'while/Identity_42:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_43:0' shape=(3, 1) dtype=float32>], [<tf.Tensor 'while/Identity_44:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_45:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_46:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_47:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_48:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_49:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_50:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_51:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_52:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_53:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_54:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_55:0' shape=(9, 10) dtype=float32>, <tf.Tensor 'while/Identity_56:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_57:0' shape=(9, 1) dtype=float32>], [<tf.Tensor 'while/Identity_58:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_59:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_60:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_61:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_62:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_63:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_64:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_65:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_66:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_67:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_68:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_69:0' shape=(7, 10) dtype=float32>, <tf.Tensor 'while/Identity_70:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_71:0' shape=(7, 1) dtype=float32>], [<tf.Tensor 'while/Identity_72:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_73:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_74:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_75:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_76:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_77:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_78:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_79:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_80:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_81:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_82:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_83:0' shape=(5, 10) dtype=float32>, <tf.Tensor 'while/Identity_84:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_85:0' shape=(5, 1) dtype=float32>], [<tf.Tensor 'while/Identity_86:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_87:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_88:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_89:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_90:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_91:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_92:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_93:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_94:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_95:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_96:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_97:0' shape=(13, 10) dtype=float32>, <tf.Tensor 'while/Identity_98:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_99:0' shape=(13, 1) dtype=float32>], [<tf.Tensor 'while/Identity_100:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_101:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_102:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_103:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_104:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_105:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_106:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_107:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_108:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_109:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_110:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_111:0' shape=(12, 10) dtype=float32>, <tf.Tensor 'while/Identity_112:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_113:0' shape=(12, 1) dtype=float32>]], [<tf.Tensor 'while/Identity_114:0' shape=(1, 20) dtype=float32>], <tf.Tensor 'while/Identity_115:0' shape=(?,) dtype=float32>, <tf.Tensor 'while/Identity_116:0' shape=() dtype=float32>, <tf.Tensor 'while/Identity_117:0' shape= dtype=float32>, <tf.Tensor 'while/Identity_118:0' shape= dtype=int32>, <tf.Tensor 'while/Identity_119:0' shape= dtype=int32>]

Second structure (23 elements):
[<tf.Tensor 'while/add_21:0' shape=() dtype=int32>, <tf.Tensor 'while/Add:0' shape=() dtype=float32>, [<tf.Tensor 'while/LOL/PerTensor/sub_15:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_1/sub_15:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_2/sub_15:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_3/sub_15:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_4/sub_15:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_5/sub_15:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_6/sub_15:0' shape=(12, 1) dtype=float32>], [<tf.Tensor 'while/LOL/PerTensor/sub_15:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_1/sub_15:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_2/sub_15:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_3/sub_15:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_4/sub_15:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_5/sub_15:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_6/sub_15:0' shape=(12, 1) dtype=float32>], <map object at 0x7f0a9b8f4be0>, [<tf.Tensor 'while/LOL/Layer2_RNN/BiasGRUCell/add:0' shape=(1, 20) dtype=float32>], <tf.Tensor 'while/concat:0' shape=(?,) dtype=float32>, <tf.Tensor 'while/Identity_116:0' shape=() dtype=float32>, <tf.Tensor 'while/Identity_117:0' shape= dtype=float32>, <tf.Tensor 'while/Identity_118:0' shape= dtype=int32>, <tf.Tensor 'while/Identity_119:0' shape= dtype=int32>]
</code>```

I tried following the solution as suggested here, but I am not able to figure as to where to make changes in the code. It would be a big help if anyone can guide a way!

Thanks in Advance :)

答:
I too faced a similar error once.
The reason for this error might be because this code is Python 3.x incompatible and works only for Python 2.7.x version. Please check once and let me know!</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run the code for a research paper Learned Optimizers that Scale and Generalize
When I run the metarun.py file (which is the main file), I get the following error:

Traceback (most recent call last):
File "metarun.py", line 394, in
tf.app.run()
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "metarun.py", line 388, in main
callbacks=[])
File "/home/rvl224/models/research/metaopt.py", line 184, in train_optimizer
train_output = opt.train(problem, dataset)
File "/home/rvl224/models/research/learned_optimizer/optimizer/trainable_optimizer.py", line 347, in train
swap_memory=True, shape_invariants=invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2816, in while_loop
result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2640, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2597, in _BuildLoop
nest.assert_same_structure(list(packed_vars_for_body), list(body_result))
File "/home/rvl224/anaconda3/lib/python3.5/site-packages/tensorflow/python/util/nest.py", line 222, in assert_same_structure
% (len_nest1, nest1, len_nest2, nest2))
ValueError: The two structures don't have the same number of elements.

First structure (120 elements):
[<tf.Tensor 'while/Identity:0' shape=() dtype=int32>, <tf.Tensor 'while/Identity_1:0' shape=() dtype=float32>, [<tf.Tensor 'while/Identity_2:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_3:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_4:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_5:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_6:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_7:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_8:0' shape=(12, 1) dtype=float32>], [<tf.Tensor 'while/Identity_9:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_10:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_11:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_12:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_13:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_14:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_15:0' shape=(12, 1) dtype=float32>], [[<tf.Tensor 'while/Identity_16:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_17:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_18:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_19:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_20:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_21:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_22:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_23:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_24:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_25:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_26:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_27:0' shape=(11, 10) dtype=float32>, <tf.Tensor 'while/Identity_28:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/Identity_29:0' shape=(11, 1) dtype=float32>], [<tf.Tensor 'while/Identity_30:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_31:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_32:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_33:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_34:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_35:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_36:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_37:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_38:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_39:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_40:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_41:0' shape=(3, 10) dtype=float32>, <tf.Tensor 'while/Identity_42:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/Identity_43:0' shape=(3, 1) dtype=float32>], [<tf.Tensor 'while/Identity_44:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_45:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_46:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_47:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_48:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_49:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_50:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_51:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_52:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_53:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_54:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_55:0' shape=(9, 10) dtype=float32>, <tf.Tensor 'while/Identity_56:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/Identity_57:0' shape=(9, 1) dtype=float32>], [<tf.Tensor 'while/Identity_58:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_59:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_60:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_61:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_62:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_63:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_64:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_65:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_66:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_67:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_68:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_69:0' shape=(7, 10) dtype=float32>, <tf.Tensor 'while/Identity_70:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/Identity_71:0' shape=(7, 1) dtype=float32>], [<tf.Tensor 'while/Identity_72:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_73:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_74:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_75:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_76:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_77:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_78:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_79:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_80:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_81:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_82:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_83:0' shape=(5, 10) dtype=float32>, <tf.Tensor 'while/Identity_84:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/Identity_85:0' shape=(5, 1) dtype=float32>], [<tf.Tensor 'while/Identity_86:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_87:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_88:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_89:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_90:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_91:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_92:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_93:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_94:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_95:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_96:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_97:0' shape=(13, 10) dtype=float32>, <tf.Tensor 'while/Identity_98:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/Identity_99:0' shape=(13, 1) dtype=float32>], [<tf.Tensor 'while/Identity_100:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_101:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_102:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_103:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_104:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_105:0' shape=(1, 20) dtype=float32>, <tf.Tensor 'while/Identity_106:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_107:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_108:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_109:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_110:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_111:0' shape=(12, 10) dtype=float32>, <tf.Tensor 'while/Identity_112:0' shape=(12, 1) dtype=float32>, <tf.Tensor 'while/Identity_113:0' shape=(12, 1) dtype=float32>]], [<tf.Tensor 'while/Identity_114:0' shape=(1, 20) dtype=float32>], <tf.Tensor 'while/Identity_115:0' shape=(?,) dtype=float32>, <tf.Tensor 'while/Identity_116:0' shape=() dtype=float32>, <tf.Tensor 'while/Identity_117:0' shape= dtype=float32>, <tf.Tensor 'while/Identity_118:0' shape= dtype=int32>, <tf.Tensor 'while/Identity_119:0' shape= dtype=int32>]

Second structure (23 elements):
[<tf.Tensor 'while/add_21:0' shape=() dtype=int32>, <tf.Tensor 'while/Add:0' shape=() dtype=float32>, [<tf.Tensor 'while/LOL/PerTensor/sub_15:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_1/sub_15:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_2/sub_15:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_3/sub_15:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_4/sub_15:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_5/sub_15:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_6/sub_15:0' shape=(12, 1) dtype=float32>], [<tf.Tensor 'while/LOL/PerTensor/sub_15:0' shape=(11, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_1/sub_15:0' shape=(3, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_2/sub_15:0' shape=(9, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_3/sub_15:0' shape=(7, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_4/sub_15:0' shape=(5, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_5/sub_15:0' shape=(13, 1) dtype=float32>, <tf.Tensor 'while/LOL/PerTensor_6/sub_15:0' shape=(12, 1) dtype=float32>], <map object at 0x7f0a9b8f4be0>, [<tf.Tensor 'while/LOL/Layer2_RNN/BiasGRUCell/add:0' shape=(1, 20) dtype=float32>], <tf.Tensor 'while/concat:0' shape=(?,) dtype=float32>, <tf.Tensor 'while/Identity_116:0' shape=() dtype=float32>, <tf.Tensor 'while/Identity_117:0' shape= dtype=float32>, <tf.Tensor 'while/Identity_118:0' shape= dtype=int32>, <tf.Tensor 'while/Identity_119:0' shape= dtype=int32>]

I tried following the solution as suggested here, but I am not able to figure as to where to make changes in the code. It would be a big help if anyone can guide a way!

Thanks in Advance :)


问:
Move Button to be in the same line with Checkbox and Textbox Bootstrap
I'm trying to move the button to be in the same line as the checkbox and textbox. Currently it displays the elements as shown below...

What I want is to have something shown below...

Also, the textbox beside the checkbox fills up the whole space in its line. How can I make it shorter?

```<code><div class="input-group">
    <span class="input-group-addon">
    <input type="checkbox"> Break After
    </span>
    <input type="text" class="form-control">
</div>

<button id="btnextra" type="button" class="btn btn-default btn-md">Extra</button>
</code>```

I have my jsfiddle here.

Thank you so much.

答:
You can just wrap the <button> in ,
update: I added a wrapper
 to contain the form elements also used .col-xs-8 class to control the size, I really suggest using the standard classes and provided by bootstrap, here is a working snippet:

.btnextra {
  margin-left: 10px;
}

.form-group-centered {
  width: 400px;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<br />
<div class="form-group row">
  <div class="col-xs-12">
    <div class="form-group-centered">
      <div class="input-group pull-left" style="
      width: 300px;
  ">
          <span class="input-group-addon"> <input type="checkbox"> Break After </span>
          <input type="text" class="form-control">

      </div>
      <button id="btnextra" type="button" class="btn btn-default btn-md btnextra pull-left" style="
  ">Extra</button>
    </div>
  </div>
</div></code>```

Body:
I'm trying to move the button to be in the same line as the checkbox and textbox. Currently it displays the elements as shown below...

What I want is to have something shown below...

Also, the textbox beside the checkbox fills up the whole space in its line. How can I make it shorter?

    <input type="checkbox"> Break After

    <input type="text" class="form-control">

<button id="btnextra" type="button" class="btn btn-default btn-md">Extra</button>

I have my jsfiddle here.

Thank you so much.

Body:
You can just wrap the <button> in <span class="input-group-btn">,
update: I added a wrapper <div class="form-group row"> to contain the form elements also used .col-xs-8 class to control the size, I really suggest using the standard classes and provided by bootstrap, here is a working snippet:

.btnextra {
  margin-left: 10px;
}

.form-group-centered {
  width: 400px;
  margin: 0 auto;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<br />
<div class="form-group row">
  <div class="col-xs-12">
    <div class="form-group-centered">
      <div class="input-group pull-left" style="
      width: 300px;
  ">
          <span class="input-group-addon"> <input type="checkbox"> Break After </span>
          <input type="text" class="form-control">

      </div>
      <button id="btnextra" type="button" class="btn btn-default btn-md btnextra pull-left" style="
  ">Extra</button>
    </div>
  </div>
</div>


问:
Communication without server
Thinking about collaborative applications like online gaming, whatsapp, and many other distributed systems, server plays a major role. It performs many critical functions which are needed for smooth functioning of the application as a whole.

But suppose I want to develop an application which users can use to connect online and share data, like text, images, drawings in real time. For example, one user may be working on a maths problem and want to discuss it with another user. So application enables those two users(and more, if needed) to connect and share their ideas.

Can users have this sort of communication without having a server as mediator? If yes,what networking technologies enable this? And what are the advantages application miss upon on lack of a mediating server?

答:
there are many problems you need to solve if you want to build such a distributed topology.

NAT must be think. It is the first thing that must solve, you may need to build Natpmp or upnp or ICE to realise nat traversal.

The second problem is how to find other users without a server. You may need to use LSD or DHT

You need to think about security of network without a certification such as the server which can store users infomation and make sure they are really unharmful.

If you solve all the prolems by using these technologies I mension above or some others, than you will find it's better to use a server cause it's relatively simple. That is the trade-off in a commercial production.

Title: Communication without server


问:
How to do "static overloaded const" in C#?
I'm creating a game in C#. Each level is made up of several tiles. Each tile is of a certain type e.g. grass floor, wooden wall, etc.

Ideally I would like to have one base class "Tile" and inherit from it to create classes for each type of tile. I would like to have the properties of the tile some kind of static/const/etc member of the sub-class since each type of tile is only ever going to have the same properties. I.e. I don't want 100 Tiles have a property which all have the same value, that seems rather inefficient.

The problem is you can't do that in C#. Are there any ways to achieve what I want?

My alternative idea was to separate it all into to trees, one with only the class "Tile" which represents an instance and another "TileType" from which I instanciate one object for each type and maybe access them through some kind of "TileTypeCollection". This feels strange though and I would rather do it in the first way.

Are there any general guidelines when dealing with a situation like this?

答:
You can create a class structure as follows:</p>

```<code>public abstract class Tile
{
  public abstract string BaseType;
}

public class Floor : Tile
{
  public override string BaseType
  {
    get
    {
       return "floor";
    }
  }
}

public class Grass : Tile
{
  public override string BaseType
  {
    get
    {
       return "grass";
    }
  }
}

public class Wooden : Tile
{
  public override string BaseType
  {
    get
    {
       return "wooden";
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can create a class structure as follows:

public abstract class Tile
{
  public abstract string BaseType;
}

public class Floor : Tile
{
  public override string BaseType
  {
    get
    {
       return "floor";
    }
  }
}

public class Grass : Tile
{
  public override string BaseType
  {
    get
    {
       return "grass";
    }
  }
}

public class Wooden : Tile
{
  public override string BaseType
  {
    get
    {
       return "wooden";
    }
  }
}


问:
Stripe Webhooks
I am having a similar problem with Stripe webhooks. Spent all weekend trying to diagnose without success. Getting a general 500 error when running test through stripe dashboard. If I just load the page directly, it generates a blank page or if I echo something like echo http_response_code(200);, I get 200 back. My code is pretty straightforward.

```<code>require('/stripe/init.php');

\Stripe\Stripe::setApiKey("[intentionally deleted for post]");

$payload = file_get_contents("php://input");

$event_json = json_decode($payload);

http_response_code(200);
</code>```

PHP runs fine on the site in all other contexts. There are no issues with implementing charges, both one time and subscriptions. Posts and Get work fine on all other pages. It's sharing hosting so have pretty limited access to error logs, etc...

I have already looked through the one or two stackoverflow responses to stripe webhook errors with through a 500 error but unfortunately these did not help.  Thanks in advance.

答:
I would try this kind of event creation:

```<code>$event = \Stripe\Webhook::constructEvent(
    $request->getContent(),
    $request->server->get('HTTP_STRIPE_SIGNATURE'),
    $this->getParameter('stripe_webhook_secret')
);
</code>```

This is Symfony code so $request is provided by Symfony but you can replace those with your native PHP variables. After this assignment, $event is populated with the data that you see in the Stripe docs examples.

Title: Stripe Webhooks

Body:
I am having a similar problem with Stripe webhooks. Spent all weekend trying to diagnose without success. Getting a general 500 error when running test through stripe dashboard. If I just load the page directly, it generates a blank page or if I echo something like echo http_response_code(200);, I get 200 back. My code is pretty straightforward.

require('/stripe/init.php');

\Stripe\Stripe::setApiKey("[intentionally deleted for post]");

$payload = file_get_contents("php://input");

$event_json = json_decode($payload);

http_response_code(200);

PHP runs fine on the site in all other contexts. There are no issues with implementing charges, both one time and subscriptions. Posts and Get work fine on all other pages. It's sharing hosting so have pretty limited access to error logs, etc...

I have already looked through the one or two stackoverflow responses to stripe webhook errors with through a 500 error but unfortunately these did not help.  Thanks in advance.

Body:
I would try this kind of event creation:

$event = \Stripe\Webhook::constructEvent(
    $request->getContent(),
    $request->server->get('HTTP_STRIPE_SIGNATURE'),
    $this->getParameter('stripe_webhook_secret')
);

This is Symfony code so $request is provided by Symfony but you can replace those with your native PHP variables. After this assignment, $event is populated with the data that you see in the Stripe docs examples.


问:
How can I have a fixed-width centered column with in a 3-column layout?
I want to get the red box to middle of the strip and need to be only 10 em wide. Left and Right contents should be as the image attached. That mean left contain should be align to left and right side content to right align.

My HTML:

```<code><div class="row">
  <div class="meta-left">
    <p>Left Contents with align left...</p>
  </div>
  <div class="logo-bg-top"></div>
  <div class="meta-right">
    <p>Right Contents with align right...</p>
  </div>
</div>
</code>```

This is how I tried in CSS:

```<code>.row {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

.row .logo-bg-top {
    flex: 0 0 9em;
    background: red;
}
</code>```

Can anybody guide me to fix this issue?

答:
As NiettheDarkAbsol said in the comments, it's better to do this with grid layout:

If you want to use grid, you can do this by adding display: grid; to your main container and then specify the items within it with grid-template-columns: 1fr 10em 1fr;.

fr indicates a fraction of document width, so since the layout is 1⁄3 (We have 3 different child elements) and the middle one is 10em, so each fr will represent (100% - 10em)⁄2 width of the document.

.row {
  display: grid;
  grid-template-columns: 1fr 10em 1fr;
}

.row [class*="meta"] {
  background: blue;
  color: white;
}

.row .meta-right {
  text-align: right;
}

.row .logo-bg-top {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="meta-left">
    <p>Left Contents with align left...</p>
  </div>
  <div class="logo-bg-top"></div>
  <div class="meta-right">
    <p>Right Contents with align right...</p>
  </div>
</div></code>```

But if you insist on using flexbox layout this could be an approach for doing such a thing:

.row {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: center;
}

.row [class*="meta"] {
  background: blue;
  color: white;
  flex: 1;
}

.row .meta-right {
  text-align: right;
}

.row .logo-bg-top {
  flex: 0 0 10em;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="meta-left">
    <p>Left Contents with align left...</p>
  </div>
  <div class="logo-bg-top"></div>
  <div class="meta-right">
    <p>Right Contents with align right...</p>
  </div>
</div></code>```

Body:
I want to get the red box to middle of the strip and need to be only 10 em wide. Left and Right contents should be as the image attached. That mean left contain should be align to left and right side content to right align.

My HTML:

Left Contents with align left...

Right Contents with align right...

This is how I tried in CSS:

.row {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

.row .logo-bg-top {
    flex: 0 0 9em;
    background: red;
}

Can anybody guide me to fix this issue?

Body:
As NiettheDarkAbsol said in the comments, it's better to do this with grid layout:

If you want to use grid, you can do this by adding display: grid; to your main container and then specify the items within it with grid-template-columns: 1fr 10em 1fr;.

fr indicates a fraction of document width, so since the layout is 1⁄3 (We have 3 different child elements) and the middle one is 10em, so each fr will represent (100% - 10em)⁄2 width of the document.

.row {
  display: grid;
  grid-template-columns: 1fr 10em 1fr;
}

.row [class*="meta"] {
  background: blue;
  color: white;
}

.row .meta-right {
  text-align: right;
}

.row .logo-bg-top {
  background: red;
}

<div class="row">
  <div class="meta-left">
    <p>Left Contents with align left...</p>
  </div>
  <div class="logo-bg-top"></div>
  <div class="meta-right">
    <p>Right Contents with align right...</p>
  </div>
</div>

But if you insist on using flexbox layout this could be an approach for doing such a thing:

.row {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: center;
}

.row [class*="meta"] {
  background: blue;
  color: white;
  flex: 1;
}

.row .meta-right {
  text-align: right;
}

.row .logo-bg-top {
  flex: 0 0 10em;
  background: red;
}

<div class="row">
  <div class="meta-left">
    <p>Left Contents with align left...</p>
  </div>
  <div class="logo-bg-top"></div>
  <div class="meta-right">
    <p>Right Contents with align right...</p>
  </div>
</div>


问:
how to make a video from extracted frames?
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

```<code>import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()
</code>```

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

答:
Try glob for listing files and sort the list. I have edited your code using glob. (Assuming your filenames of images are in the sequence you want)

```<code>import cv2
import os
import glob

video_name = 'video.avi'

images = glob.glob('images/*.jpg')
images.sort()

frame = cv2.imread(images[0])
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(image))

cv2.destroyAllWindows()
video.release()
</code>```

Body:
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

Body:
Try glob for listing files and sort the list. I have edited your code using glob. (Assuming your filenames of images are in the sequence you want)

import cv2
import os
import glob

video_name = 'video.avi'

images = glob.glob('images/*.jpg')
images.sort()

frame = cv2.imread(images[0])
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(image))

cv2.destroyAllWindows()
video.release()


问:
Is it still possible to do ContentOverride in Winforms ViewModels?
Previously it was possible to use ContentOverride in Winforms ViewModels.

Is this still possible in MDriven 7.0.0.11262?

答:
I am not aware of any changes so it should work as before. The ContentOverride signal the render-logic (Eco.ViewModel.WinForms.ViewModelUserControl) to call the OnColumnUIOverride event with the following argument:</p>

```<code>  /// <summary>
  /// Arguments for the OnColumnUIOverrideArgs event; fired to allow for override of column render.
  /// If you have other UI components that you want to use in ViewModel driven UI's this event provides
  /// a hook point to inject them.
  /// </summary>
  public class OnColumnUIOverrideArgs : EventArgs
  {
    public ViewModel ViewModel;
    /// <summary>
    /// The Column in question
    /// </summary>
    public ViewModelColumn ViewModelColumn;
    /// <summary>
    /// What kind of UI we had in mind
    /// </summary>
    public ViewModelUIComponentType ViewModelUIComponentType;
    /// <summary>
    /// Set this to false to stop us from calling default logic
    /// </summary>
    public bool ContinueWithDefault;
  }
</code>```

Body:
I am not aware of any changes so it should work as before. The ContentOverride signal the render-logic (Eco.ViewModel.WinForms.ViewModelUserControl) to call the OnColumnUIOverride event with the following argument:

  /// <summary>
  /// Arguments for the OnColumnUIOverrideArgs event; fired to allow for override of column render.
  /// If you have other UI components that you want to use in ViewModel driven UI's this event provides
  /// a hook point to inject them.
  /// </summary>
  public class OnColumnUIOverrideArgs : EventArgs
  {
    public ViewModel ViewModel;
    /// <summary>
    /// The Column in question
    /// </summary>
    public ViewModelColumn ViewModelColumn;
    /// <summary>
    /// What kind of UI we had in mind
    /// </summary>
    public ViewModelUIComponentType ViewModelUIComponentType;
    /// <summary>
    /// Set this to false to stop us from calling default logic
    /// </summary>
    public bool ContinueWithDefault;
  }


问:
Cassandra/Java mismatched character Exception when creating table with MD5 as name
I'm setting up a Cassandra database and try to create tables with an MD5 hash code as table name.
When I do this, I get an com.datastax.oss.driver.api.core.servererrors.SyntaxError: line 1:35 mismatched character '2' expecting '-' exception.

My Query:

```<code>CREATE TABLE IF NOT EXISTS 77f2d6b127b7d4a89a940d0829ff1e672afb4362_status (
    jsonSchema TEXT,
    onlineStatus INT,
    key text,
    timestamp timeuuid,
    primary key(key, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)
  AND compaction = {'class': 'TimeWindowCompactionStrategy',
                    'compaction_window_size': 1,
                    'compaction_window_unit': 'DAYS'};
</code>```

And the exception:

```<code>Caused by: com.datastax.oss.driver.api.core.servererrors.SyntaxError: line 1:35 mismatched character '2' expecting '-'
    at com.datastax.oss.driver.api.core.servererrors.SyntaxError.copy(SyntaxError.java:48)
    at com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures.getUninterruptibly(CompletableFutures.java:113)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:53)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:30)
    at com.datastax.oss.driver.internal.core.session.DefaultSession.execute(DefaultSession.java:207)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:47)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:56)
</code>```

I wonder why this happens. According to https://docs.datastax.com/en/archived/cql/3.3/cql/cql_reference/ref-lexical-valid-chars.html the query should have a correct syntax.

What I have tried

Double quotation marks

It works when I put the table name in double quotation marks (CREATE TABLE IF NOT EXISTS "77f2d6b127b7d4a89a940d0829ff1e672afb4362_status" (... but then I get problems with my IntelliJ database IDE because it does not query the database using double quotation marks for the table names.

Start table name with a letter ([a-z])

When I add in front of the table name manually a letter (not a number; e.g. a77f2d6b127b7d4a89a940d0829ff1e672afb4362_status), the table is created but I get another timeout exception:

```<code>com.datastax.oss.driver.api.core.DriverTimeoutException: Query timed out after PT2S
    at com.datastax.oss.driver.api.core.DriverTimeoutException.copy(DriverTimeoutException.java:34)
    at com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures.getUninterruptibly(CompletableFutures.java:113)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:53)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:30)
    at com.datastax.oss.driver.internal.core.session.DefaultSession.execute(DefaultSession.java:207)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:47)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:56)
</code>```

After the timeout exception I can execute the same query again. This time without errors -> table was successfully created.

I use following Java driver: [Maven: com.datastax.oss:java-driver-core:4.0.1]

Any help is more than welcome.

答:
In the CQL grammar, the rule for table names is called cfName. As you can see a table name can be either a non-quoted identifier (IDENT), a quoted name (QUOTED_NAME) or unreserved keywords. The rule for IDENT is defined here. As you can see, it needs to start with a letter. To create a table named like yours, you need to double quote it (I tried with CQLSH, and it worked – sorry if IntelliJ cannot understand that).

The driver timeout for CQL queries is by default 2 seconds. This is usually not enough for DDL queries. You can raise the timeout for an individual query like this:

```
     session.execute(
        SimpleStatement.newInstance(
            "CREATE TABLE IF NOT EXISTS ...")
        .setTimeout(Duration.ofSeconds(30)));
```

Body:
I'm setting up a Cassandra database and try to create tables with an MD5 hash code as table name.
When I do this, I get an com.datastax.oss.driver.api.core.servererrors.SyntaxError: line 1:35 mismatched character '2' expecting '-' exception.

My Query:

CREATE TABLE IF NOT EXISTS 77f2d6b127b7d4a89a940d0829ff1e672afb4362_status (
    jsonSchema TEXT,
    onlineStatus INT,
    key text,
    timestamp timeuuid,
    primary key(key, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)
  AND compaction = {'class': 'TimeWindowCompactionStrategy',
                    'compaction_window_size': 1,
                    'compaction_window_unit': 'DAYS'};

And the exception:

Caused by: com.datastax.oss.driver.api.core.servererrors.SyntaxError: line 1:35 mismatched character '2' expecting '-'
    at com.datastax.oss.driver.api.core.servererrors.SyntaxError.copy(SyntaxError.java:48)
    at com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures.getUninterruptibly(CompletableFutures.java:113)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:53)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:30)
    at com.datastax.oss.driver.internal.core.session.DefaultSession.execute(DefaultSession.java:207)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:47)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:56)

I wonder why this happens. According to https://docs.datastax.com/en/archived/cql/3.3/cql/cql_reference/ref-lexical-valid-chars.html the query should have a correct syntax.

What I have tried

Double quotation marks

It works when I put the table name in double quotation marks (CREATE TABLE IF NOT EXISTS "77f2d6b127b7d4a89a940d0829ff1e672afb4362_status" (... but then I get problems with my IntelliJ database IDE because it does not query the database using double quotation marks for the table names.

Start table name with a letter ([a-z])

When I add in front of the table name manually a letter (not a number; e.g. a77f2d6b127b7d4a89a940d0829ff1e672afb4362_status), the table is created but I get another timeout exception:

com.datastax.oss.driver.api.core.DriverTimeoutException: Query timed out after PT2S
    at com.datastax.oss.driver.api.core.DriverTimeoutException.copy(DriverTimeoutException.java:34)
    at com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures.getUninterruptibly(CompletableFutures.java:113)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:53)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:30)
    at com.datastax.oss.driver.internal.core.session.DefaultSession.execute(DefaultSession.java:207)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:47)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:56)

After the timeout exception I can execute the same query again. This time without errors -> table was successfully created.

I use following Java driver: [Maven: com.datastax.oss:java-driver-core:4.0.1]

Any help is more than welcome.

Body:
In the CQL grammar, the rule for table names is called cfName. As you can see a table name can be either a non-quoted identifier (IDENT), a quoted name (QUOTED_NAME) or unreserved keywords. The rule for IDENT is defined here. As you can see, it needs to start with a letter. To create a table named like yours, you need to double quote it (I tried with CQLSH, and it worked – sorry if IntelliJ cannot understand that).

The driver timeout for CQL queries is by default 2 seconds. This is usually not enough for DDL queries. You can raise the timeout for an individual query like this:

     session.execute(
        SimpleStatement.newInstance(
            "CREATE TABLE IF NOT EXISTS ...")
        .setTimeout(Duration.ofSeconds(30)));


问:
Getting image on UIImageView
I'm currently making an app where the user takes a photo or select it from an album, then an overlay is placed over the image. The user can then scale, rotate and save the image.

For now, I have 2 xib files. The first one has thumbnails for overlay pictures to choose from.  Clicking on one of them goes to another xib file where I have 2 UIImageViews. One for the overlay and one for the camera. Previously I just used interface builder to set an image at the attributes. But if have 20 overlays, it means I have to use 20 xibs. So I thought the best way is to add pictures through code so I can use this 2nd xib as a template for the overlays. Here's when I'm stuck. When I click on a thumbnail in the 1st xib file, how do tell the 2nd xib file to store an overlay in the UIImageView?

For the camera, I'm using

```<code>imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
</code>```

and it works fine. I can even save it to the album. I thought I could use the code below for the overlays but that didn't work.

```<code>UIImage *image = [UIImage imageNamed: @"char1.png"];
</code>```

Hope someone can help. Thanks very much.

Hakimo

答:
You don't need to use xib at all in this situation. Create UIImageView by hands, set its frame and image, add it as a subview to your viewControllers.view . You can have as many UIImageViews as you need. Make an array of them. Your case is obviously misuse of xibs concept. Xibs are usually used when there is need to create some complicated view with many subviews that wouldn't be used in code, like labels, decoration images etc.</p>

```<code>CGRect frameForImage = CGRectMake(100, 100, 200, 300);
UIImageView *originalImage = [[UIImageView alloc] initWithFrame:frameForImage];
originalImage.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[self.view addSubview:originalImage];
[originalImage release];

frameForImage.origin.x += 400;
UIImageView *resizedImage = [[UIImageView alloc] initWithFrame:frameForImage];
resizedImage.image = [info objectForKey:@"UIImagePickerControllerWhateverImage"];
[self.view addSubview:resizedImage];
[resizedImage release];
</code>```

Title: Getting image on UIImageView

Body:
I'm currently making an app where the user takes a photo or select it from an album, then an overlay is placed over the image. The user can then scale, rotate and save the image.

For now, I have 2 xib files. The first one has thumbnails for overlay pictures to choose from.  Clicking on one of them goes to another xib file where I have 2 UIImageViews. One for the overlay and one for the camera. Previously I just used interface builder to set an image at the attributes. But if have 20 overlays, it means I have to use 20 xibs. So I thought the best way is to add pictures through code so I can use this 2nd xib as a template for the overlays. Here's when I'm stuck. When I click on a thumbnail in the 1st xib file, how do tell the 2nd xib file to store an overlay in the UIImageView?

For the camera, I'm using

imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

and it works fine. I can even save it to the album. I thought I could use the code below for the overlays but that didn't work.

UIImage *image = [UIImage imageNamed: @"char1.png"];

Hope someone can help. Thanks very much.

Hakimo

Body:
You don't need to use xib at all in this situation. Create UIImageView by hands, set its frame and image, add it as a subview to your viewControllers.view . You can have as many UIImageViews as you need. Make an array of them. Your case is obviously misuse of xibs concept. Xibs are usually used when there is need to create some complicated view with many subviews that wouldn't be used in code, like labels, decoration images etc.

CGRect frameForImage = CGRectMake(100, 100, 200, 300);
UIImageView *originalImage = [[UIImageView alloc] initWithFrame:frameForImage];
originalImage.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[self.view addSubview:originalImage];
[originalImage release];

frameForImage.origin.x += 400;
UIImageView *resizedImage = [[UIImageView alloc] initWithFrame:frameForImage];
resizedImage.image = [info objectForKey:@"UIImagePickerControllerWhateverImage"];
[self.view addSubview:resizedImage];
[resizedImage release];


问:
Scala test match case classes on some field
I have

```<code>case class Foo(field1: String, field2: String, field3: String)

expected: Seq[Foo] = Seq(...)

result: Seq[Foo] = Seq(...)
</code>```

I want to write a Scala matcher that compare the elements of Seq without taking in consideration field1.

So two elements will match if field2 and field3 are equals. Field1 value is not considerated.

Example:

```<code>val expected = Seq(
  Foo(
    "f1", "f2", "f3"
  )
)

val result = Seq(
  Foo(
    "fx", "f2", "f3"
  )
)
</code>```

This two sequence has to match.

```<code>  result should matchWithoutId(expected)
</code>```

答:
The documentation is in Using custom Matchers, this example would be (for example)

```<code>def matchWithoutId(expected: Foo): Matcher[Foo] = Matcher { actual =>
  MatchResult(
    actual.field2 == expected.field2 && actual.field3 == expected.field3,
    if (actual.field2 != expected.field2)
      s"field2 of $actual was not equal to that of $expected"
    else
      s"field3 of $actual was not equal to that of $expected",
    s"field2 and field3 of $actual were equal to those of $expected")
}
</code>```

Adjust error messages to taste.

Or another approach (probably a better one in this case):

```<code>def matchWithoutId(expected: Foo): Matcher[Foo] = have(
  'field2 (expected.field2),
  'field3 (expected.field3)
)
</code>```

Normally I'd say using Symbols to name properties and use reflection should be avoided, but here a change to Foo will make the tests fail to compile anyway because of access to expected's fields.

EDIT: I missed that you want to compare Seq[Foo]s and not Foos, so Mario Galic's answer is probably the one you want. Still, this can hopefully be useful as well.

Body:
I have

case class Foo(field1: String, field2: String, field3: String)

expected: Seq[Foo] = Seq(...)

result: Seq[Foo] = Seq(...)

I want to write a Scala matcher that compare the elements of Seq without taking in consideration field1.

So two elements will match if field2 and field3 are equals. Field1 value is not considerated.

Example:

val expected = Seq(
  Foo(
    "f1", "f2", "f3"
  )
)

val result = Seq(
  Foo(
    "fx", "f2", "f3"
  )
)

This two sequence has to match.

  result should matchWithoutId(expected)

Body:
The documentation is in Using custom Matchers, this example would be (for example)

def matchWithoutId(expected: Foo): Matcher[Foo] = Matcher { actual =>
  MatchResult(
    actual.field2 == expected.field2 && actual.field3 == expected.field3,
    if (actual.field2 != expected.field2)
      s"field2 of $actual was not equal to that of $expected"
    else
      s"field3 of $actual was not equal to that of $expected",
    s"field2 and field3 of $actual were equal to those of $expected")
}

Adjust error messages to taste.

Or another approach (probably a better one in this case):

def matchWithoutId(expected: Foo): Matcher[Foo] = have(
  'field2 (expected.field2),
  'field3 (expected.field3)
)

Normally I'd say using Symbols to name properties and use reflection should be avoided, but here a change to Foo will make the tests fail to compile anyway because of access to expected's fields.

EDIT: I missed that you want to compare Seq[Foo]s and not Foos, so Mario Galic's answer is probably the one you want. Still, this can hopefully be useful as well.


问:
Set class if if filled or empty
Im building my own custom selecter and i need to set a class if something is selected or not. Why is this not working?

Im new to react, so bear with me. I also need to type some more before i can post my question although im not sure how to elaborate this question further since its probably clear to some what im doing wrong.

EDIT: I have changed the props to state, but it is still not working. When i select from the dropdown, i doesn't select the option i choose and also the correct classes aren't set. eg. empty, not-empty, so i think somethings is not correct in the logic?

```<code>import React, { Component } from 'react'

const optionsData = [
    'Select',
    'Option1',
    'Option2',
    'Option3'
]

class CustomSelect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            placeholder:'',
            id:'',
            onChange:'',
            label:'',
            value:'',
            validationMsg:'',
            disabled:''
        };
    }
    onFocus = () => {
        this.setState({
            onFocus: true
        });
    }
    // Fix so when you dont make a choice it still lose focus
    onBlur = () => {
        this.setState({
            onFocus: false
        });
    }
    onChange = () => {
        this.setState({
            onFocus: false
        });
    }

    getClass = () => {
        if (this.state.onFocus === true)
            return "in-focus"
        else if (!this.state.value === '' | !this.state.value === 'Select')
            return "not-empty"
        else if (this.state.value === '')
            return "empty"
        else
            return "";
    }

    render() {
        let inputFocus = this.getClass();
        return (
            <div className={`form-item ${inputFocus}`}>
                {this.props.label &&
                    <label htmlFor={this.props.id}>
                        {this.props.label}
                    </label>
                }
                <select
                    id={this.state.id}
                    placeholder={this.state.placeholder}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    onChange={this.onChange}
                    disabled={this.state.disabled}
                    value={this.state.value ? this.props.value : ''}
                >
                    {optionsData.map(option =>
                        <option
                            key={option}
                            value={option}
                        >
                            {option}
                        </option>
                    )}
                </select>
                {/* {this.props.validationMsg && <span className="validation-message">{this.props.validationMsg}</span>} */}
            </div>
        )
    }
}

export default CustomSelect
</code>```

答:
You need to change

this.props.label to this.state.label

this.props.placeholder to this.props.placeholder

this.props.id to this.state.id

and similarly for each of those items. Your code should work then.
You might like to go through these:

State in React

Props in react

Also, change the name of setClass to getClass. That conveys its usage in a better way.

UPDATE: Now since you're done with the changes, the reason your drop down is not working is because in your handleChange you're not setting the state value which you're using in select.

```<code>  onChange = (e) => {
        this.setState({
            onFocus: true, <--- you might like to set this true
            value: e.target.value <----- you'll have to do this
        });
    }
</code>```

See this: See the select section in this

Similarly, for other issues you have to set the state accordingly.
Also, there were still some props needed to be changed to state

Here's a working code after these fixes:
https://codesandbox.io/s/cranky-leaf-4h5dp?file=/src/CustomSelect.js

```<code>    import React, { Component } from 'react'

const optionsData = [
    'Select',
    'Option1',
    'Option2',
    'Option3'
]

class CustomSelect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            placeholder:'',
            id:'',
            onChange:'',
            label:'',
            value:'',
            validationMsg:'',
            disabled:''
        };
    }
    onFocus = () => {
        this.setState({
            onFocus: true
        });
    }
    // Fix so when you dont make a choice it still lose focus
    onBlur = () => {
        this.setState({
            onFocus: false
        });
    }
    onChange = (e) => {
        this.setState({
            onFocus: true,
            value: e.target.value
        });
    }

    getClass = () => {
        if (this.state.onFocus === true)
            return "in-focus"
        else if (!this.state.value === '' | !this.state.value === 'Select')
            return "not-empty"
        else if (this.state.value === '')
            return "empty"
        else
            return "";
    }

    render() {
        let inputFocus = this.getClass();
        return (
            <div className={`form-item ${inputFocus}`}>
                {this.state.label &&
                    <label htmlFor={this.state.id}>
                        {this.state.label}
                    </label>
                }
                <select
                    id={this.state.id}
                    placeholder={this.state.placeholder}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    onChange={this.onChange}
                    disabled={this.state.disabled}
                    value={this.state.value ? this.state.value : ''}
                >
                    {optionsData.map(option =>
                        <option
                            key={option}
                            value={option}
                        >
                            {option}
                        </option>
                    )}
                </select>
                {/* {this.props.validationMsg && <span className="validation-message">{this.props.validationMsg}</span>} */}
            </div>
        )
    }
}

export default CustomSelect
</code>```

Title: Set class if if filled or empty

Body:
Im building my own custom selecter and i need to set a class if something is selected or not. Why is this not working?

Im new to react, so bear with me. I also need to type some more before i can post my question although im not sure how to elaborate this question further since its probably clear to some what im doing wrong.

EDIT: I have changed the props to state, but it is still not working. When i select from the dropdown, i doesn't select the option i choose and also the correct classes aren't set. eg. empty, not-empty, so i think somethings is not correct in the logic?

import React, { Component } from 'react'

const optionsData = [
    'Select',
    'Option1',
    'Option2',
    'Option3'
]

class CustomSelect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            placeholder:'',
            id:'',
            onChange:'',
            label:'',
            value:'',
            validationMsg:'',
            disabled:''
        };
    }
    onFocus = () => {
        this.setState({
            onFocus: true
        });
    }
    // Fix so when you dont make a choice it still lose focus
    onBlur = () => {
        this.setState({
            onFocus: false
        });
    }
    onChange = () => {
        this.setState({
            onFocus: false
        });
    }

    getClass = () => {
        if (this.state.onFocus === true)
            return "in-focus"
        else if (!this.state.value === '' | !this.state.value === 'Select')
            return "not-empty"
        else if (this.state.value === '')
            return "empty"
        else
            return "";
    }

    render() {
        let inputFocus = this.getClass();
        return (
            <div className={`form-item ${inputFocus}`}>
                {this.props.label &&

                        {this.props.label}

                }
                <select
                    id={this.state.id}
                    placeholder={this.state.placeholder}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    onChange={this.onChange}
                    disabled={this.state.disabled}
                    value={this.state.value ? this.props.value : ''}
                >
                    {optionsData.map(option =>
                        <option
                            key={option}
                            value={option}
                        >
                            {option}
                        </option>
                    )}
                </select>
                {/* {this.props.validationMsg && {this.props.validationMsg}} */}

        )
    }
}

export default CustomSelect

Body:
You need to change

this.props.label to this.state.label

this.props.placeholder to this.props.placeholder

this.props.id to this.state.id

and similarly for each of those items. Your code should work then.
You might like to go through these:

State in React

Props in react

Also, change the name of setClass to getClass. That conveys its usage in a better way.

UPDATE: Now since you're done with the changes, the reason your drop down is not working is because in your handleChange you're not setting the state value which you're using in select.

  onChange = (e) => {
        this.setState({
            onFocus: true, <--- you might like to set this true
            value: e.target.value <----- you'll have to do this
        });
    }

See this: See the select section in this

Similarly, for other issues you have to set the state accordingly.
Also, there were still some props needed to be changed to state

Here's a working code after these fixes:
https://codesandbox.io/s/cranky-leaf-4h5dp?file=/src/CustomSelect.js

    import React, { Component } from 'react'

const optionsData = [
    'Select',
    'Option1',
    'Option2',
    'Option3'
]

class CustomSelect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            placeholder:'',
            id:'',
            onChange:'',
            label:'',
            value:'',
            validationMsg:'',
            disabled:''
        };
    }
    onFocus = () => {
        this.setState({
            onFocus: true
        });
    }
    // Fix so when you dont make a choice it still lose focus
    onBlur = () => {
        this.setState({
            onFocus: false
        });
    }
    onChange = (e) => {
        this.setState({
            onFocus: true,
            value: e.target.value
        });
    }

    getClass = () => {
        if (this.state.onFocus === true)
            return "in-focus"
        else if (!this.state.value === '' | !this.state.value === 'Select')
            return "not-empty"
        else if (this.state.value === '')
            return "empty"
        else
            return "";
    }

    render() {
        let inputFocus = this.getClass();
        return (
            <div className={`form-item ${inputFocus}`}>
                {this.state.label &&
                    <label htmlFor={this.state.id}>
                        {this.state.label}
                    </label>
                }
                <select
                    id={this.state.id}
                    placeholder={this.state.placeholder}
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    onChange={this.onChange}
                    disabled={this.state.disabled}
                    value={this.state.value ? this.state.value : ''}
                >
                    {optionsData.map(option =>
                        <option
                            key={option}
                            value={option}
                        >
                            {option}
                        </option>
                    )}
                </select>
                {/* {this.props.validationMsg && <span className="validation-message">{this.props.validationMsg}</span>} */}
            </div>
        )
    }
}

export default CustomSelect


问:
How to pass a C Struct to Rust?
I've found https://rust-embedded.github.io/book/interoperability/c-with-rust.html which teaches how to pass a C Struct to Rust. However, it uses the cty crate, which have to be generated by some kind of script.

I want to do things more easily as there is very few things I need to pass. Just some strings (char*) and numbers.

I already sucessfully passed a single uint8_t from C to Rust.

I'm now trying this on the Rust side:

```<code>#[repr(C)]
pub struct VPNParameters {
    pub address: *mut c_char,
    pub address_size: usize,
    pub x: c_int,
}

#[no_mangle]
pub extern "C" fn passParameters(vpnParameters: *mut VPNParameters)
{
    //error: says "vpnParameters" has no address field
    println!("{}", vpnParameters.address);
}
</code>```

and on C++:

```<code>struct VPNParameters {
    char* address;
    size_t address_size;
    int x;
} VPNParameters;

extern "C" void passParameters(VPNParameters* vPNParameters);
</code>```

I think it's something like that. But why I can't access the struct members on Rust? And possibly it won't work either, I may need to convert the char to a string.

I guess this would work:

```<code>println!("{}", unsafe { *vPNParameters.address(i as isize) });
</code>```

答:
The pointer itself does not have an address field. To "arrive" at the struct that is pointed to, you need to dereference the pointer.

#[repr(C)]
pub struct VPNParameters {
    pub address: *mut libc::c_char,
    pub address_size: usize,
    pub x: libc::c_int,
}

#[no_mangle]
pub extern "C" fn passParameters(vpnParameters: *mut VPNParameters)
{
    // Note the asterisk operator
    println!("{:?}", unsafe { (*vpnParameters).address });
}
```

Title: How to pass a C Struct to Rust?

Body:
I've found https://rust-embedded.github.io/book/interoperability/c-with-rust.html which teaches how to pass a C Struct to Rust. However, it uses the cty crate, which have to be generated by some kind of script.

I want to do things more easily as there is very few things I need to pass. Just some strings (char*) and numbers.

I already sucessfully passed a single uint8_t from C to Rust.

I'm now trying this on the Rust side:

#[repr(C)]
pub struct VPNParameters {
    pub address: *mut c_char,
    pub address_size: usize,
    pub x: c_int,
}

#[no_mangle]
pub extern "C" fn passParameters(vpnParameters: *mut VPNParameters)
{
    //error: says "vpnParameters" has no address field
    println!("{}", vpnParameters.address);
}

and on C++:

struct VPNParameters {
    char* address;
    size_t address_size;
    int x;
} VPNParameters;

extern "C" void passParameters(VPNParameters* vPNParameters);

I think it's something like that. But why I can't access the struct members on Rust? And possibly it won't work either, I may need to convert the char to a string.

I guess this would work:

println!("{}", unsafe { *vPNParameters.address(i as isize) });


问:
Embedding XCFramework in application with project framework dependencies
I have an Xcode workspace which features a project with an iOS Application target, and another project with a Framework target. The framework target is dependent on another framework, which is integrated in the form of an xcframework:

MyApp

MyFramework

OtherFramework

Using regular OtherFramework.framework would require it to be linked to MyFramework and then embedded in MyApp even though MyApp doesn't require the framework itself. However when integrating with xcframework, this project then fails to build with a No such module 'OtherFramework' error.

Project settings:

MyFramework Project

MyApp Project

Removing OtherFramework.xcframework from the MyApp target fixes the build issue, but then causes library not loaded errors as the framework is not present in the application.

Demo project here: https://github.com/msaps/XCFramework-Link-Issue

How are you meant to link an xcframework in an application and link in a dependent framework?

Why?

pyckamil just posted this article which explains the issue in detail: Everything wrong with XCFrameworks.

It turns out Xcode has an optimisation for the ProcessXCFrameworkLibrary step which extracts the correct .framework from an .xcframework for the active build architecture. This is only run once which causes issues for additional targets that try to link the same framework.

Update

This issue is resolved in Xcode 12.0

答:
UPDATED - Resolved in Xcode 12.0

shinsuk came up with a reliable workaround that works by adding architecture-explicit framework search paths to ensure the correct .framework within an XCFramework is found.

Details can be found in the README.


问:
NSIS concatenating part of two strings
I am trying to sort of merge two strings together in NSIS. I have two strings
2.1.3.0 and 0.0.0.27269 and the string I want to create from them is 2.1.3.27269

My attempts thus far haven't worked, here is what I tried:

```<code>;;$VERSION      is defined with 2.1.3.0
;;$FILEVERSION2 is defined with 0.0.0.27269

;;debug
DetailPrint ${VERSION}
DetailPrint ${FILEVERSION}

;;attempt, also it doesn't say what the variables $R0-$R2 are after values
;;copied into them, is that normal?
StrCpy $R0 ${FILEVERSION2} 5 -5
StrCpy $R1 ${VERSION} -2
StrCpy $R2 $R1"."$R0

DetailPrint $R2 ;;this doesn't print a value, only prints "$R2"
!define FILEVERSION3 $R2
</code>```

Any help would be great.
Hunter

also posted here: http://forums.winamp.com/showthread.php?p=2777308#post2777308

答:
To concatenate variables in NSIS you need to wrap them in quote marks.

```<code>;;$VERSION      is defined with 2.1.3.0
;;$FILEVERSION2 is defined with 0.0.0.27269

;;debug
DetailPrint ${VERSION}
DetailPrint ${FILEVERSION}

StrCpy $R0 ${FILEVERSION2} 5 -5
StrCpy $R1 ${VERSION} -2

; This concatenates the strings together with a dot
StrCpy $R2 "$R1.$R0"

DetailPrint $R2
!define FILEVERSION3 $R2
</code>```

It also might pay to have a look through the NSIS string functions list. Some of the functions such as the ones to get the first and last parts of strings could make your code more robust than splitting strings using hardcoded indexes.

Title: NSIS concatenating part of two strings

Body:
I am trying to sort of merge two strings together in NSIS. I have two strings
2.1.3.0 and 0.0.0.27269 and the string I want to create from them is 2.1.3.27269

My attempts thus far haven't worked, here is what I tried:

;;$VERSION      is defined with 2.1.3.0
;;$FILEVERSION2 is defined with 0.0.0.27269

;;debug
DetailPrint ${VERSION}
DetailPrint ${FILEVERSION}

;;attempt, also it doesn't say what the variables $R0-$R2 are after values
;;copied into them, is that normal?
StrCpy $R0 ${FILEVERSION2} 5 -5
StrCpy $R1 ${VERSION} -2
StrCpy $R2 $R1"."$R0

DetailPrint $R2 ;;this doesn't print a value, only prints "$R2"
!define FILEVERSION3 $R2

Any help would be great.
Hunter

also posted here: http://forums.winamp.com/showthread.php?p=2777308#post2777308

Body:
To concatenate variables in NSIS you need to wrap them in quote marks.

;;$VERSION      is defined with 2.1.3.0
;;$FILEVERSION2 is defined with 0.0.0.27269

;;debug
DetailPrint ${VERSION}
DetailPrint ${FILEVERSION}

StrCpy $R0 ${FILEVERSION2} 5 -5
StrCpy $R1 ${VERSION} -2

; This concatenates the strings together with a dot
StrCpy $R2 "$R1.$R0"

DetailPrint $R2
!define FILEVERSION3 $R2

It also might pay to have a look through the NSIS string functions list. Some of the functions such as the ones to get the first and last parts of strings could make your code more robust than splitting strings using hardcoded indexes.


答:
If you don't use button how suggest from @ROOT you can do that:

.input-group {
  width: 50%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="input-group">
  <span class="input-group-addon">
                <input type="checkbox"> Break After
                </span>
  <input type="text" class="form-control">
</div>

<button id="btnextra" type="button" class="btn btn-default btn-md">Extra</button></code>```

add css class for input-group

Title: Move Button to be in the same line with Checkbox and Textbox Bootstrap

Body:
I'm trying to move the button to be in the same line as the checkbox and textbox. Currently it displays the elements as shown below...

What I want is to have something shown below...

Also, the textbox beside the checkbox fills up the whole space in its line. How can I make it shorter?

    <input type="checkbox"> Break After

    <input type="text" class="form-control">

<button id="btnextra" type="button" class="btn btn-default btn-md">Extra</button>

I have my jsfiddle here.

Thank you so much.

Body:
If you don't use button how suggest from @ROOT you can do that:

.input-group {
  width: 50%;
  float: left;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="input-group">
  <span class="input-group-addon">
                <input type="checkbox"> Break After
                </span>
  <input type="text" class="form-control">
</div>

<button id="btnextra" type="button" class="btn btn-default btn-md">Extra</button>

add css class for input-group


问:
How to delete all the boxes in Hive Flutter?
I am developing an application using Flutter; it will store some data locally, so I decided to use Hive package which was really amazing package to store data. So now I will store all the data locally when the user press the sync button. After that, if the user clicks sync again, I have to delete all the boxes and store data which may or may not have the same box name.

I don't want to increase the application storage to increase if the sync button is clicked, I want to delete all the boxes and again I want to create the box.

答:
You can use deleteFromDisk method. It removes the file which contains the box and closes the box.</p>

```<code>_myCourseBox.deleteFromDisk();
</code>```

Body:
You can use deleteFromDisk method. It removes the file which contains the box and closes the box.

_myCourseBox.deleteFromDisk();


问:
Export CSV via Maatwebsite , Laravel
I try to export a csv file with some data, but with my current code I get response 200, and some strange characters, and no download, not sure why.

Source URL  here.

Exports/DataExport.php

```<code>namespace App\Exports;
use App\ViewData;
use Maatwebsite\Excel\Concerns\FromCollection;
use Excel;

class DataExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return ViewData::all();
    }
}
</code>```

Controller

```<code>use App\ViewData;
use App\Exports\DataExport;

use Maatwebsite\Excel\Facades\Excel;
    .....
    //  Export CSV data
    public function export()
    {
        return Excel::download(new DataExport, 'data.xlsx');
    }
</code>```

I added in config/app.php file, service provider and aliase.

答:
You are downloading the csv file from a frontend framework, so ofcourse it will gives you some strange characters instead of downloading a whole file, let me gives you a short code for that

```<code>downloadCSV() {
let newWindow = window.open();
axios.get('/json/persons/export')
   .then(response => {
     newWindow.location = 'http://' + window.location.hostname + '/json/persons/export';
   });
}
</code>```

You need to manually hit that url for the download to work. The rest you understand I think.

Title: Export CSV via Maatwebsite , Laravel

Body:
I try to export a csv file with some data, but with my current code I get response 200, and some strange characters, and no download, not sure why.

Source URL  here.

Exports/DataExport.php

namespace App\Exports;
use App\ViewData;
use Maatwebsite\Excel\Concerns\FromCollection;
use Excel;

class DataExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return ViewData::all();
    }
}

Controller

use App\ViewData;
use App\Exports\DataExport;

use Maatwebsite\Excel\Facades\Excel;
    .....
    //  Export CSV data
    public function export()
    {
        return Excel::download(new DataExport, 'data.xlsx');
    }

I added in config/app.php file, service provider and aliase.

Body:
You are downloading the csv file from a frontend framework, so ofcourse it will gives you some strange characters instead of downloading a whole file, let me gives you a short code for that

downloadCSV() {
let newWindow = window.open();
axios.get('/json/persons/export')
   .then(response => {
     newWindow.location = 'http://' + window.location.hostname + '/json/persons/export';
   });
}

You need to manually hit that url for the download to work. The rest you understand I think.


问:
How to filter myself out of Google Analytics with a dynamic IP address?
Does anyone know how to setup Google Analytics to filter yourself out if you're visiting the site from a dynamic IP address?  I don't want to include myself in my stats from home use where I have a dynamic IP address via Verizon FiOS.</p>

答: Consider using the NoScript plugin for Firefox.  Just mark google-analytics.com as an untrusted site and you should be all set.  A nice side-benefit: better security in your browser.</p>

OwnerDisplayName: magenta

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jdigital


问:
operator > < on sql c# asp.net
I have page.aspx , i have label that shown what is the minimum number (from item table, sql) to open an auoction ...example -  the minimum number value is 5... after i got 5 bids (from table: purchase) - the auoction start and at other lablel shown img: V. while the number of purchase small then 5 - i want to show X image.

i have two tables:

items (id, minNumber)

purchase (id)

when user buy somthing the id value up by one..(example: if i bought banana so i got the id one..after that i buy ball - i got the id 2.)

the question:

how can i use the operators > < = at code behind with the use of sql tables....

i'm very new at sql. i'm usually use LINQ to SQL.. or sql cmnd at code behind.LINQ like:

```<code>using (DataClassesDataContext myDataContext = new DataClassesDataContext())
{
  var bla = from items in myDataContext.items
         ..................
    }
</code>```

but how to continue?

i'v been tried:

```<code>               var Tokef =
                from items in myDataContext.items
                from purchase in myDataContext.purchases
                if (items.Minbuy == purchase.purchaseid) {
                   Image2.Visible = true; }
</code>```

but it doesnt work !!

答:
try something like

```<code> string sql = "Select * From items Where id LIKE '" + ID + "' AND minNumber <>= '" + minNumber+ "'";
</code>```

for Linq to SQL
try something like:var items = from p in db.items where p.ID == "someValue" AND p.minNumber <>= "somevalue" select p;

Title: operator > < on sql c# asp.net

Body:
I have page.aspx , i have label that shown what is the minimum number (from item table, sql) to open an auoction ...example -  the minimum number value is 5... after i got 5 bids (from table: purchase) - the auoction start and at other lablel shown img: V. while the number of purchase small then 5 - i want to show X image.

i have two tables:

items (id, minNumber)

purchase (id)

when user buy somthing the id value up by one..(example: if i bought banana so i got the id one..after that i buy ball - i got the id 2.)

the question:

how can i use the operators > < = at code behind with the use of sql tables....

i'm very new at sql. i'm usually use LINQ to SQL.. or sql cmnd at code behind.LINQ like:

using (DataClassesDataContext myDataContext = new DataClassesDataContext())
{
  var bla = from items in myDataContext.items
         ..................
    }

but how to continue?

i'v been tried:

               var Tokef =
                from items in myDataContext.items
                from purchase in myDataContext.purchases
                if (items.Minbuy == purchase.purchaseid) {
                   Image2.Visible = true; }

but it doesnt work !!

Body:
try something like

 string sql = "Select * From items Where id LIKE '" + ID + "' AND minNumber <>= '" + minNumber+ "'";

for Linq to SQL
try something like:var items = from p in db.items where p.ID == "someValue" AND p.minNumber <>= "somevalue" select p;


问:
Express with FIREBASE I get TypeError: Cannot read property 'trim' of undefined
I'm working in a firebase project, and I'm trying to follow a tutorial and I can find the fix.
I have seen this type of validation in other projects and it should work, but I don't know what I'm missing in my code.

I getting

TypeError: Cannot read property 'trim' of undefined

This is for a POST request

```<code>exports.createContact= (req, res)=>{
    if (req.body.body.trim() === '') {   // ERROR HERE WHEN VALIDATING

    return res.status(400).json({ body: 'Body must not be empty' });
  }
...
}
</code>```

This is the index.js

```<code>"use strict";
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const {createContact}= require('./handlers/contacts');

//middle ware

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// server functions

app.post('/contact', createContact);

exports.api = functions.https.onRequest(app);
</code>```

Thanks for your help

答:
As you asked in question (req.body.body), You can do like this,

```<code>if (!(req.body.body || '').trim()) {   // ERROR HERE WHEN VALIDATING
    return res.status(400).json({ body: 'Body must not be empty' });
}
</code>```

But If your request body is like this req.body, You can do like this,

```<code>if (!req.body || !Object.keys(req.body).length) {
    return res.status(400).json({ body: 'Body must not be empty' });
}
</code>```

Body:
I'm working in a firebase project, and I'm trying to follow a tutorial and I can find the fix.
I have seen this type of validation in other projects and it should work, but I don't know what I'm missing in my code.

I getting

TypeError: Cannot read property 'trim' of undefined

This is for a POST request

exports.createContact= (req, res)=>{
    if (req.body.body.trim() === '') {   // ERROR HERE WHEN VALIDATING

    return res.status(400).json({ body: 'Body must not be empty' });
  }
...
}

This is the index.js

"use strict";
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const {createContact}= require('./handlers/contacts');

//middle ware

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// server functions

app.post('/contact', createContact);

exports.api = functions.https.onRequest(app);

Thanks for your help

Body:
As you asked in question (req.body.body), You can do like this,

if (!(req.body.body || '').trim()) {   // ERROR HERE WHEN VALIDATING
    return res.status(400).json({ body: 'Body must not be empty' });
}

But If your request body is like this req.body, You can do like this,

if (!req.body || !Object.keys(req.body).length) {
    return res.status(400).json({ body: 'Body must not be empty' });
}