问:
Unhandled promise rejection: Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten
I have tried to incorporate the Angular2 quickstart code into my current webpack build and it seems that something is overwriting the zone.js promise which is throwing this error. According to most of the stackoverflow posts I've seen, the zone.js file needs to be loaded after any files that may include promises.

I'm assuming what is happening is that the html that has the <src> tag with the zone.js file is getting loaded before webpack loads the rest of the node_module files.

Any ideas or suggestions?

This is the package.json I'm using.

```<code>{
  "name": "site-pinger",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build:watch": "webpack --colors --progress --watch",
    "build": "webpack --colors --progress",
    "start": "webpack-dev-server --progress --colors --hot --inline --port 3000"
  },
  "author": "",
  "license": "ISC",
  "standard": {
    "parser": "babel-eslint"
  },
  "babel": {
    "presets": [
      "latest",
      "stage-0"
    ]
  },
  "devDependencies": {
    "@types/jasmine": "2.5.36",
    "@types/node": "^6.0.46",
    "babel-core": "^6.17.0",
    "babel-eslint": "^7.0.0",
    "babel-loader": "^6.2.5",
    "babel-polyfill": "^6.16.0",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "canonical-path": "0.0.2",
    "concurrently": "^3.2.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.5",
    "html-webpack-plugin": "^2.28.0",
    "jasmine-core": "~2.4.1",
    "json-loader": "^0.5.4",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "lodash": "^4.16.4",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "standard": "^8.4.0",
    "style-loader": "^0.13.2",
    "ts-loader": "^2.0.1",
    "tslint": "^3.15.1",
    "typescript": "~2.0.10",
    "url-loader": "^0.5.8",
    "webpack": "^2.1.0",
    "webpack-dev-server": "^2.4.1"
  },
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.4",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4"
  },
  "repository": {}
}
</code>```

This is the webpack.config.js file

```<code>'use strict'

const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const devtool = 'source-map'

const devServer = {
  historyApiFallback: true
}

const entry = {
  main: [
    'babel-polyfill',
    './src/main'
  ],
}

const output = {
  filename: '[name].js',
  path: __dirname + '/dist',
  publicPath: '/'
}

const extensions = [
  '.js',
  '.ts',
  '.css',
  '.html'
]

const modules = [
  'node_modules',
  'lib'
]

const rules = [{
  test: /.ts$/,
  exclude: /node_modules/,
  loaders: ['ts-loader']
}, {
  test: /.js$/,
  exclude: /node_modules/,
  loaders: ['babel-loader']
}, {
  test: /.css$/,
  loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' })
}, {
  test: /.html$/,
  exclude: /node_modules/,
  include: /static/,
  loader: 'html-loader'
}, {
  test: /.(ico|png|eot|svg|ttf|woff|woff2)$/,
  loader: 'url?limit=10000'
}]

const plugins = [
  new ExtractTextPlugin('[name].css'),
  new HtmlWebpackPlugin({
    hash: true,
    inject: 'head',
    template: 'static/index.html'
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks: Infinity
  })
]

module.exports = {
  devtool,
  devServer,
  entry,
  output,
  resolve: {
    extensions,
    modules
  },
  module: {
    rules
  },
  plugins
}
</code>```

This is my index.html where I've manually included the zone.js file to ensure that their Promise doesn't get overwritten.

```<code><!doctype html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Site Pinger</title>

    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="../src/systemjs.config.js"></script>
  </head>

  <body>
    <app>Loading AppComponent content here ...</app>
  </body>
</html>
</code>```

答:
I had a similar error when loading core-js and zone.js.
What did the trick for me was to just put the import for zone.js after core-js.

Changed this:

```<code>import 'zone.js/dist/zone';
import 'core-js';
</code>```

to this:

```<code>import 'core-js';
import 'zone.js/dist/zone';
</code>```

