问:
MySQL Error Code: 1215. Cannot add foreign key constraint (the datatypes of the two columns match)
I am trying to create a foreign key constraint to the existing table only to receive Error Code: 1215. Cannot add foreign key constraint. Below I include SHOW CREATE TABLE observation_log_status;, SHOW CREATE TABLE observation_log; outputs and the foreign key constraint statement that fails. I have checked (according to the suggestion here) that the datatypes of the two columns are the same (they are) and if the two columns were signed or unsigned (according to the suggestion here) (they are neither), but the error remains the same. I am using MySQL 5.7.17.

Thanks,
Aina.

EDIT: this is not a duplicate, but I am obliged now to explain how it is different. In the question that is meant to be the duplicate the OP didn't have the same datatype for the two columns, I do, as shown by my SHOW CREATE TABLE statements outputs.

*********************************SOLUTION**************************************

ANOTHER EDIT: As P.Salmon suggested the problem was indeed the ENGINE.
I solved it by running ALTER TABLE observation_log ENGINE = InnoDB;.
Then the ALTER TABLE observation_log_status ADD CONSTRAINT observation_log_fk FOREIGN KEY (aat_id) REFERENCES observation_log(aat_id); statement worked fine.

*********************************SOLUTION**************************************

```<code>SHOW CREATE TABLE observation_log;
observation_log, CREATE TABLE `observation_log` (
`aat_id` decimal(14,0) NOT NULL DEFAULT '0',
  `utdate` date DEFAULT NULL,
  `session` char(1) NOT NULL DEFAULT '',
  ...,
  `aaoprgid` char(11) DEFAULT NULL,
  PRIMARY KEY (`aat_id`),
  KEY `obs_object` (`object`),
  KEY `obs_utdate` (`utdate`),
  KEY `obs_ra_dec` (`raj2000_int`,`decj2000_int`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

SHOW CREATE TABLE observation_log_status;
observation_log_status, CREATE TABLE `observation_log_status` (
  `observation_log_status_id` int(11) NOT NULL AUTO_INCREMENT,
  `aat_id` decimal(14,0) NOT NULL DEFAULT '0',
  `data_needs_processing_status` tinyint(1) DEFAULT '1',
  `data_file_transfer_status` tinyint(1) DEFAULT '0',
  `megatable_update_status` tinyint(1) DEFAULT '0',
  `data_file_search_attempt_count` int(11) DEFAULT '0',
  `data_file_trasnfer_attempt_count` int(11) DEFAULT '0',
  `megatable_update_attempt_count` int(11) DEFAULT '0',
  `data_file_transfer_timer` int(11) DEFAULT '0',
  `row_insert_time` datetime(6) DEFAULT CURRENT_TIMESTAMP(6),
  PRIMARY KEY (`observation_log_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
</code>```

The statement the generates the error:

```<code>ALTER TABLE observation_log_status ADD CONSTRAINT observation_log_fk FOREIGN KEY (aat_id) REFERENCES observation_log(aat_id);
</code>```

答:
aat_id` decimal(14,0) NOT NULL DEFAULT '0'

Try removing the default value. Foreign keys cannot have default value. Only those value present in the primary key can be accepted by foreign key

Body:
I am trying to create a foreign key constraint to the existing table only to receive Error Code: 1215. Cannot add foreign key constraint. Below I include SHOW CREATE TABLE observation_log_status;, SHOW CREATE TABLE observation_log; outputs and the foreign key constraint statement that fails. I have checked (according to the suggestion here) that the datatypes of the two columns are the same (they are) and if the two columns were signed or unsigned (according to the suggestion here) (they are neither), but the error remains the same. I am using MySQL 5.7.17.

Thanks,
Aina.

EDIT: this is not a duplicate, but I am obliged now to explain how it is different. In the question that is meant to be the duplicate the OP didn't have the same datatype for the two columns, I do, as shown by my SHOW CREATE TABLE statements outputs.

*********************************SOLUTION**************************************

ANOTHER EDIT: As P.Salmon suggested the problem was indeed the ENGINE.
I solved it by running ALTER TABLE observation_log ENGINE = InnoDB;.
Then the ALTER TABLE observation_log_status ADD CONSTRAINT observation_log_fk FOREIGN KEY (aat_id) REFERENCES observation_log(aat_id); statement worked fine.

*********************************SOLUTION**************************************