Going back to your webpack problem, as @estus said, there is no need to put  the systemjs import there, as it will be included in your dist/* files generated by webpack (which are missing in your index.html).

My index.html after "webpacking" my project looks like:

```<code><html>
  <head>
    <!-- only some css links here -->
  </head>
  <body>
    <my-app>
    </my-app>

    <script src="dist/vendor.bundle.min.js"></script>
    <script src="dist/app.bundle.min.js"></script>
  </body>
</html>
</code>```

Hope it helps.

Body:
I have tried to incorporate the Angular2 quickstart code into my current webpack build and it seems that something is overwriting the zone.js promise which is throwing this error. According to most of the stackoverflow posts I've seen, the zone.js file needs to be loaded after any files that may include promises.

I'm assuming what is happening is that the html that has the <src> tag with the zone.js file is getting loaded before webpack loads the rest of the node_module files.

Any ideas or suggestions?

This is the package.json I'm using.

{
  "name": "site-pinger",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build:watch": "webpack --colors --progress --watch",
    "build": "webpack --colors --progress",
    "start": "webpack-dev-server --progress --colors --hot --inline --port 3000"
  },
  "author": "",
  "license": "ISC",
  "standard": {
    "parser": "babel-eslint"
  },
  "babel": {
    "presets": [
      "latest",
      "stage-0"
    ]
  },
  "devDependencies": {
    "@types/jasmine": "2.5.36",
    "@types/node": "^6.0.46",
    "babel-core": "^6.17.0",
    "babel-eslint": "^7.0.0",
    "babel-loader": "^6.2.5",
    "babel-polyfill": "^6.16.0",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "canonical-path": "0.0.2",
    "concurrently": "^3.2.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.5",
    "html-webpack-plugin": "^2.28.0",
    "jasmine-core": "~2.4.1",
    "json-loader": "^0.5.4",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "lodash": "^4.16.4",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "standard": "^8.4.0",
    "style-loader": "^0.13.2",
    "ts-loader": "^2.0.1",
    "tslint": "^3.15.1",
    "typescript": "~2.0.10",
    "url-loader": "^0.5.8",
    "webpack": "^2.1.0",
    "webpack-dev-server": "^2.4.1"
  },
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.4",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4"
  },
  "repository": {}
}

This is the webpack.config.js file

'use strict'

const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const devtool = 'source-map'

const devServer = {
  historyApiFallback: true
}

const entry = {
  main: [
    'babel-polyfill',
    './src/main'
  ],
}

const output = {
  filename: '[name].js',
  path: __dirname + '/dist',
  publicPath: '/'
}

const extensions = [
  '.js',
  '.ts',
  '.css',
  '.html'
]

const modules = [
  'node_modules',
  'lib'
]

const rules = [{
  test: /.ts$/,
  exclude: /node_modules/,
  loaders: ['ts-loader']
}, {
  test: /.js$/,
  exclude: /node_modules/,
  loaders: ['babel-loader']
}, {
  test: /.css$/,
  loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' })
}, {
  test: /.html$/,
  exclude: /node_modules/,
  include: /static/,
  loader: 'html-loader'
}, {
  test: /.(ico|png|eot|svg|ttf|woff|woff2)$/,
  loader: 'url?limit=10000'
}]

const plugins = [
  new ExtractTextPlugin('[name].css'),
  new HtmlWebpackPlugin({
    hash: true,
    inject: 'head',
    template: 'static/index.html'
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks: Infinity
  })
]

module.exports = {
  devtool,
  devServer,
  entry,
  output,
  resolve: {
    extensions,
    modules
  },
  module: {
    rules
  },
  plugins
}

This is my index.html where I've manually included the zone.js file to ensure that their Promise doesn't get overwritten.

<!doctype html>

    <meta charset="utf-8">
    <title>Site Pinger</title>

    <app>Loading AppComponent content here ...</app>

Body:
I had a similar error when loading core-js and zone.js.
What did the trick for me was to just put the import for zone.js after core-js.

Changed this:

import 'zone.js/dist/zone';
import 'core-js';

to this:

import 'core-js';
import 'zone.js/dist/zone';

Going back to your webpack problem, as @estus said, there is no need to put  the systemjs import there, as it will be included in your dist/* files generated by webpack (which are missing in your index.html).

My index.html after "webpacking" my project looks like:

<html>
  <head>
    <!-- only some css links here -->
  </head>
  <body>
    <my-app>
    </my-app>

    <script src="dist/vendor.bundle.min.js"></script>
    <script src="dist/app.bundle.min.js"></script>
  </body>
</html>

Hope it helps.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?
I'm getting the following error in SSRS:

An error occurred while the query design method was being saved.

An item with the same key has already been added

What does an "item" denote, though? I even tried editing the RDL and deleting all references to  the Stored Procedure I need to use called prc_RPT_Select_BI_Completes_Data_View.

Could this possibly have to do with the fact that the Stored Procedure uses Dynamic SQL (the N'  notation)?

In the stored procedure I have:

```<code>SET @SQL +=  N'
SELECT   bi.SupplierID as ''Supplier ID''
        ,bi.SupplierName as ''Supplier Name''

        ,bi.PID as ''PID''
        ,bi.RespondentID as ''Respondent ID''

        ,lk_slt.Name as ''Entry Link Type''

        ,ts.SurveyNumber as ''Initial Survey ID'''
</code>```

答:
I just got this error and i came to know that it is about the local variable alias

at the end of the stored procedure i had like

```<code>select @localvariable1,@localvariable2
</code>```

it was working fine in sql but when i ran this in ssrs
it was always throwing error but after I gave alias it is fixed

```<code>select @localvariable1 as A,@localvariable2 as B
</code>```

Body:
I'm getting the following error in SSRS:

An error occurred while the query design method was being saved.

An item with the same key has already been added

What does an "item" denote, though? I even tried editing the RDL and deleting all references to  the Stored Procedure I need to use called prc_RPT_Select_BI_Completes_Data_View.

Could this possibly have to do with the fact that the Stored Procedure uses Dynamic SQL (the N'  notation)?

In the stored procedure I have:

SET @SQL +=  N'
SELECT   bi.SupplierID as ''Supplier ID''
        ,bi.SupplierName as ''Supplier Name''

        ,bi.PID as ''PID''
        ,bi.RespondentID as ''Respondent ID''

        ,lk_slt.Name as ''Entry Link Type''

        ,ts.SurveyNumber as ''Initial Survey ID'''

Body:
I just got this error and i came to know that it is about the local variable alias

at the end of the stored procedure i had like

select @localvariable1,@localvariable2

it was working fine in sql but when i ran this in ssrs
it was always throwing error but after I gave alias it is fixed

select @localvariable1 as A,@localvariable2 as B

ContentLicense: CC BY-SA 3.0


问:
Python - how to use few times the same next iteration?
I would like to search a list:

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

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

```<code>x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)
</code>```

We know the previous item, the next item and the current item.

But everytime I use:

```
if i != prev and <b>i != next(hiter)</b>...
```

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

答:
You're making this too complicated on yourself. Instead, just read x multiple times within your loop:

```<code>for idx in range(1, len(x)-1): # Consider using enumerate, it's a great idea
    curr = x[idx]
    prev = x[idx - 1]
    nxt = x[idx + 1]
    if (curr != prev) and (curr != nxt):
        print('prev %s - CURRENT %s - next %s' % (prev, curr, nxt))
</code>```

Body:
I would like to search a list:

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

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)

We know the previous item, the next item and the current item.

But everytime I use:

if i != prev and i != next(hiter)...

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

Body:
You're making this too complicated on yourself. Instead, just read x multiple times within your loop:

for idx in range(1, len(x)-1): # Consider using enumerate, it's a great idea
    curr = x[idx]
    prev = x[idx - 1]
    nxt = x[idx + 1]
    if (curr != prev) and (curr != nxt):
        print('prev %s - CURRENT %s - next %s' % (prev, curr, nxt))


问:
Div not inline when window gets smaller?
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

答:
You can use a table instead of the .center div, and give it the following styles:

```<code>table {
  width: 100%;
  text-align: center;
}
td {
  width: 20%; /* This is 100/the number of <td>'s you have in the table. */
}
</code>```

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}
table {
  width: 100%;
  text-align: center;
}
td {
  width: 20%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <table>
    <tr>
      <td>
        <div id="bg01" class="bg01Off">
        </div>
      </td>
      <td>
        <div id="bg02" class="bg02Off">
        </div>
      </td>
      <td>
        <div id="bg03" class="bg03Off">
        </div>
      </td>
      <td>
        <div id="bg04" class="bg04Off">
        </div>
      </td>
      <td>
        <div id="bg05" class="bg05Off">
        </div>
      </td>
    </tr>
  </table></code>```

Body:
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

Colour

Body:
You can use a table instead of the .center div, and give it the following styles:

table {
  width: 100%;
  text-align: center;
}
td {
  width: 20%; /* This is 100/the number of <td>'s you have in the table. */
}

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}
table {
  width: 100%;
  text-align: center;
}
td {
  width: 20%;
}

<div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <table>
    <tr>
      <td>
        <div id="bg01" class="bg01Off">
        </div>
      </td>
      <td>
        <div id="bg02" class="bg02Off">
        </div>
      </td>
      <td>
        <div id="bg03" class="bg03Off">
        </div>
      </td>
      <td>
        <div id="bg04" class="bg04Off">
        </div>
      </td>
      <td>
        <div id="bg05" class="bg05Off">
        </div>
      </td>
    </tr>
  </table>


问:
Azure autoscale scale in kills in use instances
I'm using Azure Autoscale feature to process hundreds of files. The system scales up correctly to 8 instances and each instance processes one file at a time.

The problem is with scaling in. Because the scale in rules seem to be based on ALL instances, if I tell it to reduce the instance count back to 1 after an average CPU load of < 25% it will arbitrarily kill instances that are still processing data.

Is there a way to prevent it from shutting down individual instances that are still in use?

答:
Scale down will remove the highest instance numbers first.  For example, if you have WorkerRole_IN_0, WorkerRole_IN_1, ..., WorkerRole_IN_8, and then you scale down by 1, Azure will remove WorkerRole_IN_8 first.  Azure has no idea what your code is doing (ie. if it is still processing a file) or if it is finished and ready to shut down.

You have a few options:

If the file processing is quick, you can delay the shutdown for up to 5 minutes in the OnStop event, giving your instance enough time to finish processing the file.  This is the easiest solution to implement, but not the most reliable.

If processing the file can be broken up into shorter chunks of work then you can have the instances process chunks until the file is complete.  This way it doesn't really matter if an arbitrary instance is shut down since you don't lose any significant amount of work and another instance will pick up where it left off.  See https://learn.microsoft.com/en-us/azure/architecture/patterns/pipes-and-filters for a pattern.  This is the ideal solution as it is an optimized architecture for distributed workloads, but some workloads (ie. image/video processing) may not be able to break up easily.