SHOW CREATE TABLE observation_log;
observation_log, CREATE TABLE `observation_log` (
`aat_id` decimal(14,0) NOT NULL DEFAULT '0',
  `utdate` date DEFAULT NULL,
  `session` char(1) NOT NULL DEFAULT '',
  ...,
  `aaoprgid` char(11) DEFAULT NULL,
  PRIMARY KEY (`aat_id`),
  KEY `obs_object` (`object`),
  KEY `obs_utdate` (`utdate`),
  KEY `obs_ra_dec` (`raj2000_int`,`decj2000_int`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

SHOW CREATE TABLE observation_log_status;
observation_log_status, CREATE TABLE `observation_log_status` (
  `observation_log_status_id` int(11) NOT NULL AUTO_INCREMENT,
  `aat_id` decimal(14,0) NOT NULL DEFAULT '0',
  `data_needs_processing_status` tinyint(1) DEFAULT '1',
  `data_file_transfer_status` tinyint(1) DEFAULT '0',
  `megatable_update_status` tinyint(1) DEFAULT '0',
  `data_file_search_attempt_count` int(11) DEFAULT '0',
  `data_file_trasnfer_attempt_count` int(11) DEFAULT '0',
  `megatable_update_attempt_count` int(11) DEFAULT '0',
  `data_file_transfer_timer` int(11) DEFAULT '0',
  `row_insert_time` datetime(6) DEFAULT CURRENT_TIMESTAMP(6),
  PRIMARY KEY (`observation_log_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The statement the generates the error:

ALTER TABLE observation_log_status ADD CONSTRAINT observation_log_fk FOREIGN KEY (aat_id) REFERENCES observation_log(aat_id);


来源: stackexchange

问:
How do I get webpack chunk hash during build?
How can I string replace a variable in my HTML template that points to the current chunk hash?

My HTML template looks like this:

```<code><html>
    <head>
        <link href="$css" rel="stylesheet">
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>
</code>```

I'm trying to get it to build like this:

```<code><html>
    <head>
        <link href="app.c824da43.css" rel="stylesheet">
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>
</code>```

I tried using string replace with [name].[chunkhash:8].css but that renders as literally:

```<code><html>
    <head>
        <link href="[name].[chunkhash:8].css" rel="stylesheet">
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>
</code>```

My project:

```<code>.
├── dist
│   ├── app.c824da43.css
│   └── index.html
├── html
│   └── index.html
├── package.json
├── sass
│   └── main.scss
└── webpack.config.js
</code>```

My webpack.config.js

```<code>var webpack = require('webpack');
var outdir = __dirname + '/dist';
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        app: [
            './sass/main.scss',
            './html/index.html',
        ]
    },
    output: {
        path: outdir,
        filename: '[name].[chunkhash:8].js'
    },
    module: {
        rules: [
            {
                test: /\.s[ac]ss$/,
                use: ExtractTextPlugin.extract({
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "file-loader",
                        options: {
                            name: "/[name].[ext]",
                        },
                    },
                    {
                        loader: 'string-replace-loader',
                        query: {
                            search: /\$css/,
                // What do I need to put here?
                            replace: '/[name].[chunkhash:8].css'
                        }
                    },
                    {
                        loader: "extract-loader",
                    },
                    {
                        loader: 'html-loader',
                        options: {
                            minimize: true,
                            removeComments: true,
                            collapseWhitespace: true
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin("[name].[chunkhash:8].css"),
    ]
};
</code>```

My package.json

```<code>{
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-loader": "^0.1.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "html-loader": "^0.4.5",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.5",
    "string-replace-loader": "^1.2.0",
    "webpack": "^2.6.1"
  }
}
</code>```

Demo with solution

答:
Remove the index.html entry point from your webpack config. Use HtmlWebpackPlugin to copy your index.html. The plugin will automatically add the CSS <link> tag to your generated html.

See https://github.com/jantimon/html-webpack-plugin

If the plugin is used, all minifications should be done inside the plugin instead of the html-loader in your /\.html$/ rule.

```<code>new HtmlWebpackPlugin({
  template: 'html/index.html',
  filename: 'index.html',
  minify: {
    collapseWhitespace: true,
    removeComments: true
  }
})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I string replace a variable in my HTML template that points to the current chunk hash?

My HTML template looks like this:

        <link href="$css" rel="stylesheet">

Hello World

I'm trying to get it to build like this:

        <link href="app.c824da43.css" rel="stylesheet">

Hello World

I tried using string replace with [name].[chunkhash:8].css but that renders as literally:

        <link href="[name].[chunkhash:8].css" rel="stylesheet">

Hello World

My project:

.
├── dist
│   ├── app.c824da43.css
│   └── index.html
├── html
│   └── index.html
├── package.json
├── sass
│   └── main.scss
└── webpack.config.js

My webpack.config.js

var webpack = require('webpack');
var outdir = __dirname + '/dist';
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        app: [
            './sass/main.scss',
            './html/index.html',
        ]
    },
    output: {
        path: outdir,
        filename: '[name].[chunkhash:8].js'
    },
    module: {
        rules: [
            {
                test: /\.s[ac]ss$/,
                use: ExtractTextPlugin.extract({
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "file-loader",
                        options: {
                            name: "/[name].[ext]",
                        },
                    },
                    {
                        loader: 'string-replace-loader',
                        query: {
                            search: /\$css/,
                // What do I need to put here?
                            replace: '/[name].[chunkhash:8].css'
                        }
                    },
                    {
                        loader: "extract-loader",
                    },
                    {
                        loader: 'html-loader',
                        options: {
                            minimize: true,
                            removeComments: true,
                            collapseWhitespace: true
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin("[name].[chunkhash:8].css"),
    ]
};

My package.json

{
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-loader": "^0.1.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "html-loader": "^0.4.5",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.5",
    "string-replace-loader": "^1.2.0",
    "webpack": "^2.6.1"
  }
}

Demo with solution

Body:
Remove the index.html entry point from your webpack config. Use HtmlWebpackPlugin to copy your index.html. The plugin will automatically add the CSS <link> tag to your generated html.

See https://github.com/jantimon/html-webpack-plugin

If the plugin is used, all minifications should be done inside the plugin instead of the html-loader in your /\.html$/ rule.

new HtmlWebpackPlugin({
  template: 'html/index.html',
  filename: 'index.html',
  minify: {
    collapseWhitespace: true,
    removeComments: true
  }
})


问:
Joining table into 4 columns
I've a problem to show 4 different columns from different table, for more detail, let see in the below :

Table personal (tbl_personal)

```<code>+---+-----+------------+
|ID |Name |Skill       |
+---+-----+------------+
| 1 | Nia | Accountant |
| 2 | Tia | Banking    |
| 3 | Ria | Technicall |
| 4 | Dia | Admin      |
+---+-----+------------+
</code>```

Table master (tbl_master)

```<code>+---+---------+---------+
|ID |Employee1|Employee2|
+---+---------+---------+
| 1 | 1       | 2       |
| 2 | 2       | 1       |
| 3 | 3       | 4       |
+---+---------+---------+
</code>```

I want to show into web page from tbl_master above in codeigniter like this :

```<code>+---+-------+-----------+-------+-----------+
|ID |Name 1 |Skill 1    |Name 2 |Skill 2    |
+---+-------+-----------+-------+-----------+
| 1 | Nia   | Accountant| Tia   | Banking   |
| 2 | Tia   | Banking   | Nia   | Accountant|
| 3 | Ria   | Technicall| Dia   | Admin     |
+---+---------+---------+-------+-----------+
</code>```

Please advice if any suggestion for me to join from tbl_personal with tbl_master,

Thanks for your support...

答:
I think you have to use 2 joins for this. Also you have to be careful in selecting columns after joining

```<code>SELECT tp1.name as Name1, tp1.Skill as Skill1,tp2.name as Name2, tp2.Skill as Skill2
FROM tbl_master tm1
JOIN tbl_personal tp1 on tp1.id = tm1.Employee1
JOIN tbl_personal tp2 on tp2.id = tm1.Employee2
</code>```

This should be the output for this query.

Just add ID column in select query.

ContentLicense: CC BY-SA 4.0

Title: Joining table into 4 columns

Body:
I've a problem to show 4 different columns from different table, for more detail, let see in the below :

Table personal (tbl_personal)

+---+-----+------------+
|ID |Name |Skill       |
+---+-----+------------+
| 1 | Nia | Accountant |
| 2 | Tia | Banking    |
| 3 | Ria | Technicall |
| 4 | Dia | Admin      |
+---+-----+------------+

Table master (tbl_master)

+---+---------+---------+
|ID |Employee1|Employee2|
+---+---------+---------+
| 1 | 1       | 2       |
| 2 | 2       | 1       |
| 3 | 3       | 4       |
+---+---------+---------+

I want to show into web page from tbl_master above in codeigniter like this :

+---+-------+-----------+-------+-----------+
|ID |Name 1 |Skill 1    |Name 2 |Skill 2    |
+---+-------+-----------+-------+-----------+
| 1 | Nia   | Accountant| Tia   | Banking   |
| 2 | Tia   | Banking   | Nia   | Accountant|
| 3 | Ria   | Technicall| Dia   | Admin     |
+---+---------+---------+-------+-----------+

Please advice if any suggestion for me to join from tbl_personal with tbl_master,

Thanks for your support...

Body:
I think you have to use 2 joins for this. Also you have to be careful in selecting columns after joining

SELECT tp1.name as Name1, tp1.Skill as Skill1,tp2.name as Name2, tp2.Skill as Skill2
FROM tbl_master tm1
JOIN tbl_personal tp1 on tp1.id = tm1.Employee1
JOIN tbl_personal tp2 on tp2.id = tm1.Employee2

This should be the output for this query.

Just add ID column in select query.


问:
PHP script processing/cpu time (Not wall clock time)
I'm trying to profile some PHP scripts I'm running. I'm already measuring the wall clock time but now I want to know how much time the cpu has dedicated to the script.

Is there any way to measure cpu time of a script? I'm using php7.1

答: AFAIK, you can use xhprof library to measure the cpu time. Here are guidelines of how you can use the library https://tideways.io/profiler/xhprof-for-php7-php5.6.


问:
Error: Cannot access file bin/Debug/... because it is being used by another process
When I debug my project, I get following error:

"Unable to copy file "obj\Debug\My Dream.exe" to "bin\Debug\My Dream.exe". The process cannot access the file 'bin\Debug\My Dream.exe' because it is being used by another process."

Using Process Explorer, I see that MyApplication.exe was out but System process still uses it although I stopped debug before.
Whenever I change my code and start debug it is going to happen. If I copy project to USB and debug, it runs OK.

Why? How can I fix this error?

I use Window 7 Professional. With Xp I have never got this error.

答:
In my case was that I have enable "Show All Files".
Visual Studio 2017</p>


问:
Why does this callback function not add bind.(this)?
As I know, we need to use .bind each time when you pass your custom function to an event handler like onChange or onSubmit

In the following Example ,we pass an event handler (talk function) as a prop.
When a user click a button,talk function will be called.

```<code>var React = require('react');
var ReactDOM = require('react-dom');
var Button = require('./Button');

var Talker = React.createClass({
  talk: function () {
    for (var speech = '', i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  },

  render: function () {
    return <Button talk={this.talk}/>;
  }
});

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);
</code>```

Button.js

```<code>var React = require('react');

var Button = React.createClass({
  render: function () {
    return (
      <button onClick={this.props.talk}>
        Click me!
      </button>
    );
  }
});

module.exports = Button;
</code>```

This example uses Button talk={this.talk} instead of Button {this.talk.bind.(this)}

,but why?

答:
Because, basically, .bind will "bind" a particular object to "this". But since the function doesn't make a use of "this" so it won't be matter if you bind it or not.

if in the function talk you have reference to a "Talker" class's instance. that's the moment you will start getting some issues.

Body:
As I know, we need to use .bind each time when you pass your custom function to an event handler like onChange or onSubmit

In the following Example ,we pass an event handler (talk function) as a prop.
When a user click a button,talk function will be called.

var React = require('react');
var ReactDOM = require('react-dom');
var Button = require('./Button');

var Talker = React.createClass({
  talk: function () {
    for (var speech = '', i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  },

  render: function () {
    return <Button talk={this.talk}/>;
  }
});

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);

Button.js

var React = require('react');

var Button = React.createClass({
  render: function () {
    return (
      <button onClick={this.props.talk}>
        Click me!
      </button>
    );
  }
});

module.exports = Button;

This example uses Button talk={this.talk} instead of Button {this.talk.bind.(this)}

,but why?


问:
Way to shrink Resources folder?
I have 100 pictures in my Resources folder and they can really be annoying when trying to find some other resource. Is there a way I could "create another resource folder" to put the 100 pictures in?

Or do I just have to deal with scrolling and scrolling when trying to find another resource?

答:
You can put files wherever you want in your project-- Resources is just a default folder that gets created for you. You could create a sibling folder to Resources, or a subfolder inside of it.

You can do this in two ways: One by right clicking on the project and creating a new group for the images. This will create the logical folder, but won't actually create a subdirectory on disk. If you want the layout on disk also, create the folder on the command line or with Finder and then drag it into Xcode.

ContentLicense: CC BY-SA 2.5

Title: Way to shrink Resources folder?


问:
unable to install wkhtmltopdf with patched qt in ubuntu 16.04
wkhtmltopdf with patched qt  pkg is not available for ubuntu 16.04 .so i am install 14.04 pkg which is install without patched qt but it need it with patched qt. I also tried with static version but it give some compilation
error </p>

答:
I ran @matheus-marchini's script to install the patched version a while back and just came back to get the instructions again - however, I discovered that in the interim, the hosting site Gna! has shut down. After a little search, I was able to replace the link directly from the source, updating the command as follows:

```<code>wget https://downloads.wkhtmltopdf.org/0.12/0.12.3/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz -P /tmp/
</code>```

If you want the most recent version (per @afzal-hossain's answer), it would be:

```<code>wget https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz -P /tmp/
</code>```

I would have written this as a comment instead of as an "answer" but I do not have enough reputation yet to do that. Hope this helps someone else!

Body:
I ran @matheus-marchini's script to install the patched version a while back and just came back to get the instructions again - however, I discovered that in the interim, the hosting site Gna! has shut down. After a little search, I was able to replace the link directly from the source, updating the command as follows:

wget https://downloads.wkhtmltopdf.org/0.12/0.12.3/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz -P /tmp/

If you want the most recent version (per @afzal-hossain's answer), it would be:

wget https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz -P /tmp/

I would have written this as a comment instead of as an "answer" but I do not have enough reputation yet to do that. Hope this helps someone else!


答:
.bind is used to ensure the function is called with the context of the class rather than the context of the caller.

It is required particularly when you access class properties within the function.
For example if your speech variable was a class variable rather than a local one.

```<code>talk: function () {
    for (this.speech = '', i = 0; i < 10000; i++) {
      this.speech += 'blah ';
    }
    alert(this.speech);
  },
</code>```

In this case you would need bind.

Your talk function is not doing this.
It has its own local variables and so can be called using any this context.

talk={this.talk} will work here.

Also the syntax for bind function incorrect in the question. It needs to be this.talk.bind(this) not this.talk.bind.(this)

Title: Why does this callback function not add bind.(this)?

Body:
.bind is used to ensure the function is called with the context of the class rather than the context of the caller.

It is required particularly when you access class properties within the function.
For example if your speech variable was a class variable rather than a local one.

talk: function () {
    for (this.speech = '', i = 0; i < 10000; i++) {
      this.speech += 'blah ';
    }
    alert(this.speech);
  },

In this case you would need bind.

Your talk function is not doing this.
It has its own local variables and so can be called using any this context.

talk={this.talk} will work here.

Also the syntax for bind function incorrect in the question. It needs to be this.talk.bind(this) not this.talk.bind.(this)


问:
Text field in same line HTML
How to make multiple text fields in the same line.

This is my code:

```<code><div class="col-lg-2">
    <div class="form-group">
        <label>Working experience</label>
        <input type="text" class="form-control  " placeholder="Year"/>Year
        <input type="text" class="form-control " placeholder="Month"/>Month
        <input type="text" class="form-control  " placeholder="Day" />Day
    </div>
</div>
</code>```

答:
You could use inline form class.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <form class="form-inline">

      Working experience
      <input type="text" class="form-control" placeholder="Year">
      <input type="text" class="form-control" placeholder="Month">
      <input type="text" class="form-control " placeholder="Day">

  </form>```

Use Expand snippet to see actual result.

Title: Text field in same line HTML

Body:
How to make multiple text fields in the same line.

This is my code:

        Working experience
        <input type="text" class="form-control  " placeholder="Year"/>Year
        <input type="text" class="form-control " placeholder="Month"/>Month
        <input type="text" class="form-control  " placeholder="Day" />Day

Body:
You could use inline form class.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <form class="form-inline">
    <div class="form-group">
      <label>Working experience</label>
      <input type="text" class="form-control" placeholder="Year">
      <input type="text" class="form-control" placeholder="Month">
      <input type="text" class="form-control " placeholder="Day">
    </div>
  </form>

Use Expand snippet to see actual result.


问:
What is the difference between var and val in Kotlin?
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

```<code>fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}
</code>```

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.

答:
val and var both are used to declare a variable.

var is like general variable and it's known as a mutable variable in kotlin and can be assigned multiple times.

val is like Final variable and it's known as immutable in kotlin and can be initialized only single time.

For more information what is val and var please see below link

http://blog.danlew.net/2017/05/30/mutable-vals-in-kotlin/

Body:
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.


问:
Login "onSuccess" navigating to another page. React
So i want to be able to go to the main page after the user successfully logs in. I am still new to React. How can this be done. I am using v4 of react as well. When i hit the login button it seems to trigger the action but not complete it.

Here is the action that handles the login:

```<code>const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
  this.props.history.push('/main');
}
dispatch({
    type: POST_DATA_SUCCESS,
    response,
});
};

export function loginUser(username1, password1) {
const promise = fetch('http://localhost:8080/users/login', {
method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
},
body: JSON.stringify({
  username: username1,
  password: password1,
})
});
return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
};
}
</code>```

Here is the backend that handles the login request:

```<code>router.get('/login',
passport.authenticate('basic', {session: false}),
(req, res) => res.json({user: req.user.apiRepr()})
);

router.post('/login', function (req, res, next) {
passport.authenticate('basic', function (err, user, info) {
    if (err) {
        return console.log(err);
    }
    if (!user) {
        return res.status(401).json({
            message: 'Username/Password Incorrect'
        });
    }
    req.logIn(user, function (err) {
        if (err) {
            return console.log(err);
        }
        return res.status(200).json({
            user: user.username
        });
    });
})(req, res, next);
});
</code>```

And the login component with the form:

```<code>import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import { loginUser } from '../actions';
import { connect } from 'react-redux';

export class Login extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
  //username: '',
  //password: '',
 }
}

render() {
 return(
 <form>
   <h3>Login to start your Journey</h3>
   <input placeholder="username" ref={input => {this.username = input}}>
   </input>
  <input placeholder="password" type="password"ref={input => {this.password
  = input}}></input>
  <button onClick={this.login.bind(this)}>Login</button>
 </form>
  )
}

login() {
 const userName = this.username.value;
 const passWord = this.password.value;
 console.log(userName);
 console.log(passWord);
 this.props.loginUser(userName, passWord);
 }
}

export default connect(null, { loginUser })(Login);
</code>```

答:
In your mainPage action creator, you make a reference to the props using this assuming it binds to the component instance. It's not.

```<code>   const mainPage = (response, dispatch) => {
     if(POST_DATA_SUCCESS) {
       this.props.history.push('/main'); // 'this' here does not refer to the React component instance
     }
     dispatch({
        type: POST_DATA_SUCCESS,
        response,
     });
   };
</code>```

If you are using react-router v4, you can use react-router-redux, and import push which is an action creator that will be handled by router reducer. You will need setup your redux store first by following the step here

```<code>import { push } from 'react-router-redux'

const mainPage = (response, dispatch) => {
    if(POST_DATA_SUCCESS) {
      dispatch(push('/main'));
    }
    dispatch({
        type: POST_DATA_SUCCESS,
        response,
    });
};
</code>```

Body:
So i want to be able to go to the main page after the user successfully logs in. I am still new to React. How can this be done. I am using v4 of react as well. When i hit the login button it seems to trigger the action but not complete it.

Here is the action that handles the login:

const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
  this.props.history.push('/main');
}
dispatch({
    type: POST_DATA_SUCCESS,
    response,
});
};

export function loginUser(username1, password1) {
const promise = fetch('http://localhost:8080/users/login', {
method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
},
body: JSON.stringify({
  username: username1,
  password: password1,
})
});
return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
};
}

Here is the backend that handles the login request:

router.get('/login',
passport.authenticate('basic', {session: false}),
(req, res) => res.json({user: req.user.apiRepr()})
);

router.post('/login', function (req, res, next) {
passport.authenticate('basic', function (err, user, info) {
    if (err) {
        return console.log(err);
    }
    if (!user) {
        return res.status(401).json({
            message: 'Username/Password Incorrect'
        });
    }
    req.logIn(user, function (err) {
        if (err) {
            return console.log(err);
        }
        return res.status(200).json({
            user: user.username
        });
    });
})(req, res, next);
});

And the login component with the form:

import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import { loginUser } from '../actions';
import { connect } from 'react-redux';

export class Login extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
  //username: '',
  //password: '',
 }
}

render() {
 return(
 <form>

Login to start your Journey

   <input placeholder="username" ref={input => {this.username = input}}>
   </input>
  <input placeholder="password" type="password"ref={input => {this.password
  = input}}></input>
  <button onClick={this.login.bind(this)}>Login</button>
 </form>
  )
}

login() {
 const userName = this.username.value;
 const passWord = this.password.value;
 console.log(userName);
 console.log(passWord);
 this.props.loginUser(userName, passWord);
 }
}

export default connect(null, { loginUser })(Login);

Body:
In your mainPage action creator, you make a reference to the props using this assuming it binds to the component instance. It's not.

   const mainPage = (response, dispatch) => {
     if(POST_DATA_SUCCESS) {
       this.props.history.push('/main'); // 'this' here does not refer to the React component instance
     }
     dispatch({
        type: POST_DATA_SUCCESS,
        response,
     });
   };

If you are using react-router v4, you can use react-router-redux, and import push which is an action creator that will be handled by router reducer. You will need setup your redux store first by following the step here

import { push } from 'react-router-redux'

const mainPage = (response, dispatch) => {
    if(POST_DATA_SUCCESS) {
      dispatch(push('/main'));
    }
    dispatch({
        type: POST_DATA_SUCCESS,
        response,
    });
};


问:
Entity Framework return every referenced table for one Entity
I tries to rewrite my Java EE project to C# Rest Api project.
For database mapping I user Entity Framework, and have some problems with gettion records from table.
First of all I've got a table wich is referred to by other tables:

```<code>CREATE TABLE Bibliogr (
  Bknumber INT PRIMARY KEY NOT NULL,
  Authors VARCHAR(500),
  Source VARCHAR(500),
  Title VARCHAR(1000)
);
</code>```

The mapped class is following:

```<code>public partial class Bibliogr
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Bibliogr()
        {
            this.AcOpTabl = new HashSet<AcOpTabl>();
            this.ConstSel = new HashSet<ConstSel>();
            this.CuryTabl = new HashSet<CuryTabl>();
            this.DecrTabl = new HashSet<DecrTabl>();
            this.DensTabl = new HashSet<DensTabl>();
            this.DielDiss = new HashSet<DielDiss>();
            this.Dielectr = new HashSet<Dielectr>();
            this.ElemTabl = new HashSet<ElemTabl>();
            this.ElOpTabl = new HashSet<ElOpTabl>();
            this.EquationTabl = new HashSet<EquationTabl>();
            this.EsOpTabl = new HashSet<EsOpTabl>();
            this.HardTabl = new HashSet<HardTabl>();
            this.HeatExpn = new HashSet<HeatExpn>();
            this.HeatTabl = new HashSet<HeatTabl>();
            this.MechTabl = new HashSet<MechTabl>();
            this.MnOpTabl = new HashSet<MnOpTabl>();
            this.ModfTabl = new HashSet<ModfTabl>();
            this.NlOpTabl = new HashSet<NlOpTabl>();
            this.PlavTabl = new HashSet<PlavTabl>();
            this.PzElTabl = new HashSet<PzElTabl>();
            this.RefrcInd = new HashSet<RefrcInd>();
            this.SuspTabl = new HashSet<SuspTabl>();
            this.Wavepure = new HashSet<Wavepure>();
        }

        public int Bknumber { get; set; }
        public string Authors { get; set; }
        public string Source { get; set; }
        public string Title { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AcOpTabl> AcOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ConstSel> ConstSel { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<CuryTabl> CuryTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<DecrTabl> DecrTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<DensTabl> DensTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<DielDiss> DielDiss { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Dielectr> Dielectr { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ElemTabl> ElemTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ElOpTabl> ElOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<EquationTabl> EquationTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<EsOpTabl> EsOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HardTabl> HardTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HeatExpn> HeatExpn { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HeatTabl> HeatTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<MechTabl> MechTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<MnOpTabl> MnOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ModfTabl> ModfTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<NlOpTabl> NlOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<PlavTabl> PlavTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<PzElTabl> PzElTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RefrcInd> RefrcInd { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SuspTabl> SuspTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Wavepure> Wavepure { get; set; }
    }
</code>```

There are a lot of HashSet which I don't want to get from my request. How can I change this behaviour? I need only this table coulmn values and not the other tables.

The request result:

```<code>{
   "AcOpTabl":[  ],
   "ConstSel":[  ],
   "CuryTabl":[  ],
   "DecrTabl":[  ],
   "DensTabl":[  ],
   "DielDiss":[  ],
   "Dielectr":[  ],
   "ElemTabl":[  ],
   "ElOpTabl":[  ],
   "EquationTabl":[  ],
   "EsOpTabl":[  ],
   "HardTabl":[  ],
   "HeatExpn":[  ],
   "HeatTabl":[  ],
   "MechTabl":[  ],
   "MnOpTabl":[  ],
   "ModfTabl":[  ],
   "NlOpTabl":[  ],
   "PlavTabl":[  ],
   "PzElTabl":[  ],
   "RefrcInd":[  ],
   "SuspTabl":[  ],
   "Wavepure":[  ],
   "Bknumber":4,
   "Authors":"Niizeki N.,Yamada N.,Toyoda H.",
   "Source":"Jap.J.Appl.Phys.,1967,v.6,N.3,p.318-327",
   "Title":"Growth ridges, etched hillocks and crystal structure of lithium niobate"
}
</code>```

答:
I am assuming you have lazy loading enabled in your EntityFramework's DbContext. When serialization happens, each property is accessed and EF loads it for you.

Good solution for this case is to remove the virtual keywords on your ICollection properties. This is selective disabling of lazy loading.

You can also disable lazy-loading all-together by doing this

```<code>public class YourContext : DbContext
{
    public YourContext()
    {
        // Default behaviour is true
        this.Configuration.LazyLoadingEnabled = false;
    }
}
</code>```

Body:
I tries to rewrite my Java EE project to C# Rest Api project.
For database mapping I user Entity Framework, and have some problems with gettion records from table.
First of all I've got a table wich is referred to by other tables:

CREATE TABLE Bibliogr (
  Bknumber INT PRIMARY KEY NOT NULL,
  Authors VARCHAR(500),
  Source VARCHAR(500),
  Title VARCHAR(1000)
);

The mapped class is following:

public partial class Bibliogr
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Bibliogr()
        {
            this.AcOpTabl = new HashSet<AcOpTabl>();
            this.ConstSel = new HashSet<ConstSel>();
            this.CuryTabl = new HashSet<CuryTabl>();
            this.DecrTabl = new HashSet<DecrTabl>();
            this.DensTabl = new HashSet<DensTabl>();
            this.DielDiss = new HashSet<DielDiss>();
            this.Dielectr = new HashSet<Dielectr>();
            this.ElemTabl = new HashSet<ElemTabl>();
            this.ElOpTabl = new HashSet<ElOpTabl>();
            this.EquationTabl = new HashSet<EquationTabl>();
            this.EsOpTabl = new HashSet<EsOpTabl>();
            this.HardTabl = new HashSet<HardTabl>();
            this.HeatExpn = new HashSet<HeatExpn>();
            this.HeatTabl = new HashSet<HeatTabl>();
            this.MechTabl = new HashSet<MechTabl>();
            this.MnOpTabl = new HashSet<MnOpTabl>();
            this.ModfTabl = new HashSet<ModfTabl>();
            this.NlOpTabl = new HashSet<NlOpTabl>();
            this.PlavTabl = new HashSet<PlavTabl>();
            this.PzElTabl = new HashSet<PzElTabl>();
            this.RefrcInd = new HashSet<RefrcInd>();
            this.SuspTabl = new HashSet<SuspTabl>();
            this.Wavepure = new HashSet<Wavepure>();
        }

        public int Bknumber { get; set; }
        public string Authors { get; set; }
        public string Source { get; set; }
        public string Title { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AcOpTabl> AcOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ConstSel> ConstSel { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<CuryTabl> CuryTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<DecrTabl> DecrTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<DensTabl> DensTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<DielDiss> DielDiss { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Dielectr> Dielectr { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ElemTabl> ElemTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ElOpTabl> ElOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<EquationTabl> EquationTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<EsOpTabl> EsOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HardTabl> HardTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HeatExpn> HeatExpn { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HeatTabl> HeatTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<MechTabl> MechTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<MnOpTabl> MnOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ModfTabl> ModfTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<NlOpTabl> NlOpTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<PlavTabl> PlavTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<PzElTabl> PzElTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RefrcInd> RefrcInd { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SuspTabl> SuspTabl { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Wavepure> Wavepure { get; set; }
    }

There are a lot of HashSet which I don't want to get from my request. How can I change this behaviour? I need only this table coulmn values and not the other tables.

The request result:

{
   "AcOpTabl":[  ],
   "ConstSel":[  ],
   "CuryTabl":[  ],
   "DecrTabl":[  ],
   "DensTabl":[  ],
   "DielDiss":[  ],
   "Dielectr":[  ],
   "ElemTabl":[  ],
   "ElOpTabl":[  ],
   "EquationTabl":[  ],
   "EsOpTabl":[  ],
   "HardTabl":[  ],
   "HeatExpn":[  ],
   "HeatTabl":[  ],
   "MechTabl":[  ],
   "MnOpTabl":[  ],
   "ModfTabl":[  ],
   "NlOpTabl":[  ],
   "PlavTabl":[  ],
   "PzElTabl":[  ],
   "RefrcInd":[  ],
   "SuspTabl":[  ],
   "Wavepure":[  ],
   "Bknumber":4,
   "Authors":"Niizeki N.,Yamada N.,Toyoda H.",
   "Source":"Jap.J.Appl.Phys.,1967,v.6,N.3,p.318-327",
   "Title":"Growth ridges, etched hillocks and crystal structure of lithium niobate"
}

Body:
I am assuming you have lazy loading enabled in your EntityFramework's DbContext. When serialization happens, each property is accessed and EF loads it for you.

Good solution for this case is to remove the virtual keywords on your ICollection properties. This is selective disabling of lazy loading.

You can also disable lazy-loading all-together by doing this

public class YourContext : DbContext
{
    public YourContext()
    {
        // Default behaviour is true
        this.Configuration.LazyLoadingEnabled = false;
    }
}


问:
console.log shows object Object in an angular form
Following and advice I'm trying to do a template driven form. But if I atempt to log in the console the userForm.value I just get " [object Object] " What am I doing wrong?</p>

```<code><form *ngIf="data" #userForm="ngForm">
    <div *ngFor="let item of data" (change)="Update(item.id, userForm.value)">
        <input type="radio" name="{{item.id}}" value="1" required ngModel>Foo
        <input type="radio" name="{{item.id}}" value="2" ngModel>Bar
    </div>
  </form>
</code>```

答:
Use JSON.stringify ,

```<code>JSON.stringify(userForm.value);
</code>```

Body:
Following and advice I'm trying to do a template driven form. But if I atempt to log in the console the userForm.value I just get " [object Object] " What am I doing wrong?

<form *ngIf="data" #userForm="ngForm">

        <input type="radio" name="{{item.id}}" value="1" required ngModel>Foo
        <input type="radio" name="{{item.id}}" value="2" ngModel>Bar

  </form>

Body:
Use JSON.stringify ,

JSON.stringify(userForm.value);


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答: When all of the requirements are met and all the tests pass.</p>

OwnerDisplayName: Micah

OwnerDisplayName: Jim Blizard


问:
replace every second line of my triangle with a blank line for loops
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

```<code>  5

 555

55555
</code>```

This is my code:

```<code> for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}
</code>```

答:
Just test for i % 2

```<code>      for(int i = 0; i < 5; i++) {

             for(int j = i; j < 5; j++) {

                 System.out.print(" ");

             }

             for(int k = 0; k <= (i*2); k++) {

                 System.out.print(i % 2 == 0 ? "*" : " ");
             }
             System.out.println();
        }
</code>```

edit

If you want to print 5 instead or * then modify the code to use 5

Body:
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

  5

 555

55555

This is my code:

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

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}

Body:
Just test for i % 2

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

             for(int j = i; j < 5; j++) {

                 System.out.print(" ");

             }

             for(int k = 0; k <= (i*2); k++) {

                 System.out.print(i % 2 == 0 ? "*" : " ");
             }
             System.out.println();
        }

edit

If you want to print 5 instead or * then modify the code to use 5


答: In this case, you want to use bind if the component Talker is used in another component. If it is the case, this in the Talker component would refer to the other component instead. In your current case, it is passed down to the button. Therefore, the use of bind is required to ensure that it is calling from Talker instead of the Button component.


问:
Two aggregates and one transaction - the Red Book example
In the Red Book Vernon models BacklogItem and Sprint entities as seperate aggregates. I see advantages of this approach but there is one case that I can't get my head around. For example, I need my Sprint aggregate to enforce maximum items assigned limit. Moreover the BacklogItem must be aware of assigment fact to make sure it is not assigned to more than one Sprint. So assigning BacklogItem to Sprint changes two aggregates in one transaction which is not what we want to do. I can not see any good approach that solves this issue. Expanding aggregate implies making BacklogItem internal part of Sprit. Which does not make any sense because of nessesity of using it inside other aggregates (Release, Schedule). Another way I have come up with is to use eventual consistency and just alert administrator about double assigment of the BacklogItem. But I perceive it as important aggregate invariant and I would like to gain opportiunity to impose that explicitly. </p>

答:
Another way I have come up with is to use eventual consistency and just alert administrator about double assignment of the BacklogItem.

My guess is that this is the correct answer.

I need my Sprint aggregate to enforce maximum items assigned limit.

There's an important consideration that you may be overlooking: who decides which BacklogItems are added to a Sprint?  Is that a decision that the model is making for itself, or is that decision made by a human being (or some other entity outside the model)?

Because for the most part the model should not be discarding decisions made by human operators; and it shouldn't force the human operators to context shift to jump through the model's hoops.

There is no point to run that command if we know in advance that we exceeding Sprint items limit. If the Command Handler will perform that checking: $sprint->hasSpaceFor($item); wouldn't it be considered as knowledge leaking?

There are a couple things to consider here.

One is that data that's not part of the aggregate is stale; there could be another command handler changing that data while you are checking it.  That doesn't mean that checking it is wrong, but it does mean that checking it in the command handler isn't obviously better than checking it somewhere else.

Secondly, your check of the invariant depends on the order in which messages arrive.  The human operator may have decided to remove an item from a sprint to make room for the new one -- but if the order of messages gets changed in transit (unreliable messaging transport), then the model ends up rejecting what should be a valid command. That's not good.

Alternatively, the messages may be arriving in the order they were dispatched.  The human operator knows the two operations cancel out, and therefore it shouldn't matter what order it happens -- but the model insists that the decisions be reported in a specific order.  That's hoop jumping -- the model is making the job harder, instead of easier.

And furthermore, the value to the business of getting the right item into the sprint may be more valuable than figuring out which one to remove.

Key insight: the human operator is working with the priorities of the business now, but the model running in production reflects the priorities at the time it was written -- in other words, the model has captured past priorities.  So you want to be careful about having the model veto the operator.

More to the point, you want to understand how business value is derived when vetoing the messages you get from the human operator, and decide where that responsibility should be managed -- maybe it's a UI concern (trying to reduce the high cost of data entry errors?), rather than a domain model concern.


答:
The Code below is Working now.

A simple if condition will solve your problem. Just check if the
  value of i is divisible by 2. If it is true then print a
  blank line. Else Print * and you are done!

* will be printed on 1st, 3rd and 5th lines.

Blank Space will be printed on 2nd and 4th lines.

```<code>public class PrintPattern{
     public static void main(String []args){
         int lineNo=0; // New Variable for Line Number (Can Use variable 'i' also)
        for(int i = 0; i < 5; i++) {
            lineNo++;
            for(int j = i; j < 5; j++) {
                System.out.print(" ");
            }

            if(lineNo%2!=0){
                for(int k = 0; k <= (i*2); k++)
                    System.out.print('*'); // Will print '*' (or '5') Sequence for Odd Lines - 1st, 3rd, 5th Lines
                System.out.println();
                }
            else
                System.out.println();// Will print Blank Line for Even Lines - 2nd and 4th Lines
        }
     }
}
</code>```

Title: replace every second line of my triangle with a blank line for loops

Body:
The Code below is Working now.

A simple if condition will solve your problem. Just check if the
  value of i is divisible by 2. If it is true then print a
  blank line. Else Print * and you are done!

* will be printed on 1st, 3rd and 5th lines.

Blank Space will be printed on 2nd and 4th lines.

public class PrintPattern{
     public static void main(String []args){
         int lineNo=0; // New Variable for Line Number (Can Use variable 'i' also)
        for(int i = 0; i < 5; i++) {
            lineNo++;
            for(int j = i; j < 5; j++) {
                System.out.print(" ");
            }

            if(lineNo%2!=0){
                for(int k = 0; k <= (i*2); k++)
                    System.out.print('*'); // Will print '*' (or '5') Sequence for Odd Lines - 1st, 3rd, 5th Lines
                System.out.println();
                }
            else
                System.out.println();// Will print Blank Line for Even Lines - 2nd and 4th Lines
        }
     }
}


问:
Why SelectMany needs the one of M<S> -> (S -> M<C>) -> (S -> M<C> -> R) -> E<R>?
In the link https://msdn.microsoft.com/en-us/library/bb534631(v=vs.110).aspx, the third signature is

```<code>// M<S> -> (S -> M<C>) -> (S -> M<C> -> R) -> E<R>
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TCollection>> collectionSelector,
    Func<TSource, TCollection, TResult> resultSelector
)
</code>```

Shouldn't the first one which has the signature of the typical Monad bind function M -> (A -> M) -> M be enough? Isn't it easy to merge code in the resultSelector into collectionSelector?

The MSDN document gave an example to show the usage of the method.

```<code>class Program
{
    static void Main(string[] args)
    {
        SelectManyEx3();
    }
    public static void SelectManyEx3()
    {
        PetOwner[] petOwners =
            { new PetOwner { Name="Higa",
                    Pets = new List<string>{ "Scruffy", "Sam" } },
                new PetOwner { Name="Ashkenazi",
                    Pets = new List<string>{ "Walker", "Sugar" } },
                new PetOwner { Name="Price",
                    Pets = new List<string>{ "Scratches", "Diesel" } },
                new PetOwner { Name="Hines",
                    Pets = new List<string>{ "Dusty" } } };

        // Project the pet owner's name and the pet's name.
        var query =
            petOwners
            .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
            .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
            .Select(ownerAndPet =>
                    new
                    {
                        Owner = ownerAndPet.petOwner.Name,
                        Pet = ownerAndPet.petName
                    }
            );

        // Print the results.
        foreach (var obj in query1)
        {
            Console.WriteLine(obj);
        }
    }
}

class PetOwner
{
    public string Name { get; set; }
    public List<string> Pets { get; set; }
}
</code>```

However, the var query = ... can be rewritten using the SelectMany of the first signature as following?

```<code>var query = petOwners.SelectMany(o => o.Pets.Select(p => new { petOwner = o, petName =p}))
</code>```

When will the SelectMany with the third signature be really useful?

答:
It would have been more helpful if they used the example like below. See how I added a Where clause in the SelectMany. This overload gives you the flexibility to run a query and then do a projection on the result of that query:

```<code>// Project the pet owner's name and the pet's name.
var query =
    petOwners
    .SelectMany(petOwner => petOwner.Pets.Where(x => x.StartsWith("S")), (petOwner, petName) => new { petOwner, petName })
    //.Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
    .Select(ownerAndPet =>
            new
            {
                Owner = ownerAndPet.petOwner.Name,
                Pet = ownerAndPet.petName
            }
    );
</code>```

Body:
In the link https://msdn.microsoft.com/en-us/library/bb534631(v=vs.110).aspx, the third signature is

// M<S> -> (S -> M<C>) -> (S -> M<C> -> R) -> E<R>
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TCollection>> collectionSelector,
    Func<TSource, TCollection, TResult> resultSelector
)

Shouldn't the first one which has the signature of the typical Monad bind function M -> (A -> M) -> M be enough? Isn't it easy to merge code in the resultSelector into collectionSelector?

The MSDN document gave an example to show the usage of the method.

class Program
{
    static void Main(string[] args)
    {
        SelectManyEx3();
    }
    public static void SelectManyEx3()
    {
        PetOwner[] petOwners =
            { new PetOwner { Name="Higa",
                    Pets = new List<string>{ "Scruffy", "Sam" } },
                new PetOwner { Name="Ashkenazi",
                    Pets = new List<string>{ "Walker", "Sugar" } },
                new PetOwner { Name="Price",
                    Pets = new List<string>{ "Scratches", "Diesel" } },
                new PetOwner { Name="Hines",
                    Pets = new List<string>{ "Dusty" } } };

        // Project the pet owner's name and the pet's name.
        var query =
            petOwners
            .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
            .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
            .Select(ownerAndPet =>
                    new
                    {
                        Owner = ownerAndPet.petOwner.Name,
                        Pet = ownerAndPet.petName
                    }
            );

        // Print the results.
        foreach (var obj in query1)
        {
            Console.WriteLine(obj);
        }
    }
}

class PetOwner
{
    public string Name { get; set; }
    public List<string> Pets { get; set; }
}

However, the var query = ... can be rewritten using the SelectMany of the first signature as following?

var query = petOwners.SelectMany(o => o.Pets.Select(p => new { petOwner = o, petName =p}))

When will the SelectMany with the third signature be really useful?

Body:
It would have been more helpful if they used the example like below. See how I added a Where clause in the SelectMany. This overload gives you the flexibility to run a query and then do a projection on the result of that query:

// Project the pet owner's name and the pet's name.
var query =
    petOwners
    .SelectMany(petOwner => petOwner.Pets.Where(x => x.StartsWith("S")), (petOwner, petName) => new { petOwner, petName })
    //.Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
    .Select(ownerAndPet =>
            new
            {
                Owner = ownerAndPet.petOwner.Name,
                Pet = ownerAndPet.petName
            }
    );


问:
OpenSocial gadget-to-gadget communication via gadgets.rpc
Could I have an example of communication between two OpenSocial gadgets using the gadgets.rpc API?

I've searched for one, but the closest I can find is a deprecated example of gadget-to-container communication.

答:
you can use pubsub for gadget-to-gadget communication.

on a gadget, you subscribe for an event as follows:

```<code>gadgets.pubsub.subscribe("my_event_type",whenEventHappens);
function whenEventHappens(sender, message){
      alert(message.content);
}
</code>```

on another gadget, you publish events as follows:

```<code>var message = {};
message["content"] = "hey,wassup?";
gadgets.pubsub.publish("my_event_type", message);
</code>```

Body:
you can use pubsub for gadget-to-gadget communication.

on a gadget, you subscribe for an event as follows:

gadgets.pubsub.subscribe("my_event_type",whenEventHappens);
function whenEventHappens(sender, message){
      alert(message.content);
}

on another gadget, you publish events as follows:

var message = {};
message["content"] = "hey,wassup?";
gadgets.pubsub.publish("my_event_type", message);


问:
how to add button click event in android studio
So I have done some research, and after defining you button as an object by the code

```<code>private Button buttonname;
buttonname = (Button) findViewById(R.id.buttonnameinandroid) ;
</code>```

here is my problem

```<code>buttonname.setOnClickListener(this); //as I understand it, the "**this**" denotes the current `view(focus)` in the android program
</code>```

then your OnClick() event...

Problem:

When I type in the "this", it says:

```<code>setOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)
</code>```

I have no idea why?

here is the code from the .java file

```<code>import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private Button btnClick;
    private EditText Name, Date;
    private TextView msg, NameOut, DateOut;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnClick = (Button) findViewById(R.id.button) ;
        btnClick.setOnClickListener(this);
        Name = (EditText) findViewById(R.id.textenter) ;
        Date = (EditText) findViewById(R.id.editText) ;
        msg = (TextView) findViewById(R.id.txtviewOut) ;
        NameOut = (TextView) findViewById(R.id.txtoutName) ;
        DateOut = (TextView) findViewById(R.id.txtOutDate) ;
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    public void onClick(View v)
    {
        if (v == btnClick)
        {
            if (Name.equals("") == false && Date.equals("") == false)
            {
                NameOut = Name;
                DateOut = Date;
                msg.setVisibility(View.VISIBLE);
            }
            else
            {
                msg.setText("Please complete both fields");
                msg.setVisibility(View.VISIBLE);
            }
        }
        return;

    }
</code>```

答:
Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:</p>

```<code>Button btn1 = (Button)findViewById(R.id.button1);

btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
//your stuff here.
    }
});
</code>```

Body:
So I have done some research, and after defining you button as an object by the code

private Button buttonname;
buttonname = (Button) findViewById(R.id.buttonnameinandroid) ;

here is my problem

buttonname.setOnClickListener(this); //as I understand it, the "**this**" denotes the current `view(focus)` in the android program

then your OnClick() event...

Problem:

When I type in the "this", it says:

setOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)

I have no idea why?

here is the code from the .java file

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private Button btnClick;
    private EditText Name, Date;
    private TextView msg, NameOut, DateOut;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnClick = (Button) findViewById(R.id.button) ;
        btnClick.setOnClickListener(this);
        Name = (EditText) findViewById(R.id.textenter) ;
        Date = (EditText) findViewById(R.id.editText) ;
        msg = (TextView) findViewById(R.id.txtviewOut) ;
        NameOut = (TextView) findViewById(R.id.txtoutName) ;
        DateOut = (TextView) findViewById(R.id.txtOutDate) ;
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    public void onClick(View v)
    {
        if (v == btnClick)
        {
            if (Name.equals("") == false && Date.equals("") == false)
            {
                NameOut = Name;
                DateOut = Date;
                msg.setVisibility(View.VISIBLE);
            }
            else
            {
                msg.setText("Please complete both fields");
                msg.setVisibility(View.VISIBLE);
            }
        }
        return;

    }

Body:
Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:

Button btn1 = (Button)findViewById(R.id.button1);

btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
//your stuff here.
    }
});


问:
divs height and width are not fixed in carousel slider
Visit this link for code snippet https://codepen.io/arunkayathi/pen/dRPYzz

html

```<code><html lang="en">

<head>

    <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

</head>

<body>
    <section id="projects">
        <div class="content-box">
            <div class="content-title wow animated fadeInDown" data-wow-duration="1s" data-wow-delay=".5s">
                <h3>My Projects</h3>
                <div class="content-title-underline"></div>
            </div>
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <div id="my-projects" class="owl-carousel owl-theme">
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTp1-NNfLpNtsFQY25z7A4u9pp2D_vJHTNU70RDupydx4i7BrMKYw" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit Website</a>
                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                                </div>

                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur . </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" target="_blank">visit site</a>

                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQAOoZwRkgQ3KDjCJ2-GRtjKDc88iUqU6mJva17ym63D2W0XwnYw" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,  </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit site</a>
                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.</p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#projects" role="button">Visit site</a>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <body>
</code>```

css

```<code>    #projects {
    background-color: #f65d52;
    /*    background-color: #2098D1;*/
}