You can implement your own autoscale algorithm and manually shut down individual instances that you choose.  To do this you would call the Delete Role Instance API (https://msdn.microsoft.com/en-us/library/azure/dn469418.aspx).  This requires some external process to be monitoring your workload and executing management operations so may not be a good solution depending on your infrastructure.


问:
How to post objects in ViewModel?
I've got this viewmodel class with an integer Id and an object type.

```<code>public class MyViewModel
{
    [Required]
    public int MyId { get; set; }

    public MyObject MyObject { get; set; }
}
</code>```

MyObject Model is:

```<code>public class MyObject
{
    [Key]
    public int ObjId { get; set; }

    public int Number { get; set; }
    public string Name { get; set; }

}
</code>```

This controller:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}
</code>```

The view is:

```<code>@model MyProject.Models.MyViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        @Html.LabelFor(model => model.MyId , htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("MyId", null, "Select", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.MyId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.MyObject.Number, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.MyObject.Number, new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Number, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.MyObject.Name , htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.MyObject.Name , new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Name , "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" formaction="@Url.Action("Create")" />
        </div>
    </div>
}
</code>```

When I post data to controller, it recognize the MyId value but don't fill MyObject parameter. Any suggests to how to post an object with ViewModel?

答:
Try below:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId,MyObject, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
}
</code>```

You aren't including MyObject in Bind(include)

Title: How to post objects in ViewModel?

Body:
I've got this viewmodel class with an integer Id and an object type.

public class MyViewModel
{
    [Required]
    public int MyId { get; set; }

    public MyObject MyObject { get; set; }
}

MyObject Model is:

public class MyObject
{
    [Key]
    public int ObjId { get; set; }

    public int Number { get; set; }
    public string Name { get; set; }

}

This controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}

The view is:

@model MyProject.Models.MyViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

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

            @Html.DropDownList("MyId", null, "Select", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.MyId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.MyObject.Number, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.TextBoxFor(model => model.MyObject.Number, new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Number, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.MyObject.Name , htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.TextBoxFor(model => model.MyObject.Name , new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Name , "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" formaction="@Url.Action("Create")" />

}

When I post data to controller, it recognize the MyId value but don't fill MyObject parameter. Any suggests to how to post an object with ViewModel?

Body:
Try below:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId,MyObject, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
}

You aren't including MyObject in Bind(include)


问:
BST, finding next highest node
In BST, according to Programming Interviews Exposed

"Given a node, you can even find the next highest node in O(log(n)) time" Pg 65

A node in BST has right child as the next highest node, then why O(log(n))? Please correct

First answer the question, then negate it

答:
I think, We can find the next highest node by simply finding the Inorder Successor of the node.

Steps -

Firstly, go to the right child of the node.

Then move as left as possible. When you reach the leaf node, print that leaf node as that node is your next highest node compared to the given node.

Title: BST, finding next highest node


问:
Aggregate question on entites
I have two entities Publisher and ReferralOffer. An offer is active for only period of time say 2 months. Publisher who bring another person as Refferal gets money which described for that offer. One publisher can bring as many person as he can for a particular offer. After some period that offer expires and new one is generated.

1 ) Now the question is Publisher is my root aggregate, but is refferaloffer is part of Publisher aggregate. or refferaloffer is separate aggregate.

2) Is refferaloffer is value object.

3) how do i create class where refferedTo And refeeredBy can be maintain.

答:
I read wiki article about referral marketing, but that's not enough for me to understand Your business.

What's a referral offer in Your case?

What kind of problems You are trying to solve? Aim of Your application?

Is referral offer publisher specific?

Can more than one publisher bring persons for one particular referral offer?

Will try to reflect some ideas in code.

Keep in mind - I have little knowledge of business domain.

Omitting/ignoring huge amount of details (e.g. technical difficulties that might arise or even domain related things like when referral becomes a publisher).

But hopefully - that might give You some ideas.

```<code> public class Publisher:Root{}

/*
 I believe it's a root, because multiple publishers can
 bring referrals to one particular referral offer

 it could be modeled as entity if offers were given for
 publishers individually

 it's certainly not a value object, because we care about identity
 of particular offer disregarding it's state.

 I'm ignoring possibility that there might be various incentives
 with common structure/behavior
*/
public class ReferralOffer:Root{
 public bool IsActive(){
  return _startedOn.AddMonths(-_lengthInMonths)>DateTime.Now;
 }
 public void BringReferral(string referralName, Publisher boughtBy){
  if (IsActive()) _referrals.Add(new Referral(referralName,boughtBy));
 }
 private List<Referral> _referrals;
 public void SendBucksToLuckyBastards(IMoneyTransferService mts){
  if (!IsActive()&&!_awardsSent){
    _referrals.SelectMany(r=>r.BoughtBy)
     .ForEach(p=>mts.SendToPublisher(p,_award));
    _awardsSent=true;
   }
 }
 public ReferralOffer(Money award, int lengthInMonths){
  _award=award;
  _lengthInMonths=lengthInMonths;
  _startedOn=DateTime.Now;
 }
 //assuming it's amount for each referral and not total
 private Money _award;
 private int _lengthInMonths;
 private DateTime _startedOn;
 private bool _awardsSent;
}

/*
 referral - person who is bought by publisher and who eventually
 might become a publisher

 if referral automatically becomes a publisher - likely this should
 be modeled otherwise

 entity, because it makes no sense w/o referral offer
*/
public class Referral:Entity{
 public Publisher BoughtBy{get; private set;}
 public string Name{get; private set;}
 //internal, because only offer constructs them
 internal Referral(string name,Publisher boughtBy){
  BoughtBy=boughtBy;
  Name=name;
 }
}

var me=publisherRepository.ByFullName("Arnis Lapsa");
var offer=new ReferralOffer(200,2);
offer.BringReferral(me, "kamal");
//two months later
offer.SendBucksToLuckyBastards(moneyTransferService);
</code>```

Keep in mind - this code is just to assist You. It's far from good.

Try to understand code thoroughly and see implications every line of code makes.

P.s. criticism is welcome as usual

ContentLicense: CC BY-SA 2.5

Title: Aggregate question on entites

Body:
I read wiki article about referral marketing, but that's not enough for me to understand Your business.

What's a referral offer in Your case?

What kind of problems You are trying to solve? Aim of Your application?

Is referral offer publisher specific?

Can more than one publisher bring persons for one particular referral offer?

Will try to reflect some ideas in code.

Keep in mind - I have little knowledge of business domain.

Omitting/ignoring huge amount of details (e.g. technical difficulties that might arise or even domain related things like when referral becomes a publisher).

But hopefully - that might give You some ideas.

 public class Publisher:Root{}

/*
 I believe it's a root, because multiple publishers can
 bring referrals to one particular referral offer

 it could be modeled as entity if offers were given for
 publishers individually

 it's certainly not a value object, because we care about identity
 of particular offer disregarding it's state.

 I'm ignoring possibility that there might be various incentives
 with common structure/behavior
*/
public class ReferralOffer:Root{
 public bool IsActive(){
  return _startedOn.AddMonths(-_lengthInMonths)>DateTime.Now;
 }
 public void BringReferral(string referralName, Publisher boughtBy){
  if (IsActive()) _referrals.Add(new Referral(referralName,boughtBy));
 }
 private List<Referral> _referrals;
 public void SendBucksToLuckyBastards(IMoneyTransferService mts){
  if (!IsActive()&&!_awardsSent){
    _referrals.SelectMany(r=>r.BoughtBy)
     .ForEach(p=>mts.SendToPublisher(p,_award));
    _awardsSent=true;
   }
 }
 public ReferralOffer(Money award, int lengthInMonths){
  _award=award;
  _lengthInMonths=lengthInMonths;
  _startedOn=DateTime.Now;
 }
 //assuming it's amount for each referral and not total
 private Money _award;
 private int _lengthInMonths;
 private DateTime _startedOn;
 private bool _awardsSent;
}

/*
 referral - person who is bought by publisher and who eventually
 might become a publisher

 if referral automatically becomes a publisher - likely this should
 be modeled otherwise

 entity, because it makes no sense w/o referral offer
*/
public class Referral:Entity{
 public Publisher BoughtBy{get; private set;}
 public string Name{get; private set;}
 //internal, because only offer constructs them
 internal Referral(string name,Publisher boughtBy){
  BoughtBy=boughtBy;
  Name=name;
 }
}

var me=publisherRepository.ByFullName("Arnis Lapsa");
var offer=new ReferralOffer(200,2);
offer.BringReferral(me, "kamal");
//two months later
offer.SendBucksToLuckyBastards(moneyTransferService);