#projects .content-title h3 {
    color: #fff;
}

.project-info {
    padding: 25px 0 25px 0;
    color: #fff;

}

.project-info h5 {

    font-size: 25px;
    font-weight: 700;
}

.project-image img {
    max-width: 480px !important;
    max-height: 480px !important;
    margin: 0 auto;
    object-fit: contain;
}

.project-info-text {
    line-height: 170%;
    letter-spacing: 1px;
    color: #fff !important;
    font-weight: 500;
    width: 70%;
    margin: 0 auto;
}

.project-btn {
    padding-top: 30px;
}
</code>```

js

```<code>$(document).ready(function () {
    $("#my-projects").owlCarousel({
        items: 1,
        autoplay: true,
        smartSpeed: 700,
        loop: true,
        autoplayHoverPause: true
    });

});
</code>```

Hello all,

I am having a problem with arranging divs in a carousel slider. As you can see from the above link the  position of project title in each slid is changing.So can somebody help me in fixing the width and height of each divs, so that text and images  will not overflow and in every slide all divs starts at same position instead  of going up or down.

答:
Add  responsiveClass for set all slide responsive.</p>

```<code> $(document).ready(function () {
        $("#my-projects").owlCarousel({
            items: 1,
            autoplay: true,
            smartSpeed: 700,
            loop: true,
            autoplayHoverPause: true,
            responsiveClass:true
        });

    });
</code>```

Body:
Visit this link for code snippet https://codepen.io/arunkayathi/pen/dRPYzz

html

    <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

My Projects

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                                        Visit Website

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur .

                                        visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,

                                        Visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.

                                        Visit site

css

    #projects {
    background-color: #f65d52;
    /*    background-color: #2098D1;*/
}

#projects .content-title h3 {
    color: #fff;
}

.project-info {
    padding: 25px 0 25px 0;
    color: #fff;

}

.project-info h5 {

    font-size: 25px;
    font-weight: 700;
}

.project-image img {
    max-width: 480px !important;
    max-height: 480px !important;
    margin: 0 auto;
    object-fit: contain;
}

.project-info-text {
    line-height: 170%;
    letter-spacing: 1px;
    color: #fff !important;
    font-weight: 500;
    width: 70%;
    margin: 0 auto;
}

.project-btn {
    padding-top: 30px;
}

js

$(document).ready(function () {
    $("#my-projects").owlCarousel({
        items: 1,
        autoplay: true,
        smartSpeed: 700,
        loop: true,
        autoplayHoverPause: true
    });

});

Hello all,

I am having a problem with arranging divs in a carousel slider. As you can see from the above link the  position of project title in each slid is changing.So can somebody help me in fixing the width and height of each divs, so that text and images  will not overflow and in every slide all divs starts at same position instead  of going up or down.

Body:
Add  responsiveClass for set all slide responsive.

 $(document).ready(function () {
        $("#my-projects").owlCarousel({
            items: 1,
            autoplay: true,
            smartSpeed: 700,
            loop: true,
            autoplayHoverPause: true,
            responsiveClass:true
        });

    });


问:
React Router v4 not navigating to historical pages using back/forward buttons
I'm using react-router-dom: v4.1.1, and this is my router code:

```<code>var ReactRouter = require('react-router-dom');
var Router = ReactRouter.BrowserRouter;
var Route = ReactRouter.Route;
var Switch = ReactRouter.Switch;
var browserHistory = ReactRouter.BrowserHistory;

  <Router history={browserHistory}>
    <div className='container'>