Keep in mind - this code is just to assist You. It's far from good.

Try to understand code thoroughly and see implications every line of code makes.

P.s. criticism is welcome as usual


问:
android: volley keeps retrying when receiving 403 code
I also modified the Retry policy but it isn't working. here's the code:

```<code>JsonObjectRequest getReq = new JsonObjectRequest(Request.Method.GET, GET_URL, null,

              new Response.Listener<JSONObject>() {
                  @Override
                  public void onResponse(JSONObject response) {
                     //bluh..

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Authorization", token);
                return headers;
            }
        };getReq.setRetryPolicy(new DefaultRetryPolicy(
                    0,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(getReq);
</code>```

sometimes it retrys up to 6 times. how can I prevent that?

答:
Problem is in "BasicNetwork" class (see commented out block)

```<code>  if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents,
                        responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
//                    if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
//                            statusCode == HttpStatus.SC_FORBIDDEN) {
//                        attemptRetryOnException("auth",
//                                request, new AuthFailureError(networkResponse));
//                    } else
                        {
                        // TODO: Only throw ServerError for 5xx status codes.
                        throw new ServerError(networkResponse);
                    }
                } else {
                    throw new NetworkError(networkResponse);
                }
</code>```

This implementation violates RFC and caused huge server traffic in my case!

Body:
I also modified the Retry policy but it isn't working. here's the code:

JsonObjectRequest getReq = new JsonObjectRequest(Request.Method.GET, GET_URL, null,

              new Response.Listener<JSONObject>() {
                  @Override
                  public void onResponse(JSONObject response) {
                     //bluh..

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Authorization", token);
                return headers;
            }
        };getReq.setRetryPolicy(new DefaultRetryPolicy(
                    0,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(getReq);

sometimes it retrys up to 6 times. how can I prevent that?

Body:
Problem is in "BasicNetwork" class (see commented out block)

  if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents,
                        responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
//                    if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
//                            statusCode == HttpStatus.SC_FORBIDDEN) {
//                        attemptRetryOnException("auth",
//                                request, new AuthFailureError(networkResponse));
//                    } else
                        {
                        // TODO: Only throw ServerError for 5xx status codes.
                        throw new ServerError(networkResponse);
                    }
                } else {
                    throw new NetworkError(networkResponse);
                }

This implementation violates RFC and caused huge server traffic in my case!


问:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)
having problems with the code mentioned below. the eclipse error code is as follows ::

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)

Any recommendations would be very much appreciated? I have have been pulling my hair out for almost one hour trying to figure out what the problem is..

```<code>private JPanel contentPane;
private JFileChooser fileChooser;
private PassengerController controller;
private PassengerTabelPanel tabelPanel;
private JTextField nameField;
private JTextField cityField;
private JTable passengerTable;
private JRadioButton  standardRadio;
private JRadioButton businessRadio;
private ButtonGroup classGroup;
private PassengerFormListener formListener;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                PassengerGui frame = new PassengerGui();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public PassengerGui() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 584, 368);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenuItem importDataItem = new JMenuItem("Import Data");
    menuBar.add(importDataItem);

    JMenuItem exportDataItem = new JMenuItem("Export Data");
    menuBar.add(exportDataItem);

    fileChooser = new JFileChooser();
    fileChooser.addChoosableFileFilter(new PassengerFileFilter());
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    classGroup = new ButtonGroup();

    //set up class radio

            classGroup.add(standardRadio);
            classGroup.add(businessRadio);

    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    nameLabel.setBounds(12, 11, 69, 31);
    contentPane.add(nameLabel);

    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    cityLabel.setBounds(12, 47, 69, 31);
    contentPane.add(cityLabel);

    JLabel lblNewLabel_2 = new JLabel("Class: ");
    lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblNewLabel_2.setBounds(12, 89, 69, 31);
    contentPane.add(lblNewLabel_2);

    nameField = new JTextField();
    nameField.setBounds(60, 18, 129, 20);
    contentPane.add(nameField);
    nameField.setColumns(10);

    cityField = new JTextField();
    cityField.setColumns(10);
    cityField.setBounds(60, 53, 129, 20);
    contentPane.add(cityField);

    JRadioButton businessRadio = new JRadioButton("Business");
    businessRadio.setBounds(58, 95, 109, 23);
    contentPane.add(businessRadio);

    JRadioButton standardRadio = new JRadioButton("Standard");
    standardRadio.setBounds(60, 127, 109, 23);
    contentPane.add(standardRadio);

    JButton btnSubmit = new JButton("Submit");
    btnSubmit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String city = cityField.getText();
            String passengerClass = classGroup.getSelection().getActionCommand();

            PassengerFormEvent ev = new PassengerFormEvent(this, name, passengerClass, city);
</code>```

答:
You are not instantiating classGroup.  You need code such as:-

```<code>classGroup = new ButtonGroup();
</code>```

before you can call methods on classGroup.

EDIT: In answer to the second problem, it's because the buttons you've added to the buttonGroup are also null. You need to create them before you add them.

Body:
having problems with the code mentioned below. the eclipse error code is as follows ::

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)

Any recommendations would be very much appreciated? I have have been pulling my hair out for almost one hour trying to figure out what the problem is..

private JPanel contentPane;
private JFileChooser fileChooser;
private PassengerController controller;
private PassengerTabelPanel tabelPanel;
private JTextField nameField;
private JTextField cityField;
private JTable passengerTable;
private JRadioButton  standardRadio;
private JRadioButton businessRadio;
private ButtonGroup classGroup;
private PassengerFormListener formListener;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                PassengerGui frame = new PassengerGui();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public PassengerGui() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 584, 368);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenuItem importDataItem = new JMenuItem("Import Data");
    menuBar.add(importDataItem);

    JMenuItem exportDataItem = new JMenuItem("Export Data");
    menuBar.add(exportDataItem);

    fileChooser = new JFileChooser();
    fileChooser.addChoosableFileFilter(new PassengerFileFilter());
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    classGroup = new ButtonGroup();

    //set up class radio

            classGroup.add(standardRadio);
            classGroup.add(businessRadio);

    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    nameLabel.setBounds(12, 11, 69, 31);
    contentPane.add(nameLabel);

    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    cityLabel.setBounds(12, 47, 69, 31);
    contentPane.add(cityLabel);

    JLabel lblNewLabel_2 = new JLabel("Class: ");
    lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblNewLabel_2.setBounds(12, 89, 69, 31);
    contentPane.add(lblNewLabel_2);

    nameField = new JTextField();
    nameField.setBounds(60, 18, 129, 20);
    contentPane.add(nameField);
    nameField.setColumns(10);

    cityField = new JTextField();
    cityField.setColumns(10);
    cityField.setBounds(60, 53, 129, 20);
    contentPane.add(cityField);

    JRadioButton businessRadio = new JRadioButton("Business");
    businessRadio.setBounds(58, 95, 109, 23);
    contentPane.add(businessRadio);

    JRadioButton standardRadio = new JRadioButton("Standard");
    standardRadio.setBounds(60, 127, 109, 23);
    contentPane.add(standardRadio);

    JButton btnSubmit = new JButton("Submit");
    btnSubmit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String city = cityField.getText();
            String passengerClass = classGroup.getSelection().getActionCommand();

            PassengerFormEvent ev = new PassengerFormEvent(this, name, passengerClass, city);

Body:
You are not instantiating classGroup.  You need code such as:-

classGroup = new ButtonGroup();

before you can call methods on classGroup.

EDIT: In answer to the second problem, it's because the buttons you've added to the buttonGroup are also null. You need to create them before you add them.


问:
How to exclude a range from another range in Python?
Suppose I've a range (section) and an additional list of ranges to exclude, represented by tuples (start, end):

```<code>section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-ranges
</code>```