<Switch>
    <Route exact path='/' render={(props) => <Home
      {...props} // for router history and all that.
      rebase={rebase}
      items={this.state.items}
      user={this.state.currentUser}
      userData={this.state.currentUserData}/>} />
    <Route path='/browse' render={() => <Browse items={_.values(this.state.items)}/>} />
    <Route render={function () {
      return <p>Not Found</p>
    }} />
  </Switch>
</div>
  </Router>
</code>```

In the Home component I have a button which, when clicked, adds a new url to the history: this.props.history.push('/?p=' + hash) where hash is simply something like f9ojy. This 'works' in the sense that the URL in the window is updated to the new hash, but when I click 'back' or 'forward' there's no change in the displayed page.

答: Found the answer in the Reactiflux discord channel; in componentDidUpdate I can check the previous this.props.location.search and compare it against the current one. If it's not the same I have a function which resets the UI based on the current parameter.

Body:
I'm using react-router-dom: v4.1.1, and this is my router code:

var ReactRouter = require('react-router-dom');
var Router = ReactRouter.BrowserRouter;
var Route = ReactRouter.Route;
var Switch = ReactRouter.Switch;
var browserHistory = ReactRouter.BrowserHistory;

  <Router history={browserHistory}>

<Switch>
    <Route exact path='/' render={(props) => <Home
      {...props} // for router history and all that.
      rebase={rebase}
      items={this.state.items}
      user={this.state.currentUser}
      userData={this.state.currentUserData}/>} />
    <Route path='/browse' render={() => <Browse items={_.values(this.state.items)}/>} />
    <Route render={function () {
      return
Not Found

    }} />
  </Switch>

  </Router>

In the Home component I have a button which, when clicked, adds a new url to the history: this.props.history.push('/?p=' + hash) where hash is simply something like f9ojy. This 'works' in the sense that the URL in the window is updated to the new hash, but when I click 'back' or 'forward' there's no change in the displayed page.


问:
Google Maps GMSMaker iconView - iOS SDK
Error:

value of type GMSmarker has no member iconView

How can I  use iconView?

```<code>        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 13.7990609, longitude: 100.5494513)
        marker.title = "Coffee Factory"
        marker.snippet = "Chatuchak"
        marker.iconView = imageView
        marker.map = mapView
</code>```

答:
you can try </p>

```<code>    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: restaurant.latitude, longitude: restaurant.longitude)
   marker.title = restaurant.name
 marker.icon = xyz
</code>```

Title: Google Maps GMSMaker iconView - iOS SDK

Body:
Error:

value of type GMSmarker has no member iconView

How can I  use iconView?

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 13.7990609, longitude: 100.5494513)
        marker.title = "Coffee Factory"
        marker.snippet = "Chatuchak"
        marker.iconView = imageView
        marker.map = mapView

Body:
you can try

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: restaurant.latitude, longitude: restaurant.longitude)
   marker.title = restaurant.name
 marker.icon = xyz


问:
how to make progress bar work with functions in button event
i am new in C# so please be patient with me .

i want to make progress bar work with any functions i make in my program

i have class to check if INTERNET available and the connection of database status

and i have "progressBar1" , style is "Marquee"

i just want to indicate that there is a process work "Function" in the program and i don't need to have step or timer to increment it

just make the progress work until the function finish its code and the functions will work in button event (when i push button)

this is my code

```<code>class checkInternet
{
    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

public bool checkInternetAvailable()
{
    int Desc;
    bool result = false;

    if (InternetGetConnectedState(out Desc, 0) == true)
    {
        try
        {
            dbConnection StartConn = new dbConnection();
            SqlConnection MyConnetion = StartConn.GetConnection();

            MyConnetion.Open();

            if (MyConnetion.State == ConnectionState.Open)
            {
                result = true;
            }

            MyConnetion.Close();
        }
        catch (Exception)
        {
            result = false;
            MessageBox.Show("The database connection does not available, May be because of this reasons: \n\n1- there is a new version of the program avalible. \n2- database has some maintenance. \n\n Please check later :)", "Conection status");
        }
    }
    else
    {
        result = false;
        MessageBox.Show("No internet connection avalible , Please check later :) \nThanks.", "Conection status");
    }

    return result;
}
}
</code>```

and this is what i have in my button event

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        checkInternet check = new checkInternet();

        progressBar1.Value = 0;
        do
        {
            progressBar1.PerformStep();

        } while (check.checkInternetAvailable());
    }
</code>```