I'm looking for an efficient algorithm which returns, from these two inputs, a new list of ranges like:

```<code>[(1,9),(16,39),(51,79),(84,100)]
</code>```

Which is the main range exluding the second list of ranges.

Thanks!

EDIT:

Actually the advice from deceze to use intervaltree seems to be interesting. With a few lines:

```<code>from intervaltree import Interval, IntervalTree
t=IntervalTree()
t[1:100]="main"
t.chop(10,15)
t.chop(40,50)
t.chop(80,83)
t
IntervalTree([Interval(1, 10, 'main'), Interval(15, 40, 'main'), Interval(50, 80, 'main'), Interval(83, 100, 'main')])
</code>```

The intervals are considered closed apparently, but this is a minor issue.

答:
```<code>section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-rang

list1 = []
list2 = [section[0]]
[list1.append(x[0]-1) for x in toexclude]
[list2.append(x[1]+1) for x in toexclude]
list1.append(section[1])

print list(zip(list2, list1)
# [(1, 9), (16, 39), (51, 79), (84, 100)]
</code>```

Body:
Suppose I've a range (section) and an additional list of ranges to exclude, represented by tuples (start, end):

section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-ranges

I'm looking for an efficient algorithm which returns, from these two inputs, a new list of ranges like:

[(1,9),(16,39),(51,79),(84,100)]

Which is the main range exluding the second list of ranges.

Thanks!

EDIT:

Actually the advice from deceze to use intervaltree seems to be interesting. With a few lines:

from intervaltree import Interval, IntervalTree
t=IntervalTree()
t[1:100]="main"
t.chop(10,15)
t.chop(40,50)
t.chop(80,83)
t
IntervalTree([Interval(1, 10, 'main'), Interval(15, 40, 'main'), Interval(50, 80, 'main'), Interval(83, 100, 'main')])

The intervals are considered closed apparently, but this is a minor issue.


问:
Convert milliseconds into UTC date object with UTC Time Zone
I am trying to convert milliseconds into UTC date object as below -

```<code>var tempDate = new Date(1465171200000);
// --> tempDate = Mon Jun 06 2016 05:30:00 **GMT+0530 (India Standard Time)** {}

var _utcDate = new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate(),  tempDate.getUTCHours(), tempDate.getUTCMinutes(), tempDate.getUTCSeconds());
//--> _utcDate = Mon Jun 06 2016 00:00:00 **GMT+0530 (India Standard Time)** {}
</code>```

Time is resetting to UTC time but Time Zone is still coming as GMT+0530 (India Standard Time).
Is there any sure shot approach to convert milliseconds into UTC date object with UTC Time Zone?

答:
Quoting from this answer (that I suggest you to read completely):

There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation.

As time zone is not stored in the Date object there is no way to set it.

I see two options:

the first is to make use of a library (as suggested in the answer above). Quite popular now is Moment.js

the second (pure JavaScript - if it's a viable solution in your context):

Do the "time math" in your local timezone.

When you're ready to switch to UTC use toUTCString() method.

Of course you'll end up with a string as this let you store the time zone as long as the date time value.

As you won't be able to manipulate the date time as a Date object from now on this must be the last step.

```<code>var tempDate = new Date(1465171200000);
// Mon Jun 06 2016 05:30:00 GMT+0530

// Do your date time math here
// using the Date object's methods

var utcDateAsString = tempDate.toUTCString();
// Mon Jun 06 2016 00:00:00 GMT
</code>```

Body:
I am trying to convert milliseconds into UTC date object as below -

var tempDate = new Date(1465171200000);
// --> tempDate = Mon Jun 06 2016 05:30:00 **GMT+0530 (India Standard Time)** {}

var _utcDate = new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate(),  tempDate.getUTCHours(), tempDate.getUTCMinutes(), tempDate.getUTCSeconds());
//--> _utcDate = Mon Jun 06 2016 00:00:00 **GMT+0530 (India Standard Time)** {}

Time is resetting to UTC time but Time Zone is still coming as GMT+0530 (India Standard Time).
Is there any sure shot approach to convert milliseconds into UTC date object with UTC Time Zone?

Body:
Quoting from this answer (that I suggest you to read completely):

There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation.

As time zone is not stored in the Date object there is no way to set it.

I see two options:

the first is to make use of a library (as suggested in the answer above). Quite popular now is Moment.js