how can i implement that ?

thanks

答:
As I understand you want user to see progressbar while your check connection task executes in background. checkInternetAvailable would be your background operation and I wouldn't suggest showing messages directly form it. Instead return a custom struct :

```<code>   public struct ConnectionCheckResult
   {
       public bool Success;
       public string Message;
   }
</code>```

And this will be your button click event handler :

```<code>private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Style = ProgressBarStyle.Marquee;
            progressBar1.Visible = true;
            //add code here to be executed on UI thread before connection check
            Task.Run(new Action(() =>
            {
                //Task.Run this code on the thread pool instead of your UI thread. So your code is checking connection while progress bar is still rendering
                ConnectionCheckResult res = new checkInternet().checkInternetAvailable();
                this.Invoke(new Action(() =>
                {
                    //this.Invoke executes following delegate on UI thread. All UI changes - like progressBar1.Visible = false; need to be made in UI thread.
                    //add code here to be executed on the UI thread after connection check.
                    progressBar1.Visible = false;
                    if (!string.IsNullOrEmpty(res.Message))
                        MessageBox.Show(res.Message);

                }));

            }));
            //add code to be executed on UI thread at the same time as connection check
        }
</code>```

I know multi-threading is difficult to wrap your head around at first, here's good tutorial with code samples.

Also when your progressbar style is Marquee you don't need to call PerformStep. It will just roll by itself.

EDIT: You should also modify checkInternetAvailable() like so :

```<code>public ConnectionCheckResult checkInternetAvailable()
{
    int Desc;
    ConnectionCheckResult result = new ConnectionCheckResult();

    if (InternetGetConnectedState(out Desc, 0) == true)
    {
        try
        {
            dbConnection StartConn = new dbConnection();
            SqlConnection MyConnetion = StartConn.GetConnection();

            MyConnetion.Open();

            if (MyConnetion.State == ConnectionState.Open)
            {
                result.Success = true;
            }

            MyConnetion.Close();
        }
        catch (Exception)
        {
            result.Success = false;
            result.Message = "The database connection does not available, May be because of this reasons: \n\n1- there is a new version of the program available. \n2- database has some maintenance. \n\n Please check later :)";
        }
    }
    else
    {
        result.Success = false;
        result.Message = "No internet connection available , Please check later :) \nThanks.";
    }

    return result;
}
</code>```

Body:
i am new in C# so please be patient with me .

i want to make progress bar work with any functions i make in my program

i have class to check if INTERNET available and the connection of database status

and i have "progressBar1" , style is "Marquee"

i just want to indicate that there is a process work "Function" in the program and i don't need to have step or timer to increment it

just make the progress work until the function finish its code and the functions will work in button event (when i push button)

this is my code

class checkInternet
{
    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

public bool checkInternetAvailable()
{
    int Desc;
    bool result = false;

    if (InternetGetConnectedState(out Desc, 0) == true)
    {
        try
        {
            dbConnection StartConn = new dbConnection();
            SqlConnection MyConnetion = StartConn.GetConnection();

            MyConnetion.Open();

            if (MyConnetion.State == ConnectionState.Open)
            {
                result = true;
            }

            MyConnetion.Close();
        }
        catch (Exception)
        {
            result = false;
            MessageBox.Show("The database connection does not available, May be because of this reasons: \n\n1- there is a new version of the program avalible. \n2- database has some maintenance. \n\n Please check later :)", "Conection status");
        }
    }
    else
    {
        result = false;
        MessageBox.Show("No internet connection avalible , Please check later :) \nThanks.", "Conection status");
    }

    return result;
}
}

and this is what i have in my button event

    private void button1_Click(object sender, EventArgs e)
    {
        checkInternet check = new checkInternet();

        progressBar1.Value = 0;
        do
        {
            progressBar1.PerformStep();

        } while (check.checkInternetAvailable());
    }

how can i implement that ?

thanks

Body:
As I understand you want user to see progressbar while your check connection task executes in background. checkInternetAvailable would be your background operation and I wouldn't suggest showing messages directly form it. Instead return a custom struct :

   public struct ConnectionCheckResult
   {
       public bool Success;
       public string Message;
   }

And this will be your button click event handler :

private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Style = ProgressBarStyle.Marquee;
            progressBar1.Visible = true;
            //add code here to be executed on UI thread before connection check
            Task.Run(new Action(() =>
            {
                //Task.Run this code on the thread pool instead of your UI thread. So your code is checking connection while progress bar is still rendering
                ConnectionCheckResult res = new checkInternet().checkInternetAvailable();
                this.Invoke(new Action(() =>
                {
                    //this.Invoke executes following delegate on UI thread. All UI changes - like progressBar1.Visible = false; need to be made in UI thread.
                    //add code here to be executed on the UI thread after connection check.
                    progressBar1.Visible = false;
                    if (!string.IsNullOrEmpty(res.Message))
                        MessageBox.Show(res.Message);

                }));

            }));
            //add code to be executed on UI thread at the same time as connection check
        }

I know multi-threading is difficult to wrap your head around at first, here's good tutorial with code samples.

Also when your progressbar style is Marquee you don't need to call PerformStep. It will just roll by itself.

EDIT: You should also modify checkInternetAvailable() like so :

public ConnectionCheckResult checkInternetAvailable()
{
    int Desc;
    ConnectionCheckResult result = new ConnectionCheckResult();

    if (InternetGetConnectedState(out Desc, 0) == true)
    {
        try
        {
            dbConnection StartConn = new dbConnection();
            SqlConnection MyConnetion = StartConn.GetConnection();

            MyConnetion.Open();

            if (MyConnetion.State == ConnectionState.Open)
            {
                result.Success = true;
            }

            MyConnetion.Close();
        }
        catch (Exception)
        {
            result.Success = false;
            result.Message = "The database connection does not available, May be because of this reasons: \n\n1- there is a new version of the program available. \n2- database has some maintenance. \n\n Please check later :)";
        }
    }
    else
    {
        result.Success = false;
        result.Message = "No internet connection available , Please check later :) \nThanks.";
    }

    return result;
}


问:
What is the best way of showing progress on an Ajax call?
I have an Ajax call that updates 5,000 records in a database so this takes a lot of time.  I have an Ajax "Loading image" showing that something is happening, but I am looking for a better way to show "Updating  50 of 5000 . . .", "Updating 200 of 5000", or something like that.

What is the best way to do something like this in Ajax / jQuery without doing 5000 different posts?

答:
For showing progress during load, I would modify my backend so that it can do selective loading.

For example,

```<code>var total_rec = 5000;
var load_steps = 20;
var per_load = total_rev / load_steps;
var loaded = 0;
while (loaded < total_rec) {
    www.foobar.com/api.php?start=loaded&end=(loaded+per_load);
    loaded += per_load;
}
</code>```

Every time the load is done, update the progress bar.

An alternative way to modify the backend can be

```<code>www.foobar.com/api.php?start=loaded&count=50
</code>```

Body:
For showing progress during load, I would modify my backend so that it can do selective loading.

For example,

var total_rec = 5000;
var load_steps = 20;
var per_load = total_rev / load_steps;
var loaded = 0;
while (loaded < total_rec) {
    www.foobar.com/api.php?start=loaded&end=(loaded+per_load);
    loaded += per_load;
}

Every time the load is done, update the progress bar.

An alternative way to modify the backend can be

www.foobar.com/api.php?start=loaded&count=50