the second (pure JavaScript - if it's a viable solution in your context):

Do the "time math" in your local timezone.

When you're ready to switch to UTC use toUTCString() method.

Of course you'll end up with a string as this let you store the time zone as long as the date time value.

As you won't be able to manipulate the date time as a Date object from now on this must be the last step.

var tempDate = new Date(1465171200000);
// Mon Jun 06 2016 05:30:00 GMT+0530

// Do your date time math here
// using the Date object's methods

var utcDateAsString = tempDate.toUTCString();
// Mon Jun 06 2016 00:00:00 GMT


问:
Parse HTML string in Angular 2 and extract and update values
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

```<code><div [innerHTML]="displayString"></div>
</code>```

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

答:
This operation doesn't require any angular functionality. One way to do it would be to construct a regular expression to match your string and retrieve the value.

However, you could also create an element using the external string and extract its innerText:

```<code>let div = document.createElement('div');
// when the string value changes
div.innerHTML = '<svg><text data-card-text>Value I want to update</text></svg>';
</code>```

and in your component, set the displayString attribute to this value:

```<code>this.displayString = div.innerText;
</code>```

Body:
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

Body:
This operation doesn't require any angular functionality. One way to do it would be to construct a regular expression to match your string and retrieve the value.

However, you could also create an element using the external string and extract its innerText:

let div = document.createElement('div');
// when the string value changes
div.innerHTML = '<svg><text data-card-text>Value I want to update</text></svg>';

and in your component, set the displayString attribute to this value:

this.displayString = div.innerText;


问:
Purge temporary tables
When I query for the tables in my tempdb I get a long list and some of  them are more than 6 months old. I would like to remove them, but when I try I get the message

Cannot drop the table '#A0033175', because it does not exist or you do
  not have permission.

I guess it is because this table belongs to other users, even the SA user can't drop it. Is there any way to have those old table dropped? I would have thought they had to be removed when their sessions were over.

SQL Server 2012 (SP3)

答:
The table name is actually something like #abc_____012345 where everything except for the initial characters following the 'abc'name portion is added by SQL Server to make the table unique to the session that created it. This way the proc can be run in multiple sessions (windows) and the temporary tables don't step on each other.

To get rid of these temp tables make sure the sessions are closed. Typically someone may have gone home without shutting SSMS leaving a bunch of Windows open that created the temp tables. Killing the sessions will cause SQL Server to drop the temp tables. You may have a very long running query (probably some kind of problem) that has been running for months and therefore the temp tables it created are still around. Be careful about killing sessions - you can make yourself very unpopular if you kill the 'wrong' session.

This applies to table with a single # sign in front of the name. Double ## signs signify  a table that is visible from all sessions and SQL Server does not change the name to make the table name unique.

Title: Purge temporary tables


问:
How should you define the word "Details" mentioned in Dependency inversion principle of SOLID?
From Wikipedia:

The principle states:

```<code>    A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
    B. Abstractions should not depend upon details. Details should depend upon abstractions.
</code>```

I can understand A.

But I have a problem to write a definition for "Details" in (B).

How can I define the term DEFINITION? What does it exactly stand for?

Thanks!

答: I would say to think of "Abstractions" as Interfaces and "Details" as Implementations of those interfaces... obviously the DI paradigm encompasses more that that simple scenario, but its a good place to start </p>

Body:
From Wikipedia:

The principle states:

    A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
    B. Abstractions should not depend upon details. Details should depend upon abstractions.

I can understand A.

But I have a problem to write a definition for "Details" in (B).

How can I define the term DEFINITION? What does it exactly stand for?

Thanks!


问:
Rethinkdb SIGTERM, shutting down
I'm running RethinkDB in Docker. Everything was working REALLY well for a while until we moved to a new datacenter (but im not sure if this is related to the move at all). Here's what is going on.

I start the rethinkdb container and everything runs well for a while. After some amount of time (it varies between an hour or more) I see the following in the Docker logs (highlighted in yellow):

I have absolutely no idea why it receives a SIGTERM from the system randomly. Any ideas would be greatly appreciated!

EDIT: I am adding the snippet of the logfile for the SIGTERMs. There doesn't seem to be any kind of pattern according to the timestamps.

```<code>2015-07-15T16:15:02.888762613 663165.661585s notice: Server got SIGTERM from pid 0, uid 0; shutting down...
2015-07-17T17:02:11.562306701 13322.914561s notice: Server got SIGTERM from pid 0, uid 0; shutting down...
2015-07-19T18:31:12.499022237 96786.220054s notice: Server got SIGTERM from pid 0, uid 0; shutting down...
2015-07-20T13:52:44.493304030 69690.608865s notice: Server got SIGTERM from pid 0, uid 0; shutting down...
</code>```

EDIT 2: I ran RethinkDB outside of Docker and I see this in the logs: error: worker process failed to resynchronize with main process. Not sure if it's anything to be concerned about. It does not appear to affect the RethinkDB instance at all (all clients remained connected).

```<code>2015-07-21T06:53:10.663375859 0.116098s info: Automatically using cache size of 10702 MB
2015-07-21T06:53:10.676277261 0.128998s notice: Listening for intracluster connections on port 29015
2015-07-21T06:53:10.684504354 0.137225s notice: Listening for client driver connections on port 28015
2015-07-21T06:53:10.685485550 0.138206s notice: Listening for administrative HTTP connections on port 8080
2015-07-21T06:53:10.686313405 0.139034s notice: Listening on addresses: 127.0.0.1, 172.17.42.1, 192.151.151.122, ::1, fe80::1879:43ff:fe5e:bdb2%34, fe80::62eb:69ff:fe07:d986%2, fe80::b837:f2ff:fecd:d5cd%4
2015-07-21T06:53:10.686316632 0.139037s notice: Server ready, "0aa312e817ef_nrx" 069ac5b3-9f43-4bbe-9022-c1f006790e99
2015-07-21T06:53:11.558116243 1.010837s error: worker process failed to resynchronize with main process
2015-07-21T06:53:11.558122179 1.010843s notice: A newer version of the RethinkDB server is available: 2.0.4. You can read the changelog at <https://github.com/rethinkdb/rethinkdb/releases>.
</code>```

EDIT 3: I found another issue here that I think may be the real problem. The rethink adapter (in the app) is keeping the connections to the DB server established which is exhausting the available file descriptors/ports in the system. Here is an example printout of an lsof. NOTE this is only a short list. There are hundreds/thousands of these kept open when multiple people use the system

```<code>node    11633 [username_ommitted]  201u    IPv4 0x53153575d33d64bb       0t0      TCP 192.168.1.142:61041->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  202u    IPv4 0x53153575d33fa65b       0t0      TCP 192.168.1.142:61053->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  203u    IPv4 0x53153575dd6a5d8b       0t0      TCP 192.168.1.142:61043->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  204u    IPv4 0x53153575bff6717b       0t0      TCP 192.168.1.142:61044->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  206u    IPv4 0x53153575d33e54bb       0t0      TCP 192.168.1.142:61049->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  207u    IPv4 0x53153575d33ef4bb       0t0      TCP 192.168.1.142:61050->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  208u    IPv4 0x53153575d33f2a4b       0t0      TCP 192.168.1.142:61051->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  209u    IPv4 0x53153575c333a17b       0t0      TCP 192.168.1.142:61054->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  210u    IPv4 0x53153575d33b47fb       0t0      TCP 192.168.1.142:61056->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  211u    IPv4 0x53153575d33de17b       0t0      TCP 192.168.1.142:61057->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  212u    IPv4 0x53153575d33f065b       0t0      TCP 192.168.1.142:61058->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  213u    IPv4 0x53153575bff67a4b       0t0      TCP 192.168.1.142:61059->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  216u    IPv4 0x53153575dd68f31b       0t0      TCP 192.168.1.142:61062->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  217u    IPv4 0x53153575dd675a4b       0t0      TCP 192.168.1.142:61063->[RETHINK_IP]:28015 (ESTABLISHED)
</code>```

答: I had the exact same issue and believe it to be caused by not closing database connections (as you note in your EDIT 3). I'm using RethinkDB in a expressjs app and followed there middleware example from here but I always terminate the request-response cycle within my controllers without calling next(), meaning the closeConnection middleware was never being reached.

Title: Rethinkdb SIGTERM, shutting down

Body:
I'm running RethinkDB in Docker. Everything was working REALLY well for a while until we moved to a new datacenter (but im not sure if this is related to the move at all). Here's what is going on.

I start the rethinkdb container and everything runs well for a while. After some amount of time (it varies between an hour or more) I see the following in the Docker logs (highlighted in yellow):

I have absolutely no idea why it receives a SIGTERM from the system randomly. Any ideas would be greatly appreciated!

EDIT: I am adding the snippet of the logfile for the SIGTERMs. There doesn't seem to be any kind of pattern according to the timestamps.

2015-07-15T16:15:02.888762613 663165.661585s notice: Server got SIGTERM from pid 0, uid 0; shutting down...
2015-07-17T17:02:11.562306701 13322.914561s notice: Server got SIGTERM from pid 0, uid 0; shutting down...
2015-07-19T18:31:12.499022237 96786.220054s notice: Server got SIGTERM from pid 0, uid 0; shutting down...
2015-07-20T13:52:44.493304030 69690.608865s notice: Server got SIGTERM from pid 0, uid 0; shutting down...

EDIT 2: I ran RethinkDB outside of Docker and I see this in the logs: error: worker process failed to resynchronize with main process. Not sure if it's anything to be concerned about. It does not appear to affect the RethinkDB instance at all (all clients remained connected).

2015-07-21T06:53:10.663375859 0.116098s info: Automatically using cache size of 10702 MB
2015-07-21T06:53:10.676277261 0.128998s notice: Listening for intracluster connections on port 29015
2015-07-21T06:53:10.684504354 0.137225s notice: Listening for client driver connections on port 28015
2015-07-21T06:53:10.685485550 0.138206s notice: Listening for administrative HTTP connections on port 8080
2015-07-21T06:53:10.686313405 0.139034s notice: Listening on addresses: 127.0.0.1, 172.17.42.1, 192.151.151.122, ::1, fe80::1879:43ff:fe5e:bdb2%34, fe80::62eb:69ff:fe07:d986%2, fe80::b837:f2ff:fecd:d5cd%4
2015-07-21T06:53:10.686316632 0.139037s notice: Server ready, "0aa312e817ef_nrx" 069ac5b3-9f43-4bbe-9022-c1f006790e99
2015-07-21T06:53:11.558116243 1.010837s error: worker process failed to resynchronize with main process
2015-07-21T06:53:11.558122179 1.010843s notice: A newer version of the RethinkDB server is available: 2.0.4. You can read the changelog at <https://github.com/rethinkdb/rethinkdb/releases>.

EDIT 3: I found another issue here that I think may be the real problem. The rethink adapter (in the app) is keeping the connections to the DB server established which is exhausting the available file descriptors/ports in the system. Here is an example printout of an lsof. NOTE this is only a short list. There are hundreds/thousands of these kept open when multiple people use the system

node    11633 [username_ommitted]  201u    IPv4 0x53153575d33d64bb       0t0      TCP 192.168.1.142:61041->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  202u    IPv4 0x53153575d33fa65b       0t0      TCP 192.168.1.142:61053->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  203u    IPv4 0x53153575dd6a5d8b       0t0      TCP 192.168.1.142:61043->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  204u    IPv4 0x53153575bff6717b       0t0      TCP 192.168.1.142:61044->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  206u    IPv4 0x53153575d33e54bb       0t0      TCP 192.168.1.142:61049->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  207u    IPv4 0x53153575d33ef4bb       0t0      TCP 192.168.1.142:61050->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  208u    IPv4 0x53153575d33f2a4b       0t0      TCP 192.168.1.142:61051->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  209u    IPv4 0x53153575c333a17b       0t0      TCP 192.168.1.142:61054->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  210u    IPv4 0x53153575d33b47fb       0t0      TCP 192.168.1.142:61056->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  211u    IPv4 0x53153575d33de17b       0t0      TCP 192.168.1.142:61057->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  212u    IPv4 0x53153575d33f065b       0t0      TCP 192.168.1.142:61058->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  213u    IPv4 0x53153575bff67a4b       0t0      TCP 192.168.1.142:61059->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  216u    IPv4 0x53153575dd68f31b       0t0      TCP 192.168.1.142:61062->[RETHINK_IP]:28015 (ESTABLISHED)
node    11633 [username_ommitted]  217u    IPv4 0x53153575dd675a4b       0t0      TCP 192.168.1.142:61063->[RETHINK_IP]:28015 (ESTABLISHED)


问:
Why does the sqlParameter request a sourceColumn?
I was examining a sqlParameter example from Microsoft and am trying to understand:

What are the reasons and benefits for specifying a SourceColumn?

The sql command already specifies the target column.

```<code>    command = New SqlCommand( _
        "INSERT INTO Customers (CustomerID, CompanyName) " & _
        "VALUES (@CustomerID, @CompanyName)", connection)

    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")
</code>```

答:
Specifying the SourceColumn in this instance means specifying the column name property (DataColumn.ColumnName) in a DataTable or Dataset.  This is only important when you're using a SqlDataAdapter object in conjunction with your SqlCommand like so:

```<code>--first, fill a DataTable with data from the database:
Dim dt As New DataTable
Dim cmdSelect = New SqlCommand("SELECT CustomerID, CompanyName FROM Customers;", connection)
Dim daCustomers As New SqlDataAdapter
daCustomers.SelectCommand = cmdSelect
daCustomers.Fill(dt)

--Now our DataTable has two columns: "CustomerID" and "CompanyName"
--We can help out our DataAdapter by telling it which columns in the database
--correspond with which columns in the DataTable
--which is what you've done with your fourth argument of .Parameters.Add()
command = New SqlCommand( _
    "INSERT INTO Customers (CustomerID, CompanyName) " & _
    "VALUES (@CustomerID, @CompanyName)", connection)

command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")
daCustomers.InsertCommand = command
</code>```

If we do it this way, then we won't have to ever specify the values of the two parameters (in this case, when the InsertCommand fires), because the data adapter will just look at the values in the appropriate DataColumn & DataRow automatically when you call daCustomers.Update(dt).

Likewise, if you want your SqlDataAdapter to be even more useful, you would want to also specify the SourceColumn for the parameters of your defined UpdateCommand and DeleteCommands.  Note that a lot of people prefer to use a SqlCommandBuilder object to automatically configure their SqlDataAdapters for this and other simple adapters without specifying much of anything for their SqlCommand objects, but I prefer this more explicit approach for anything but the simplest cases.

I am unaware of any benefit to be gained by specifying SourceColumn when you're not using a SqlDataAdapter with your SqlCommand.

Body:
I was examining a sqlParameter example from Microsoft and am trying to understand:

What are the reasons and benefits for specifying a SourceColumn?

The sql command already specifies the target column.

    command = New SqlCommand( _
        "INSERT INTO Customers (CustomerID, CompanyName) " & _
        "VALUES (@CustomerID, @CompanyName)", connection)

    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")

Body:
Specifying the SourceColumn in this instance means specifying the column name property (DataColumn.ColumnName) in a DataTable or Dataset.  This is only important when you're using a SqlDataAdapter object in conjunction with your SqlCommand like so:

--first, fill a DataTable with data from the database:
Dim dt As New DataTable
Dim cmdSelect = New SqlCommand("SELECT CustomerID, CompanyName FROM Customers;", connection)
Dim daCustomers As New SqlDataAdapter
daCustomers.SelectCommand = cmdSelect
daCustomers.Fill(dt)

--Now our DataTable has two columns: "CustomerID" and "CompanyName"
--We can help out our DataAdapter by telling it which columns in the database
--correspond with which columns in the DataTable
--which is what you've done with your fourth argument of .Parameters.Add()
command = New SqlCommand( _
    "INSERT INTO Customers (CustomerID, CompanyName) " & _
    "VALUES (@CustomerID, @CompanyName)", connection)

command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")
daCustomers.InsertCommand = command

If we do it this way, then we won't have to ever specify the values of the two parameters (in this case, when the InsertCommand fires), because the data adapter will just look at the values in the appropriate DataColumn & DataRow automatically when you call daCustomers.Update(dt).

Likewise, if you want your SqlDataAdapter to be even more useful, you would want to also specify the SourceColumn for the parameters of your defined UpdateCommand and DeleteCommands.  Note that a lot of people prefer to use a SqlCommandBuilder object to automatically configure their SqlDataAdapters for this and other simple adapters without specifying much of anything for their SqlCommand objects, but I prefer this more explicit approach for anything but the simplest cases.

I am unaware of any benefit to be gained by specifying SourceColumn when you're not using a SqlDataAdapter with your SqlCommand.


问:
Angular Pipe: Cannot replace /n
I have been trying to make a pipe to replace certain characters in a message, this is the code for the pipe:

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    let newValue = value.replace(/\n/g, '<br>');
    console.log(newValue);
    return `${newValue}`;
  }
}
</code>```

I am using it on the page like this:

```<code>  <ion-card-content [innerHtml]="message | linky | replace"></ion-card-content>
</code>```

The Issue: It works when the replace statement is something is like this:

```<code>let newValue = value.replace('bit', '<br>');
</code>```

But is doesn't do anything when it looks like this:(I need to get it working for this)

```<code>let newValue = value.replace(/\n/g, '<br>');
</code>```

I can't seem to figure out where am I going wrong.

答:
I was able to get it work by putting
 is double quotes and adding an extra \ to\n. I don't know why I needed to do that to make it work but it works perfectly now. Here is the solution:

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    if(value) {
    let newValue = value.replace(/\\n/g, "<br>").replace(/&/g, "&");
    console.log(newValue);
    return `${newValue}`;
  }
  }
}
</code>```

Title: Angular Pipe: Cannot replace /n

Body:
I have been trying to make a pipe to replace certain characters in a message, this is the code for the pipe:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    let newValue = value.replace(/\n/g, '
');
    console.log(newValue);
    return `${newValue}`;
  }
}

I am using it on the page like this:

  <ion-card-content [innerHtml]="message | linky | replace"></ion-card-content>

The Issue: It works when the replace statement is something is like this:

let newValue = value.replace('bit', '
');

But is doesn't do anything when it looks like this:(I need to get it working for this)

let newValue = value.replace(/\n/g, '
');

I can't seem to figure out where am I going wrong.

Body:
I was able to get it work by putting <br> is double quotes and adding an extra \ to\n. I don't know why I needed to do that to make it work but it works perfectly now. Here is the solution:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    if(value) {
    let newValue = value.replace(/\\n/g, "<br>").replace(/&/g, "&amp;");
    console.log(newValue);
    return `${newValue}`;
  }
  }
}


问:
Margins not working on a scrollview
XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fancy="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBlack"
android:fillViewport="true"
android:orientation="vertical">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="@color/colorNavigationKolBG"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">

  <!-- FORM STUFF HERE, I CUT IT OUT -->

    <mehdi.sakout.fancybuttons.FancyButton
        android:id="@+id/btn_add_pic"
        android:layout_width="250dp"
        android:layout_height="40dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="7dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/descriptionForm"
        fancy:fb_borderColor="@color/colorNavigationKolBTN"
        fancy:fb_borderWidth="1dp"
        fancy:fb_defaultColor="@color/colorNavigationKolBTN"
        fancy:fb_focusColor="#3B5F6A"
        fancy:fb_fontIconResource=""
        fancy:fb_fontIconSize="20sp"
        fancy:fb_iconPosition="left"
        fancy:fb_radius="0dp"
        fancy:fb_text="Add Image"
        fancy:fb_textColor="#FFFFFF"
        fancy:fb_textSize="20sp" />

    <mehdi.sakout.fancybuttons.FancyButton
        android:id="@+id/btn_submit"
        android:layout_width="250dp"
        android:layout_height="60dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearImageLayout"
        fancy:fb_borderColor="@color/colorNavigationKolBTN"
        fancy:fb_borderWidth="1dp"
        fancy:fb_defaultColor="@color/colorNavigationKolBTN"
        fancy:fb_focusColor="#3B5F6A"
        fancy:fb_fontIconResource=""
        fancy:fb_fontIconSize="20sp"
        fancy:fb_iconPosition="left"
        fancy:fb_radius="0dp"
        fancy:fb_text="Submit"
        fancy:fb_textColor="#FFFFFF"
        fancy:fb_textSize="20sp" />

    <LinearLayout
        android:id="@+id/linearImageLayout"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/border"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_add_pic"
        fancy:srcCompat="@color/cardview_light_background">

        <ImageView
            android:id="@+id/imageForm"
            android:layout_width="match_parent"
            android:layout_height="150dp" />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

The imageview visibility is set to gone, when an user adds an image the visibility changes to visible and the imageview pushes the submit button downward.

However, the result is undesirable, it makes the submit button anchor to the very bottom of the layout. As you can see below:

My quesiton is, how can I make this layout respect the bottom margin of the submit button?

答:
Adding layout_marginBottom to its parent (in this case, the ConstraintLayout) might work.

It seems to me that all those constraint attributes might have messed up the margins. For this layout, I don't think you need a ConstraintLayout. A LinearLayout would do just fine.

Title: Margins not working on a scrollview

Body:
XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fancy="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBlack"
android:fillViewport="true"
android:orientation="vertical">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="@color/colorNavigationKolBG"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">

    <mehdi.sakout.fancybuttons.FancyButton
        android:id="@+id/btn_add_pic"
        android:layout_width="250dp"
        android:layout_height="40dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="7dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/descriptionForm"
        fancy:fb_borderColor="@color/colorNavigationKolBTN"
        fancy:fb_borderWidth="1dp"
        fancy:fb_defaultColor="@color/colorNavigationKolBTN"
        fancy:fb_focusColor="#3B5F6A"
        fancy:fb_fontIconResource=""
        fancy:fb_fontIconSize="20sp"
        fancy:fb_iconPosition="left"
        fancy:fb_radius="0dp"
        fancy:fb_text="Add Image"
        fancy:fb_textColor="#FFFFFF"
        fancy:fb_textSize="20sp" />

    <mehdi.sakout.fancybuttons.FancyButton
        android:id="@+id/btn_submit"
        android:layout_width="250dp"
        android:layout_height="60dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearImageLayout"
        fancy:fb_borderColor="@color/colorNavigationKolBTN"
        fancy:fb_borderWidth="1dp"
        fancy:fb_defaultColor="@color/colorNavigationKolBTN"
        fancy:fb_focusColor="#3B5F6A"
        fancy:fb_fontIconResource=""
        fancy:fb_fontIconSize="20sp"
        fancy:fb_iconPosition="left"
        fancy:fb_radius="0dp"
        fancy:fb_text="Submit"
        fancy:fb_textColor="#FFFFFF"
        fancy:fb_textSize="20sp" />

    <LinearLayout
        android:id="@+id/linearImageLayout"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/border"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_add_pic"
        fancy:srcCompat="@color/cardview_light_background">

        <ImageView
            android:id="@+id/imageForm"
            android:layout_width="match_parent"
            android:layout_height="150dp" />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

The imageview visibility is set to gone, when an user adds an image the visibility changes to visible and the imageview pushes the submit button downward.

However, the result is undesirable, it makes the submit button anchor to the very bottom of the layout. As you can see below:

My quesiton is, how can I make this layout respect the bottom margin of the submit button?


问:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>

答: Personally, I've only seen callbacks used.  However, I haven't seen that much event driven python code so YMMV.</p>

OwnerDisplayName: okoman

OwnerDisplayName: David Locke


问:
Ruby on Rails: Why "edit" action does not work?
In views/products/edit.html.erb I use:

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
</code>```

which generates:

```<code><form method="post" action="/aircons/8" accept-charset="UTF-8">
</code>```

and I get the following error:

```<code>The action '8' could not be found for ProductsController
</code>```

when trying to update a product with id=8.

I think that form's method should be put. Is that right ? How should I fix this ?

Some controller code:

```<code>def edit
  @product = Product.find(params[:id])
end

def update
  update_params_with_new_values(params)

  @product = Product.find(params[:id])

  if @product.update_attributes(params[:product])
    flash[:notice] = "Product updated successfully."
    redirect_to(:product => 'index')
  else
    render('edit')
  end
end

def update_params_with_new_values(params)
  params[:product][:shop_id] = Shop.create(:name => params[:new_shop]).id if params[:product][:shop_id] == "new_shop"
  params[:product][:brand_id] = Brand.create(:name => params[:new_brand]).id if params[:product][:brand_id] == "new_brand"
end
</code>```

routes.rb contains only the following two lines:

```<code>root :to => "products#index"
resources :products
</code>```

答:
try using this

```<code><% form_for @product %>
#code goes here
<% end %>
</code>```

you need not do all the things that you are trying. If you have created this Product model using scaffolding mechanism you must have its entry in the config/routes.rb file this will give you a path variable as below

```<code>GET     /products/:id/edit      edit    return an HTML form for editing a photo
PUT     /products/:id   update  update a specific photo
</code>```

you can get the edit path as edit_product_path for more info on this have a look at this

Hope you understand it better now.

Body:
In views/products/edit.html.erb I use:

<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>

which generates:

<form method="post" action="/aircons/8" accept-charset="UTF-8">

and I get the following error:

The action '8' could not be found for ProductsController

when trying to update a product with id=8.

I think that form's method should be put. Is that right ? How should I fix this ?

Some controller code:

def edit
  @product = Product.find(params[:id])
end

def update
  update_params_with_new_values(params)

  @product = Product.find(params[:id])

  if @product.update_attributes(params[:product])
    flash[:notice] = "Product updated successfully."
    redirect_to(:product => 'index')
  else
    render('edit')
  end
end

def update_params_with_new_values(params)
  params[:product][:shop_id] = Shop.create(:name => params[:new_shop]).id if params[:product][:shop_id] == "new_shop"
  params[:product][:brand_id] = Brand.create(:name => params[:new_brand]).id if params[:product][:brand_id] == "new_brand"
end

routes.rb contains only the following two lines:

root :to => "products#index"
resources :products

Body:
try using this

<% form_for @product %>
#code goes here
<% end %>

you need not do all the things that you are trying. If you have created this Product model using scaffolding mechanism you must have its entry in the config/routes.rb file this will give you a path variable as below

GET     /products/:id/edit      edit    return an HTML form for editing a photo
PUT     /products/:id   update  update a specific photo

you can get the edit path as edit_product_path for more info on this have a look at this

Hope you understand it better now.