问:
Module not found when doing unit test with typescrit/mocha
I am fairly new with Typescript and was trying to set up a project following this tutorial : http://mherman.org/blog/2016/11/05/developing-a-restful-api-with-node-and-typescript/

I am at the step where we create a file named helloworld.test.ts and run npm test to see if the basic route of the api is working.

However when I run the npm test command (which do : mocha --reporter spec --compilers ts:ts-node/register 'test/**/*.test.ts') I get the following errors :

```<code>/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:312
          throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
                ^
TSError: ⨯ Unable to compile TypeScript
Cannot find type definition file for 'body-parser'. (2688)
Cannot find type definition file for 'chai'. (2688)
Cannot find type definition file for 'chai-http'. (2688)
Cannot find type definition file for 'debug'. (2688)
Cannot find type definition file for 'express'. (2688)
Cannot find type definition file for 'express-serve-static-core'. (2688)
Cannot find type definition file for 'mime'. (2688)
Cannot find type definition file for 'mocha'. (2688)
Cannot find type definition file for 'morgan'. (2688)
Cannot find type definition file for 'node'. (2688)
Cannot find type definition file for 'serve-static'. (2688)
test/helloworld.test.ts (1,24): Cannot find module 'mocha'. (2307)
test/helloworld.test.ts (2,23): Cannot find module 'chai'. (2307)
test/helloworld.test.ts (3,27): Cannot find module 'chai-http'. (2307)
test/helloworld.test.ts (5,17): Cannot find module '../src/App'. (2307)
test/helloworld.test.ts (10,1): Cannot find name 'describe'. (2304)
test/helloworld.test.ts (12,3): Cannot find name 'it'. (2304)
test/helloworld.test.ts (19,3): Cannot find name 'it'. (2304)
    at getOutput (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:312:17)
    at /home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:343:18
    at Object.compile (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:476:19)
    at Module.m._compile (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:406:44)
    at Module._extensions..js (module.js:582:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:409:12)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.require (module.js:500:17)
    at require (internal/module.js:20:19)
    at /home/louis/Bureau/my-simple-project/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (native)
    at Mocha.loadFiles (/home/louis/Bureau/my-simple-project/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/home/louis/Bureau/my-simple-project/node_modules/mocha/lib/mocha.js:514:10)
    at Object.<anonymous> (/home/louis/Bureau/my-simple-project/node_modules/mocha/bin/_mocha:480:18)
    at Module._compile (module.js:573:32)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.runMain (module.js:607:10)
    at run (bootstrap_node.js:382:7)
    at startup (bootstrap_node.js:137:9)
    at bootstrap_node.js:497:3
npm ERR! Test failed.  See above for more details.
</code>```

Content of test/helloworld.test.ts :

```<code>import * as mocha from 'mocha';
import * as chai from 'chai';
import chaiHttp = require('chai-http');

import app from '../src/App';

chai.use(chaiHttp);
const expect = chai.expect;

describe('baseRoute', () => {

  it('should be json', () => {
    return chai.request(app).get('/')
    .then(res => {
      expect(res.type).to.eql('application/json');
    });
  });

  it('should have a message prop', () => {
    return chai.request(app).get('/')
    .then(res => {
      expect(res.body.message).to.eql('Hello World!');
    });
  });

});
</code>```

Content of tsconfig.json :

```<code>{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
</code>```

Content of package.json :

```<code>{
  "name": "simple-project",
  "version": "1.0.0",
  "description": "description",
  "main": "index.js",
  "scripts": {
    "start": "node dist/index.js",
    "build": "gulp scripts",
    "test": "mocha --reporter spec --compilers ts:ts-node/register 'test/**/*.test.ts'"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/body-parser": "0.0.33",
    "@types/chai": "^3.4.34",
    "@types/chai-http": "0.0.29",
    "@types/debug": "0.0.29",
    "@types/express": "^4.0.33",
    "@types/mocha": "^2.2.32",
    "@types/morgan": "^1.7.32",
    "@types/node": "^6.0.46",
    "chai": "^3.5.0",
    "chai-http": "^3.0.0",
    "gulp": "^3.9.1",
    "gulp-sourcemaps": "^2.6.1",
    "gulp-typescript": "^3.1.1",
    "merge-stream": "^1.0.1",
    "mocha": "^3.1.2",
    "ts-node": "^1.6.1",
    "typescript": "^2.0.6"
  },
  "dependencies": {
    "body-parser": "^1.15.2",
    "debug": "^2.2.0",
    "express": "^4.14.0",
    "morgan": "^1.7.0"
  }
}
</code>```

I have the same issue when cloning the repo from the tutorial (https://github.com/mjhea0/typescript-node-api).

I think the npm package are correctly installed since when I run npm start the api is correctly working.

I am not sure wether I should add some files to this post since my file are basically nearly the same as the ones in the repo.

I am using Ubuntu 16.04, my node version is 7.0.0 my npm version is 3.10.10 and the tutorial use typescript 2.

答:
I could reproduce. ts-node is outdated

```<code>npm install ts-node@^3 --dev
</code>```

will fix it

Body:
I am fairly new with Typescript and was trying to set up a project following this tutorial : http://mherman.org/blog/2016/11/05/developing-a-restful-api-with-node-and-typescript/

I am at the step where we create a file named helloworld.test.ts and run npm test to see if the basic route of the api is working.

However when I run the npm test command (which do : mocha --reporter spec --compilers ts:ts-node/register 'test/**/*.test.ts') I get the following errors :

/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:312
          throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
                ^
TSError: ⨯ Unable to compile TypeScript
Cannot find type definition file for 'body-parser'. (2688)
Cannot find type definition file for 'chai'. (2688)
Cannot find type definition file for 'chai-http'. (2688)
Cannot find type definition file for 'debug'. (2688)
Cannot find type definition file for 'express'. (2688)
Cannot find type definition file for 'express-serve-static-core'. (2688)
Cannot find type definition file for 'mime'. (2688)
Cannot find type definition file for 'mocha'. (2688)
Cannot find type definition file for 'morgan'. (2688)
Cannot find type definition file for 'node'. (2688)
Cannot find type definition file for 'serve-static'. (2688)
test/helloworld.test.ts (1,24): Cannot find module 'mocha'. (2307)
test/helloworld.test.ts (2,23): Cannot find module 'chai'. (2307)
test/helloworld.test.ts (3,27): Cannot find module 'chai-http'. (2307)
test/helloworld.test.ts (5,17): Cannot find module '../src/App'. (2307)
test/helloworld.test.ts (10,1): Cannot find name 'describe'. (2304)
test/helloworld.test.ts (12,3): Cannot find name 'it'. (2304)
test/helloworld.test.ts (19,3): Cannot find name 'it'. (2304)
    at getOutput (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:312:17)
    at /home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:343:18
    at Object.compile (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:476:19)
    at Module.m._compile (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:406:44)
    at Module._extensions..js (module.js:582:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/home/louis/Bureau/my-simple-project/node_modules/ts-node/src/index.ts:409:12)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.require (module.js:500:17)
    at require (internal/module.js:20:19)
    at /home/louis/Bureau/my-simple-project/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (native)
    at Mocha.loadFiles (/home/louis/Bureau/my-simple-project/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/home/louis/Bureau/my-simple-project/node_modules/mocha/lib/mocha.js:514:10)
    at Object.<anonymous> (/home/louis/Bureau/my-simple-project/node_modules/mocha/bin/_mocha:480:18)
    at Module._compile (module.js:573:32)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.runMain (module.js:607:10)
    at run (bootstrap_node.js:382:7)
    at startup (bootstrap_node.js:137:9)
    at bootstrap_node.js:497:3
npm ERR! Test failed.  See above for more details.

Content of test/helloworld.test.ts :

import * as mocha from 'mocha';
import * as chai from 'chai';
import chaiHttp = require('chai-http');

import app from '../src/App';

chai.use(chaiHttp);
const expect = chai.expect;

describe('baseRoute', () => {

  it('should be json', () => {
    return chai.request(app).get('/')
    .then(res => {
      expect(res.type).to.eql('application/json');
    });
  });

  it('should have a message prop', () => {
    return chai.request(app).get('/')
    .then(res => {
      expect(res.body.message).to.eql('Hello World!');
    });
  });

});

Content of tsconfig.json :

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

Content of package.json :

{
  "name": "simple-project",
  "version": "1.0.0",
  "description": "description",
  "main": "index.js",
  "scripts": {
    "start": "node dist/index.js",
    "build": "gulp scripts",
    "test": "mocha --reporter spec --compilers ts:ts-node/register 'test/**/*.test.ts'"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/body-parser": "0.0.33",
    "@types/chai": "^3.4.34",
    "@types/chai-http": "0.0.29",
    "@types/debug": "0.0.29",
    "@types/express": "^4.0.33",
    "@types/mocha": "^2.2.32",
    "@types/morgan": "^1.7.32",
    "@types/node": "^6.0.46",
    "chai": "^3.5.0",
    "chai-http": "^3.0.0",
    "gulp": "^3.9.1",
    "gulp-sourcemaps": "^2.6.1",
    "gulp-typescript": "^3.1.1",
    "merge-stream": "^1.0.1",
    "mocha": "^3.1.2",
    "ts-node": "^1.6.1",
    "typescript": "^2.0.6"
  },
  "dependencies": {
    "body-parser": "^1.15.2",
    "debug": "^2.2.0",
    "express": "^4.14.0",
    "morgan": "^1.7.0"
  }
}

I have the same issue when cloning the repo from the tutorial (https://github.com/mjhea0/typescript-node-api).

I think the npm package are correctly installed since when I run npm start the api is correctly working.

I am not sure wether I should add some files to this post since my file are basically nearly the same as the ones in the repo.

I am using Ubuntu 16.04, my node version is 7.0.0 my npm version is 3.10.10 and the tutorial use typescript 2.

Body:
I could reproduce. ts-node is outdated

npm install ts-node@^3 --dev

will fix it


来源: stackexchange

问:
How do I create a string intermixed with specially formatted placeholders for custom text
I would like to create a string which has a placeholder held within curly brackets for custom text. For example

```<code>string mySpecialMessage = "Hi there developer {name}.
I see that you have {reputation} reputation points!
Thanks for looking at my stack overflow. You're a real {compliment}";
</code>```

I would then feed it into a method

```<code>Display(mySpecialMessage, MessageType.HighPriority, 2);
</code>```

And the method looks like this

```<code>public void Display (string messageContents, messageType messageType, float displayDuration)
{
// TODO - Format messageContents with replaced placeholders
// Create a new instance of message

Message newMessage = new Message(messageContents, messageType, displayDuration);

// Adds message to queue

messageQueue.Enqueue(newMessage);
if (!processing)
    {
        StartCoroutine(ProcessMessageQueue());
    }
}
}
</code>```

My question is: How do I extract all these curly brackets and format it back into the string?

答:
Use string interpolation:

```<code>string name = "Example Name";
string reputation = "Example Reputation";
string compliment = "Example Compliment";

string mySpecialMessage =
    $"Hi there developer {name}. " +
    $"I see that you have {reputation} reputation points!" +
    $"Thanks for looking at my stack overflow.You're a real {compliment}";
</code>```

Note the $ before the string.

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing or, in formal terms, a form of quasi-quotation (or logic substitution interpretation). String interpolation allows easier and more intuitive string formatting and content-specification compared with string concatenation.

Source

ContentLicense: CC BY-SA 3.0

Body:
I would like to create a string which has a placeholder held within curly brackets for custom text. For example

string mySpecialMessage = "Hi there developer {name}.
I see that you have {reputation} reputation points!
Thanks for looking at my stack overflow. You're a real {compliment}";

I would then feed it into a method

Display(mySpecialMessage, MessageType.HighPriority, 2);

And the method looks like this

public void Display (string messageContents, messageType messageType, float displayDuration)
{
// TODO - Format messageContents with replaced placeholders
// Create a new instance of message

Message newMessage = new Message(messageContents, messageType, displayDuration);

// Adds message to queue

messageQueue.Enqueue(newMessage);
if (!processing)
    {
        StartCoroutine(ProcessMessageQueue());
    }
}
}

My question is: How do I extract all these curly brackets and format it back into the string?

Body:
Use string interpolation:

string name = "Example Name";
string reputation = "Example Reputation";
string compliment = "Example Compliment";

string mySpecialMessage =
    $"Hi there developer {name}. " +
    $"I see that you have {reputation} reputation points!" +
    $"Thanks for looking at my stack overflow.You're a real {compliment}";

Note the $ before the string.

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing or, in formal terms, a form of quasi-quotation (or logic substitution interpretation). String interpolation allows easier and more intuitive string formatting and content-specification compared with string concatenation.

Source


问:
Solr sort by field value
i try to sort response from "apache solr" by field value.
This is my sort function:

```<code>sort=if(eq(custom_s_doctor_location_key, "advanced imaging center - lake ridge-landing"),1,0) desc
</code>```

But i get error:

```<code>  "error":{
"metadata":[
  "error-class","org.apache.solr.common.SolrException",
  "root-error-class","org.apache.solr.common.SolrException"],
"msg":"Can't determine a Sort Order (asc or desc) in sort spec 'if(eq(custom_s_doctor_location_key, \"advanced imaging center - lake ridge-landing\"),1,0) desc', pos=35",
"code":400}})
</code>```

答: custom_s_doctor_location_key is a numeric field? If it is not, you would need to use some other function like strdist to compare as string. I would be cumbersome but should work</p>

Title: Solr sort by field value

Body:
i try to sort response from "apache solr" by field value.
This is my sort function:

sort=if(eq(custom_s_doctor_location_key, "advanced imaging center - lake ridge-landing"),1,0) desc

But i get error:

  "error":{
"metadata":[
  "error-class","org.apache.solr.common.SolrException",
  "root-error-class","org.apache.solr.common.SolrException"],
"msg":"Can't determine a Sort Order (asc or desc) in sort spec 'if(eq(custom_s_doctor_location_key, \"advanced imaging center - lake ridge-landing\"),1,0) desc', pos=35",
"code":400}})


问:
iOS Audio Kit : Stop drawing a Node in a plot
I'm following the Microphone Analysis in the examples of AudioKit here :

http://audiokit.io/examples/MicrophoneAnalysis/

The plot displays the audio wave forms in loop.

I want to stop drawing inside the plot when I tap a button, but I don't know how to tell to the plot to stop drawing the microphone inputs.

This is my plot configuration :

```<code>func setupPlot() {
    plot = AKNodeOutputPlot(microphone, frame: audioInputPlot.bounds)
    plot.plotType = .rolling
    plot.shouldFill = true
    plot.shouldMirror = true
    plot.color = UIColor(red:0.24, green:1.00, blue:0.08, alpha:1.0)
    plot.alpha = 0.0
    plot.setRollingHistoryLength(200)
}
</code>```

答:
try setting plot.node = nil
this stops the plot from receiving any inputs from the mic.

Body:
I'm following the Microphone Analysis in the examples of AudioKit here :

http://audiokit.io/examples/MicrophoneAnalysis/

The plot displays the audio wave forms in loop.

I want to stop drawing inside the plot when I tap a button, but I don't know how to tell to the plot to stop drawing the microphone inputs.

This is my plot configuration :

func setupPlot() {
    plot = AKNodeOutputPlot(microphone, frame: audioInputPlot.bounds)
    plot.plotType = .rolling
    plot.shouldFill = true
    plot.shouldMirror = true
    plot.color = UIColor(red:0.24, green:1.00, blue:0.08, alpha:1.0)
    plot.alpha = 0.0
    plot.setRollingHistoryLength(200)
}


问:
Making a list in LibreOffice Calc from other lists of unknown legnth
I have one worksheet (data) with the columns (maximum rows is 100):

```
  | A                     | B      | C        | D      | E        |
--|-----------------------|--------|----------|--------|----------|
1 | non_important_columns | time_a | reason_a | time_b | reason_b |
2 | ..................... | 00:13  | blam     | 00:59  | bang     |
3 | ..................... | 00:27  | bung     |        |          |
4 | ..................... | 01:14  | bint     | 02:31  | brik     |
```

From this data I want to make a report as a list:

```
  | A      | B     | C      |
--|--------|-------|--------|
1 | source | time  | reason |
2 | time_a | 00:13 | blam   |
3 | time_a | 00:27 | bung   |
4 | time_a | 01:14 | bint   |
5 | time_b | 00:59 | bang   |
6 | time_b | 02:31 | brik   |
```

I wont now before hand what cells actually have data in them, but I don't want any empty cells in the list. Ideally I would like to remove the 'source' column and instead color-code the results.

How could I accomplish this?

Thanks in advance,

Kruffalon

答:
Temporarily copy the data from Calc to Base as described at https://superuser.com/a/1216718/541756.  Use the following query.

```<code>SELECT 'a' AS "source", "time_a", "reason_a" FROM "Table1" WHERE "time_a" <> ''
UNION
SELECT 'b' AS "source", "time_b", "reason_b" FROM "Table1" WHERE "time_b" <> ''
</code>```

Color coding

After the results are in Calc, manually select the "a" rows and set them to a certain background color, and a different color for the "b" rows.  Then delete the source column.

A suggestion

Consider using Base with MySQL to maintain this data rather than Calc.  Without knowing more about this project, I cannot give advice as to which would be better.

Body:
I have one worksheet (data) with the columns (maximum rows is 100):

  | A                     | B      | C        | D      | E        |
--|-----------------------|--------|----------|--------|----------|
1 | non_important_columns | time_a | reason_a | time_b | reason_b |
2 | ..................... | 00:13  | blam     | 00:59  | bang     |
3 | ..................... | 00:27  | bung     |        |          |
4 | ..................... | 01:14  | bint     | 02:31  | brik     |

From this data I want to make a report as a list:

  | A      | B     | C      |
--|--------|-------|--------|
1 | source | time  | reason |
2 | time_a | 00:13 | blam   |
3 | time_a | 00:27 | bung   |
4 | time_a | 01:14 | bint   |
5 | time_b | 00:59 | bang   |
6 | time_b | 02:31 | brik   |

I wont now before hand what cells actually have data in them, but I don't want any empty cells in the list. Ideally I would like to remove the 'source' column and instead color-code the results.

How could I accomplish this?

Thanks in advance,

Kruffalon

Body:
Temporarily copy the data from Calc to Base as described at https://superuser.com/a/1216718/541756.  Use the following query.

SELECT 'a' AS "source", "time_a", "reason_a" FROM "Table1" WHERE "time_a" <> ''
UNION
SELECT 'b' AS "source", "time_b", "reason_b" FROM "Table1" WHERE "time_b" <> ''

Color coding

After the results are in Calc, manually select the "a" rows and set them to a certain background color, and a different color for the "b" rows.  Then delete the source column.

A suggestion

Consider using Base with MySQL to maintain this data rather than Calc.  Without knowing more about this project, I cannot give advice as to which would be better.


问:
Map and filter an array at the same time
I have an array of objects that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I'm trying this:

```<code>function renderOptions(options) {
    return options.map(function (option) {
        if (!option.assigned) {
            return (someNewObject);
        }
    });
}
</code>```

Is that a good approach? Is there a better method? I'm open to use any library such as lodash.

答:
At some point, isn't it easier(or just as easy) to use a forEach

var options = [
  { name: 'One', assigned: true },
  { name: 'Two', assigned: false },
  { name: 'Three', assigned: true },
];

var reduced = []
options.forEach(function(option) {
  if (option.assigned) {
     var someNewValue = { name: option.name, newProperty: 'Foo' }
     reduced.push(someNewValue);
  }
});

document.getElementById('output').innerHTML = JSON.stringify(reduced);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Only assigned options</h1>
<pre id="output"> ``````

However it would be nice if there was a malter() or fap() function that combines the map and filter functions. It would work like a filter, except instead of returning true or false, it would return any object or a null/undefined.

ContentLicense: CC BY-SA 4.0

Body:
I have an array of objects that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I'm trying this:

function renderOptions(options) {
    return options.map(function (option) {
        if (!option.assigned) {
            return (someNewObject);
        }
    });
}

Is that a good approach? Is there a better method? I'm open to use any library such as lodash.

Body:
At some point, isn't it easier(or just as easy) to use a forEach

var options = [
  { name: 'One', assigned: true },
  { name: 'Two', assigned: false },
  { name: 'Three', assigned: true },
];

var reduced = []
options.forEach(function(option) {
  if (option.assigned) {
     var someNewValue = { name: option.name, newProperty: 'Foo' }
     reduced.push(someNewValue);
  }
});

document.getElementById('output').innerHTML = JSON.stringify(reduced);

<h1>Only assigned options</h1>
<pre id="output"> </pre>

However it would be nice if there was a malter() or fap() function that combines the map and filter functions. It would work like a filter, except instead of returning true or false, it would return any object or a null/undefined.


问:
ValueError: could not convert string to float: b'import matplotlib.pyplot as plt'
```<code>from matplotlib import pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')

x,y = np.loadtxt(r'C:\Users\npatel\Documents\Coremotion Data\MotionData\data.txt',unpack = True, delimiter = '/s')
print(x)
print(y)
plt.show()
</code>```

results in

```<code>ValueError: could not convert string to float: b'import matplotlib.pyplot as plt'
</code>```

I am trying to display accelerometer values from csv file but this error pops up.If anyone knows other method to display accelerometer values(x,y,z) against time in 2D in python, help is appreciated.

答:
I don't think '/s' means what you think it means. Specifically, it doesn't mean "whitespace". Get rid of the delimiter keyword to np.loadtxt(), and accept the default value, which is to separate the fields by any white space.

```<code>np.loadtxt(r'data.txt',unpack=True)
</code>```

At some point after asking your original question, you've changed your dataset to be comma-separated rather when whitespace-separated. For comma-separated values, you should specify ',' as the delimiter:

```<code>np.loadtxt(r'data.txt', delimiter=',', unpack=True)
</code>```

Reference: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html

Body:
from matplotlib import pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')

x,y = np.loadtxt(r'C:\Users\npatel\Documents\Coremotion Data\MotionData\data.txt',unpack = True, delimiter = '/s')
print(x)
print(y)
plt.show()

results in

ValueError: could not convert string to float: b'import matplotlib.pyplot as plt'

I am trying to display accelerometer values from csv file but this error pops up.If anyone knows other method to display accelerometer values(x,y,z) against time in 2D in python, help is appreciated.

Body:
I don't think '/s' means what you think it means. Specifically, it doesn't mean "whitespace". Get rid of the delimiter keyword to np.loadtxt(), and accept the default value, which is to separate the fields by any white space.

np.loadtxt(r'data.txt',unpack=True)

At some point after asking your original question, you've changed your dataset to be comma-separated rather when whitespace-separated. For comma-separated values, you should specify ',' as the delimiter:

np.loadtxt(r'data.txt', delimiter=',', unpack=True)

Reference: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html


问:
JPA Design of User and Roles
I have a User class and a Role class.  Both of these classes are JPA entities, and hence stored in a Person table and a Role table, as well as a corresponding link table Person_Role used for joins, since the association is many to many. A user may have many roles, and a role may be assigned to many users.

```<code>@Entity
@Table(name="role")
public class Role implements Comparable<Role>
{
   // data members
   @Id @GeneratedValue
   private int    id;              // primary key
   private String name;            // name of the role
   private String description;     // description of the role

   ...
}

@Entity
@Table(name="person")
public class Person implements Comparable<Person>
{
   // data members
   @Id @GeneratedValue
   protected int       id;          // the primary key
   protected String    username;    // the user's unique user name
   protected String    firstName;   // the user's first name
   protected String    lastName;    // the user's last  name
   protected String    email;       // the user's work e-mail address
   @Transient
   protected String    history;     // chronological list of changes to the person
                                    // don't want to load this unless an explicit call to getHistory() is made
   @Transient
   protected Set<Role> roles;       // list of roles assigned to the user
                                    // don't want to load this unless an explicit call to getRoles() is made

   ...
}
</code>```

The User entity is used extensively throughout the application, as it is a shared reference for many objects, and is used in many, many  searches.  99.99% of the time, the user's roles and history are not needed.  I'm new to JPA, and have been reading the "Java Persistence with Hibernate" book in order to learn.  As I understand lazy fetching, it will load all the corresponding User data from the database when any getXXX() method is called.

Ex: user.getFirstName() would cause a database hit and load all the data, including roles and history, for the user.

I want to avoid this at all costs.  Its just needless in 99.99% of the use cases.  So, what's the best way to handle this?

My initial thought is to mark the Set<Role> roles and Set<String> history in the User class as @Transient and manually query for the roles and history only when the user.getRoles() or user.getHistory() method is called.

Thanks for any suggestions.

答:
It will not Load all the data just the the relative to

```<code> Person entity = (Person) this.em.find(Person.class, id);
</code>```

in lazy fetching it will issue a select statement from only the table person, as for protected Set<Role> roles;it will not be loaded but replaced with a proxy object

Hibernate uses a proxy object to implement lazy loading. When we request to load the Object from the database, and the fetched Object has a reference to another concrete object, Hibernate returns a proxy instead of the concrete associated object.

Hibernate creates a proxy object using bytecode instrumentation (provided by javassist). Hibernate creates a subclass of our entity class at runtime using the code generation library and replaces the actual object with the newly created proxy.

Title: JPA Design of User and Roles

Body:
I have a User class and a Role class.  Both of these classes are JPA entities, and hence stored in a Person table and a Role table, as well as a corresponding link table Person_Role used for joins, since the association is many to many. A user may have many roles, and a role may be assigned to many users.

@Entity
@Table(name="role")
public class Role implements Comparable<Role>
{
   // data members
   @Id @GeneratedValue
   private int    id;              // primary key
   private String name;            // name of the role
   private String description;     // description of the role

   ...
}

@Entity
@Table(name="person")
public class Person implements Comparable<Person>
{
   // data members
   @Id @GeneratedValue
   protected int       id;          // the primary key
   protected String    username;    // the user's unique user name
   protected String    firstName;   // the user's first name
   protected String    lastName;    // the user's last  name
   protected String    email;       // the user's work e-mail address
   @Transient
   protected String    history;     // chronological list of changes to the person
                                    // don't want to load this unless an explicit call to getHistory() is made
   @Transient
   protected Set<Role> roles;       // list of roles assigned to the user
                                    // don't want to load this unless an explicit call to getRoles() is made

   ...
}

The User entity is used extensively throughout the application, as it is a shared reference for many objects, and is used in many, many  searches.  99.99% of the time, the user's roles and history are not needed.  I'm new to JPA, and have been reading the "Java Persistence with Hibernate" book in order to learn.  As I understand lazy fetching, it will load all the corresponding User data from the database when any getXXX() method is called.

Ex: user.getFirstName() would cause a database hit and load all the data, including roles and history, for the user.

I want to avoid this at all costs.  Its just needless in 99.99% of the use cases.  So, what's the best way to handle this?

My initial thought is to mark the Set<Role> roles and Set<String> history in the User class as @Transient and manually query for the roles and history only when the user.getRoles() or user.getHistory() method is called.

Thanks for any suggestions.

Body:
It will not Load all the data just the the relative to

 Person entity = (Person) this.em.find(Person.class, id);

in lazy fetching it will issue a select statement from only the table person, as for protected Set<Role> roles;it will not be loaded but replaced with a proxy object

Hibernate uses a proxy object to implement lazy loading. When we request to load the Object from the database, and the fetched Object has a reference to another concrete object, Hibernate returns a proxy instead of the concrete associated object.

Hibernate creates a proxy object using bytecode instrumentation (provided by javassist). Hibernate creates a subclass of our entity class at runtime using the code generation library and replaces the actual object with the newly created proxy.


问:
ESP8266 12E NodeMCU 1.0 pin mapping for micro sd card?
I tried several pin conifguration to connect nodemcu and micro sd card. However, I had not any luck to successfully connect to sd card. I followed esp8266 forum and some other solution! I need your suggestions :)  </p>

答:
CONNECT SDCARD NODEMCU - TESTED

```<code>CS   - D8
MISO - D7
MOSI - D6
SCK  - D5
</code>```

In Arduino IDE open FILE > EXAMPLES > SD > CARDINFO

Change

```<code>const int chipSelect = 15; // original code is 4
</code>```

That's it, your SD Card will be working.

This works, just tested on my breadboard.

Body:
CONNECT SDCARD NODEMCU - TESTED

CS   - D8
MISO - D7
MOSI - D6
SCK  - D5

In Arduino IDE open FILE > EXAMPLES > SD > CARDINFO

Change

const int chipSelect = 15; // original code is 4

That's it, your SD Card will be working.

This works, just tested on my breadboard.


问:
how to refresh the kendo grid once $scope.gridOptions get new data
I am new to kendo grid
i have assign data to kendo grid inside service call
i have search field in the html form, whenever type number and press search service will called, the new data will bind to $scope.gridOptions.dataSource.data  but in view screen the new data not shown.

```<code>                'use strict';
            angular
                .module('app.core')
                .controller('CheckController', function($scope,PageValues,eventService,$filter,$timeout) {

                var vm = this;
                PageValues.title = "Check";
                PageValues.description = "Check";

                $scope.checkStatus = function(){

                    if($scope.phone_number != ''){
                        var chkPostRequest = {
                            "checkContacts": [
                                {

                                    "Date": '2011=02-01',
                                    "Type": "test"
                                    "Category": 'test'
                                }
                            ]
                        };
                        eventService.checkStatusSer(chkPostRequest).then(function(response){
                                if(angular.lowercase(response.transactionStatus) == "success"){
                                $scope.gridOptions = {};
                                    response.checkContactResponses.forEach(function(contStatus, key) {
                                        $scope.chkStsRes.checkContactResponses[key] = {
                                            "PhoneNumber" : contStatus.contactDetail.contact,
                                            "phoneType" : contStatus.phoneType
                                        };
                                    });
                                    $scope.gridOptions = {
                                        dataSource: {
                                           data: $scope.chkStsRes.checkContactResponses,
                                            schema: {
                                                model: {
                                                    fields: {
                                                        PhoneNumber: { type: "string" } ,
                                                        PhoneNumberType: { type: "string" },
                                                    }
                                                }
                                            },
                                            pageSize: 10
                                        },

                                        scrollable: true,
                                        sortable: true,
                                        columns: [
                                            { field: "PhoneNumber", title: "Phone Number",  width: "130px",cellFilter: 'phonemask'},
                                            { field: "PhoneNumberType", title: "Phone Number Type", width: "80px" },
                                        ]
                                    };
                                   $scope.mygrid.refresh();
                                }
                        });
                    }
                }
                });
</code>```

HTML code

```<code><input required id="phone_number" ng-model="phone_number" class="k-textbox" style="width: 100%;" value=""/>
<button class="btn" ng-click="checkStatus()" type="button" ><span>Check Status</span></button>
<kendo-grid options="gridOptions" id="searchGrid"></kendo-grid>
</code>```

Response json

```<code>        {
          "transactionStatus": "SUCCESS",
          "checkContactResponses": [
            {
              "phoneType": "Mobile",
              "contactDetail": {
                "contact": "3341234567"
              }
            },
            {
              "phoneType": "Landline",
              "contactDetail": {
                "contact": "3346543210"
              }
            }
          ]
        }
</code>```

response json is modofied whenever i click button
How can i refresh are reload kendo grid, whenever the service call hits.

答:
You assign a variable to the kendo-grid attribute, which you can then use to call the normal kendo functions. For example:

```<code><div kendo-grid="mygrid" options="gridOptions" id="searchGrid"></div>
</code>```

Now, within your controller, you can refresh the grid like this:

```<code>$scope.mygrid.refresh();
</code>```

Here is a simple fiddle: https://plnkr.co/edit/JX0S08cfKDERMwkLaKPs

Body:
I am new to kendo grid
i have assign data to kendo grid inside service call
i have search field in the html form, whenever type number and press search service will called, the new data will bind to $scope.gridOptions.dataSource.data  but in view screen the new data not shown.

                'use strict';
            angular
                .module('app.core')
                .controller('CheckController', function($scope,PageValues,eventService,$filter,$timeout) {

                var vm = this;
                PageValues.title = "Check";
                PageValues.description = "Check";

                $scope.checkStatus = function(){

                    if($scope.phone_number != ''){
                        var chkPostRequest = {
                            "checkContacts": [
                                {

                                    "Date": '2011=02-01',
                                    "Type": "test"
                                    "Category": 'test'
                                }
                            ]
                        };
                        eventService.checkStatusSer(chkPostRequest).then(function(response){
                                if(angular.lowercase(response.transactionStatus) == "success"){
                                $scope.gridOptions = {};
                                    response.checkContactResponses.forEach(function(contStatus, key) {
                                        $scope.chkStsRes.checkContactResponses[key] = {
                                            "PhoneNumber" : contStatus.contactDetail.contact,
                                            "phoneType" : contStatus.phoneType
                                        };
                                    });
                                    $scope.gridOptions = {
                                        dataSource: {
                                           data: $scope.chkStsRes.checkContactResponses,
                                            schema: {
                                                model: {
                                                    fields: {
                                                        PhoneNumber: { type: "string" } ,
                                                        PhoneNumberType: { type: "string" },
                                                    }
                                                }
                                            },
                                            pageSize: 10
                                        },

                                        scrollable: true,
                                        sortable: true,
                                        columns: [
                                            { field: "PhoneNumber", title: "Phone Number",  width: "130px",cellFilter: 'phonemask'},
                                            { field: "PhoneNumberType", title: "Phone Number Type", width: "80px" },
                                        ]
                                    };
                                   $scope.mygrid.refresh();
                                }
                        });
                    }
                }
                });

HTML code

<input required id="phone_number" ng-model="phone_number" class="k-textbox" style="width: 100%;" value=""/>
<button class="btn" ng-click="checkStatus()" type="button" >Check Status</button>
<kendo-grid options="gridOptions" id="searchGrid"></kendo-grid>

Response json

        {
          "transactionStatus": "SUCCESS",
          "checkContactResponses": [
            {
              "phoneType": "Mobile",
              "contactDetail": {
                "contact": "3341234567"
              }
            },
            {
              "phoneType": "Landline",
              "contactDetail": {
                "contact": "3346543210"
              }
            }
          ]
        }

response json is modofied whenever i click button
How can i refresh are reload kendo grid, whenever the service call hits.

Body:
You assign a variable to the kendo-grid attribute, which you can then use to call the normal kendo functions. For example:

<div kendo-grid="mygrid" options="gridOptions" id="searchGrid"></div>

Now, within your controller, you can refresh the grid like this:

$scope.mygrid.refresh();

Here is a simple fiddle: https://plnkr.co/edit/JX0S08cfKDERMwkLaKPs


问:
Is it always necessary for a notifying thread to lock the shared data during modification?
When using a condition variable, http://en.cppreference.com/w/cpp/thread/condition_variable describes the typical steps for the thread that notifies as:

acquire a std::mutex (typically via std::lock_guard)

perform the modification while the lock is held

execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)

For the simple case shown below, is it necessary for the main thread to lock "stop" when it modifies it? While I understand that locking when modifying shared data is almost always a good idea, I'm not sure why it would be necessary in this case.

```<code>std::condition_variable cv;
std::mutex mutex;
bool stop = false;

void worker() {
    std::unique_lock<std::mutex> lock(mutex);
    cv.wait(lock, [] { return stop; })
}

// No lock (Why would this not work?)
void main() {
     std::thread(worker);
     std::this_thread::sleep_for(1s);
     stop = true;
     cv.notify_one();
}

// With lock: why is this neccesary?
void main() {
     std::thread mythread(worker);
     std::this_thread::sleep_for(1s);
     {
         std::unique_lock<std::mutex>(mutex);
         stop = true;
     }
     cv.notify_one();
     mythread.join();
}
</code>```

答:
Is , it is necessary.

First of all, from the standard point of view, you code exhibits undefined behavior,  as stop is not atomic and isn't change under a lock, while other threads may read or write to it.
 both reading and writing must occur under a lock if multiple threads read and write to a shared memory.

From hardware perspective, if stop isn't changed under a lock, other threads, even through they lock some lock, aren't guaranteed to "see" the change that was done. locks don't just prevent from other threads to intervene, they also force the latest change to be read or written into the main memory, and hence all the threads can work with the latest values.

Body:
When using a condition variable, http://en.cppreference.com/w/cpp/thread/condition_variable describes the typical steps for the thread that notifies as:

acquire a std::mutex (typically via std::lock_guard)

perform the modification while the lock is held

execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)

For the simple case shown below, is it necessary for the main thread to lock "stop" when it modifies it? While I understand that locking when modifying shared data is almost always a good idea, I'm not sure why it would be necessary in this case.

std::condition_variable cv;
std::mutex mutex;
bool stop = false;

void worker() {
    std::unique_lock<std::mutex> lock(mutex);
    cv.wait(lock, [] { return stop; })
}

// No lock (Why would this not work?)
void main() {
     std::thread(worker);
     std::this_thread::sleep_for(1s);
     stop = true;
     cv.notify_one();
}

// With lock: why is this neccesary?
void main() {
     std::thread mythread(worker);
     std::this_thread::sleep_for(1s);
     {
         std::unique_lock<std::mutex>(mutex);
         stop = true;
     }
     cv.notify_one();
     mythread.join();
}


问:
T-SQL Window Function
For the sake of example, I have the following data set:
ToyReferenceNumber, Company, CompositeCalculatedField, PermanentRecallDate, ReturnToStoreDate

Basically, there could be 3-4 entries for each item (imaginary company TheToyCompany, or TTC):

```<code>TTC-011-0934, TTC, calculation, NULL, 2017-03-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2014-05-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2011-08-27 12:01:01.00
TTC-994-0132, TTC, calculation, 2017-06-12 12:01:01.00, NULL
TTC-994-0132, TTC, calculation, NULL, 2017-02-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, 2015-03-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, NULL
</code>```

From a business logic standpoint, for the first product (0934), it had a recall multiple times (which printing or prod batch, we don't care), but was fixed and returned to stores after each.

For 0132, it was attempted to fix the defect, but then the company simply decided to scrap the product as it was not selling anyway.

For 0122, a product batch was recalled, fixed, and then sent to stores on 2015-03-01, but a current batch is currently being fixed (hence, the NULL, NULL).

What management wants is a report that current fix-factory billing (e.g. time sheets for guys who fix the toys).

Pseudo-Query:

```<code> For a given product, return only the record with NULL, NULL dates (actively being fixed)
    IF not null, null, return only the record with the PermanentRecallDate
    IF no PermanentRecallDate, return only the record with the latest ReturnToStoreDate
</code>```

The oracle query was basically the same as the following pseudo-code:

```<code>SELECT <normal columns>
,MAX(ts.PermanentRecallDate) KEEP (dense_rank last order by ts.PermanentRecallDate NULLS LAST) PERANENTRECALLDATE
,MAX(ts.ReturnToStoreDate) KEEP (dense_rank last order by ts.ReturnToStoreDate NULLS LAST) RETURNTOSTOREDATE
</code>```

The oracle query is pretty straightforward, but I need it in T-SQL:

```<code>WITH CTE_ToyReferenceExport
AS
(
SELECT ts.ToyReferenceNumber AS TOYNUM
    ,tsh.Company AS COMPANY
    ,MAX(largeSetofCalculations) AS CompositeCalculatedField
    ,MAX(ts.PermanentRecallDate) AS PERMANETRECALL
    ,MAX(ts.ReturnToStoreDate) AS RETURNTOSTORE
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.PermanentRecallDate) as PRDRank
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.(ReturnToStoreDate) AS RTSDRank

    FROM origin.ToyStaging ts
    JOIN origin.ToyOrders to ON ts.ordernumer = to.ordno
    JOIN origin.ToyShipment tsh ON to.packno = tsh.crateno
    LEFT JOIN origin.Shippers sh ON to.packno = sh.cratenum AND 'calcField' = sh.originfield
GROUP BY ts.ToyReferenceNumber, tsh.Company, ts.permanentrecalldate, ts.returntostoredate
)
</code>```

There is a lot more to it, but the main thing that trips me up is getting the result set returned by "MAX..Keep Dense_rank last order by.. NULLS LAST" logic.

Any help would be appreciated.  SQL Server 2012 is the version.

答:
Here's one method of implementing your requirements.

```<code>WITH Limits AS (
  SELECT DISTINCT ToyReferenceNumber
       , FIRST_VALUE(PermanentRecallDate)
               OVER (PARTITION BY ToyReferenceNumber
                         ORDER BY CASE WHEN ReturnToStoreDate IS NULL THEN 1 ELSE 2 END
                                , CASE WHEN PermanentRecallDate IS NULL THEN 1 ELSE 2 END
                                , PermanentRecallDate DESC) PermanentRecallDate
       , FIRST_VALUE(ReturnToStoreDate)
               OVER (PARTITION BY ToyReferenceNumber
                         ORDER BY CASE WHEN ReturnToStoreDate IS NULL THEN 1 ELSE 2 END
                                , ReturnToStoreDate DESC) ReturnToStoreDate
    FROM ToyStaging
)
SELECT ts.*
  FROM ToyStaging TS
  JOIN Limits L
    ON TS.ToyReferenceNumber = L.ToyReferenceNumber
   AND (L.PermanentRecallDate IS NULL
        and ts.PermanentRecallDate is null
        OR TS.PermanentRecallDate = L.PermanentRecallDate)
   AND (L.ReturnToStoreDate IS NULL
        AND ts.ReturnToStoreDate is null
        OR TS.ReturnToStoreDate = L.ReturnToStoreDate)
</code>```

In the Limits CTE the FIRST_VALUE analytic functions will both return null if a null null record exists for a given ToyReferenceNumber. Otherwise the PermanentRecallDate column will return the latest PermanentRecallDate, and the ReturnToStoreDate column will return the latest ReturnToStoreDate when no PermanentRecallDate exist thereby instantiating your rules as to which record to return.  The distinct prunes out the duplicate records, and then Limits is joined back to ToyStaging to get the desired data.

Given your sample data the Limits CTE returns:

```<code>| ToyReferenceNumber |    PermanentRecallDate |      ReturnToStoreDate |
|--------------------|------------------------|------------------------|
|       TTC-011-0934 |                 (null) | 2017-03-01 12:01:01.00 |
|       TTC-354-0122 |                 (null) |                 (null) |
|       TTC-994-0132 | 2017-06-12 12:01:01.00 |                 (null) |
</code>```

and the whole query returns:

```<code>| ToyReferenceNumber | Company | CompositeCalculatedField |    PermanentRecallDate |      ReturnToStoreDate |
|--------------------|---------|--------------------------|------------------------|------------------------|
|       TTC-011-0934 |     TTC |              calculation |                 (null) | 2017-03-01 12:01:01.00 |
|       TTC-354-0122 |     TTC |              calculation |                 (null) |                 (null) |
|       TTC-994-0132 |     TTC |              calculation | 2017-06-12 12:01:01.00 |                 (null) |
</code>```

See this SQL Fiddle to see it in action.

Title: T-SQL Window Function

Body:
For the sake of example, I have the following data set:
ToyReferenceNumber, Company, CompositeCalculatedField, PermanentRecallDate, ReturnToStoreDate

Basically, there could be 3-4 entries for each item (imaginary company TheToyCompany, or TTC):

TTC-011-0934, TTC, calculation, NULL, 2017-03-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2014-05-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2011-08-27 12:01:01.00
TTC-994-0132, TTC, calculation, 2017-06-12 12:01:01.00, NULL
TTC-994-0132, TTC, calculation, NULL, 2017-02-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, 2015-03-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, NULL

From a business logic standpoint, for the first product (0934), it had a recall multiple times (which printing or prod batch, we don't care), but was fixed and returned to stores after each.

For 0132, it was attempted to fix the defect, but then the company simply decided to scrap the product as it was not selling anyway.

For 0122, a product batch was recalled, fixed, and then sent to stores on 2015-03-01, but a current batch is currently being fixed (hence, the NULL, NULL).

What management wants is a report that current fix-factory billing (e.g. time sheets for guys who fix the toys).

Pseudo-Query:

 For a given product, return only the record with NULL, NULL dates (actively being fixed)
    IF not null, null, return only the record with the PermanentRecallDate
    IF no PermanentRecallDate, return only the record with the latest ReturnToStoreDate

The oracle query was basically the same as the following pseudo-code:

SELECT <normal columns>
,MAX(ts.PermanentRecallDate) KEEP (dense_rank last order by ts.PermanentRecallDate NULLS LAST) PERANENTRECALLDATE
,MAX(ts.ReturnToStoreDate) KEEP (dense_rank last order by ts.ReturnToStoreDate NULLS LAST) RETURNTOSTOREDATE

The oracle query is pretty straightforward, but I need it in T-SQL:

WITH CTE_ToyReferenceExport
AS
(
SELECT ts.ToyReferenceNumber AS TOYNUM
    ,tsh.Company AS COMPANY
    ,MAX(largeSetofCalculations) AS CompositeCalculatedField
    ,MAX(ts.PermanentRecallDate) AS PERMANETRECALL
    ,MAX(ts.ReturnToStoreDate) AS RETURNTOSTORE
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.PermanentRecallDate) as PRDRank
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.(ReturnToStoreDate) AS RTSDRank

    FROM origin.ToyStaging ts
    JOIN origin.ToyOrders to ON ts.ordernumer = to.ordno
    JOIN origin.ToyShipment tsh ON to.packno = tsh.crateno
    LEFT JOIN origin.Shippers sh ON to.packno = sh.cratenum AND 'calcField' = sh.originfield
GROUP BY ts.ToyReferenceNumber, tsh.Company, ts.permanentrecalldate, ts.returntostoredate
)

There is a lot more to it, but the main thing that trips me up is getting the result set returned by "MAX..Keep Dense_rank last order by.. NULLS LAST" logic.

Any help would be appreciated.  SQL Server 2012 is the version.

Body:
Here's one method of implementing your requirements.

WITH Limits AS (
  SELECT DISTINCT ToyReferenceNumber
       , FIRST_VALUE(PermanentRecallDate)
               OVER (PARTITION BY ToyReferenceNumber
                         ORDER BY CASE WHEN ReturnToStoreDate IS NULL THEN 1 ELSE 2 END
                                , CASE WHEN PermanentRecallDate IS NULL THEN 1 ELSE 2 END
                                , PermanentRecallDate DESC) PermanentRecallDate
       , FIRST_VALUE(ReturnToStoreDate)
               OVER (PARTITION BY ToyReferenceNumber
                         ORDER BY CASE WHEN ReturnToStoreDate IS NULL THEN 1 ELSE 2 END
                                , ReturnToStoreDate DESC) ReturnToStoreDate
    FROM ToyStaging
)
SELECT ts.*
  FROM ToyStaging TS
  JOIN Limits L
    ON TS.ToyReferenceNumber = L.ToyReferenceNumber
   AND (L.PermanentRecallDate IS NULL
        and ts.PermanentRecallDate is null
        OR TS.PermanentRecallDate = L.PermanentRecallDate)
   AND (L.ReturnToStoreDate IS NULL
        AND ts.ReturnToStoreDate is null
        OR TS.ReturnToStoreDate = L.ReturnToStoreDate)

In the Limits CTE the FIRST_VALUE analytic functions will both return null if a null null record exists for a given ToyReferenceNumber. Otherwise the PermanentRecallDate column will return the latest PermanentRecallDate, and the ReturnToStoreDate column will return the latest ReturnToStoreDate when no PermanentRecallDate exist thereby instantiating your rules as to which record to return.  The distinct prunes out the duplicate records, and then Limits is joined back to ToyStaging to get the desired data.

Given your sample data the Limits CTE returns:

| ToyReferenceNumber |    PermanentRecallDate |      ReturnToStoreDate |
|--------------------|------------------------|------------------------|
|       TTC-011-0934 |                 (null) | 2017-03-01 12:01:01.00 |
|       TTC-354-0122 |                 (null) |                 (null) |
|       TTC-994-0132 | 2017-06-12 12:01:01.00 |                 (null) |

and the whole query returns:

| ToyReferenceNumber | Company | CompositeCalculatedField |    PermanentRecallDate |      ReturnToStoreDate |
|--------------------|---------|--------------------------|------------------------|------------------------|
|       TTC-011-0934 |     TTC |              calculation |                 (null) | 2017-03-01 12:01:01.00 |
|       TTC-354-0122 |     TTC |              calculation |                 (null) |                 (null) |
|       TTC-994-0132 |     TTC |              calculation | 2017-06-12 12:01:01.00 |                 (null) |

See this SQL Fiddle to see it in action.


问:
Explaining margins and dealing with tiles
I have few problems that I cannot fix, I will be grateful if somebody will explain me how it works. Firstly, i have a container with id "kafle", I positioned it as I wanted, and now i want to place a few tiles into it. I want do something like this:  I want to tile 1 be 50% width of container with id "kafle", and tile to be another 50% width. I set margin and padding of tile 1 and 2 to 0, but despite this, there is something what makes that tile 2 is going under tile 1, and i don't know why. The other problem is that i don't know how i can place tile 3, 4, 5 and 6 under tile 1, but in one line with tile 2. When im setting display: inline-block to all of the tiles, tile 3, 4, 5 and 6 are going under height of tile 2. How can I deal with it? I will be grateful for explaining it.

html, body{
    height: 100%;
    min-height: 100%;
    margin:0;
}

#kafle{
    position:relative;
    height: 80%;
    width: 60%;
    top:10%;
    left:20%;
    background-color: aquamarine;
}

#onas{
    background-color: coral;
    height:33%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#aktualnosci{
    background-color: firebrick;
    height:90%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#galeria{
    background-color: forestgreen;
    height:10%;
    width:15%;
    display: inline-block;
}

#wspierajanas{
    background-color: khaki;
    height:10%;
    width:15%;
    display: inline-block;
}

#kontakt{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

#minigra{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <script src="javascript.js"></script>

    <div id="kafle">
        <div id="onas">1</div>
        <div id="aktualnosci">2</div>
       <div id="galeria">3</div>
        <div id="wspierajanas">4</div>
        <div id="kontakt">5</div>
        <div id="minigra">6</div>
    </div>

</body>

</html></code>```

答:
OK, because I hate myself, I decided to build this layout in CSS Grid (CSS Tricks article), which has spotty compatibility and no consistency.

Regardless, your layout is achievable using this fairly recent addition to CSS.  The trick is of course landing on a syntax that will work consistently for most browsers.  Below is one that seems to work well across the major ones.

html, body{
  height: 100%;
  min-height: 100%;
  margin:0;
}

#kafle{
  position:relative;
  height: 80%;
  width: 60%;
  top:10%;
  left:20%;
  background-color: aquamarine;

  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
  -ms-grid-rows: 1fr 1fr 1fr;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(3, 1fr);
  -webkit-box-align: stretch;
      -ms-flex-align: stretch;
          align-items: stretch;
  justify-items: stretch;
}

#onas{
  background-color: coral;
  grid-column: 1 / 4;
  grid-row: 1 / 2;
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 1;
  -ms-grid-row-span: 1;
}

#aktualnosci{
  background-color: firebrick;
  grid-column: 4 / 7;
  grid-row: 1 / 4;
  -ms-grid-column: 4;
  -ms-grid-column-span: 6;
  -ms-grid-row: 1;
  -ms-grid-row-span: 3;
}

#galeria{
  background-color: forestgreen;
  grid-column: 1 / 4;
  grid-row: 2 / 3;
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 2;
  -ms-grid-row-span: 1;
}

#wspierajanas{
  background-color: khaki;
  -ms-grid-column: 1;
  -ms-grid-column-span: 1;
  -ms-grid-row: 3;
  -ms-grid-row-span: 1;
}

#kontakt{
  background-color: fuchsia;
  -ms-grid-column: 2;
  -ms-grid-column-span: 1;
  -ms-grid-row: 3;
  -ms-grid-row-span: 1;
}

#minigra{
  background-color: fuchsia;
  -ms-grid-column: 3;
  -ms-grid-column-span: 1;
  -ms-grid-row: 3;
  -ms-grid-row-span: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="kafle">
  <div id="onas">1</div>
  <div id="aktualnosci">2</div>
  <div id="galeria">3</div>
  <div id="wspierajanas">4</div>
  <div id="kontakt">5</div>
  <div id="minigra">6</div>
</div></code>```

Body:
I have few problems that I cannot fix, I will be grateful if somebody will explain me how it works. Firstly, i have a container with id "kafle", I positioned it as I wanted, and now i want to place a few tiles into it. I want do something like this:  I want to tile 1 be 50% width of container with id "kafle", and tile to be another 50% width. I set margin and padding of tile 1 and 2 to 0, but despite this, there is something what makes that tile 2 is going under tile 1, and i don't know why. The other problem is that i don't know how i can place tile 3, 4, 5 and 6 under tile 1, but in one line with tile 2. When im setting display: inline-block to all of the tiles, tile 3, 4, 5 and 6 are going under height of tile 2. How can I deal with it? I will be grateful for explaining it.

html, body{
    height: 100%;
    min-height: 100%;
    margin:0;
}

#kafle{
    position:relative;
    height: 80%;
    width: 60%;
    top:10%;
    left:20%;
    background-color: aquamarine;
}

#onas{
    background-color: coral;
    height:33%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#aktualnosci{
    background-color: firebrick;
    height:90%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#galeria{
    background-color: forestgreen;
    height:10%;
    width:15%;
    display: inline-block;
}

#wspierajanas{
    background-color: khaki;
    height:10%;
    width:15%;
    display: inline-block;
}

#kontakt{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

#minigra{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">

1

2

3

4

5

6

Body:
OK, because I hate myself, I decided to build this layout in CSS Grid (CSS Tricks article), which has spotty compatibility and no consistency.

Regardless, your layout is achievable using this fairly recent addition to CSS.  The trick is of course landing on a syntax that will work consistently for most browsers.  Below is one that seems to work well across the major ones.

html, body{
  height: 100%;
  min-height: 100%;
  margin:0;
}

#kafle{
  position:relative;
  height: 80%;
  width: 60%;
  top:10%;
  left:20%;
  background-color: aquamarine;

  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
  -ms-grid-rows: 1fr 1fr 1fr;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(3, 1fr);
  -webkit-box-align: stretch;
      -ms-flex-align: stretch;
          align-items: stretch;
  justify-items: stretch;
}

#onas{
  background-color: coral;
  grid-column: 1 / 4;
  grid-row: 1 / 2;
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 1;
  -ms-grid-row-span: 1;
}

#aktualnosci{
  background-color: firebrick;
  grid-column: 4 / 7;
  grid-row: 1 / 4;
  -ms-grid-column: 4;
  -ms-grid-column-span: 6;
  -ms-grid-row: 1;
  -ms-grid-row-span: 3;
}

#galeria{
  background-color: forestgreen;
  grid-column: 1 / 4;
  grid-row: 2 / 3;
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 2;
  -ms-grid-row-span: 1;
}

#wspierajanas{
  background-color: khaki;
  -ms-grid-column: 1;
  -ms-grid-column-span: 1;
  -ms-grid-row: 3;
  -ms-grid-row-span: 1;
}

#kontakt{
  background-color: fuchsia;
  -ms-grid-column: 2;
  -ms-grid-column-span: 1;
  -ms-grid-row: 3;
  -ms-grid-row-span: 1;
}

#minigra{
  background-color: fuchsia;
  -ms-grid-column: 3;
  -ms-grid-column-span: 1;
  -ms-grid-row: 3;
  -ms-grid-row-span: 1;
}

<div id="kafle">
  <div id="onas">1</div>
  <div id="aktualnosci">2</div>
  <div id="galeria">3</div>
  <div id="wspierajanas">4</div>
  <div id="kontakt">5</div>
  <div id="minigra">6</div>
</div>


问:
Adding a new row erases my already added products on the invoice form in Ionic
I created invoice form. In order to add products, I have created a table with Add new row button to add products. Now when I am clicking it, it erases already added products.

My requirement is that when I click on Add new Row, my already added products in the table should not get erased.

Below is the image of my invoice.html form

invoice.html code of the table to add products

```<code>    <!--
  Generated template for the InvoicePage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
   <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>invoice</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
    <form #invoiceForm="ngForm" (ngSubmit)="onSubmit(invoiceForm.value)">
      <div>
            <input type="text" name="filterText" [(ngModel)]="filterText" style="float:left" (keypress)="isShow=true" (click)="isShow=true"/>
        </div>
      <div style="border: 1px solid #a9a9a9;width:35px;height: 23px;float: left;text-align:center;border-left: 0px;padding: 4px;" (click)="isShow = !isShow">
            <ion-icon ios="ios-arrow-dropdown" md="md-arrow-dropdown"></ion-icon>
        </div>
        <div><a style="margin-left:15px;text-decoration:none" (click)="addNewCust()">Add New Customer</a></div>
      <div style="clear:both;float:left;border: 1px solid #a9a9a9;width:198px;height:88px;overflow:auto;border-top:0px;cursor:pointer" *ngIf="isShow">
          <ul>
              <li *ngFor="let list of custList | filter:filterText" style="list-style:none" (click)="assignValue(list)">{{list.partyname}}</li>
            </ul>
        </div>
      <div style="clear:both;margin-top:120px">
            <label>Billing Address</label>
            <textarea name="address" [(ngModel)]="address"></textarea>
            <label>Terms</label>
            <select name="terms" ngModel>
                    <option>NET 15</option>
                    <option>NET 30</option>
             </select>
            <label>Invoice Date</label>
            <input type="text" name="invoiceDate" value="{{invoiceDate | date:d}}"/>
            <label>Due date</label>
            <input type="text" name="dueDate" value="{{dueDate | date:d}}"/>
        </div>
        <div style="clear:both">
            <label>Place of Supply</label>
            <select name="pos" ngModel>
                <option>Delhi</option>
                <option>Mumbai</option>
                <option>Bengaluru</option>
            </select>
        </div>
    <div style="margin-top:15px">
       <table>
              <tr>
                    <th></th>
                    <th>Product/Service</th>
                    <th>Description</th>
                    <th>Quantity</th>
                    <th>Rate</th>
                    <th>Amount</th>
                    <th>Tax</th>
                    <th></th>
                </tr>
                <tr *ngFor="let items of inVoiceItems;let i=index;">
                    <td>{{i+1}}</td>
                    <td style="width:198px">
                        <input type="text" name="prdText" [(ngModel)]="inVoiceItems[i].prdText" style="width:198px;border:0px"/>
                        <!--<div style="clear:both;border: 1px solid #a9a9a9;width:198px;height:88px;overflow:auto;cursor:pointer" *ngIf="isShowPrd">
                                <ul>
                                    <li *ngFor="let list of prdList" style="list-style:none" (click)="assignPrdValue(list,i)">{{list.PRODUCTSERVICE}}</li>
                                </ul>
                        </div>-->
                    </td>
                    <td><input type="text" name="prdDesc" [(ngModel)]="inVoiceItems[i].prdDesc" style="width:198px;border:0px"/></td>
                    <td><input type="text" name="prdQty" [(ngModel)]="inVoiceItems[i].prdQty" style="width:198px;border:0px"/></td>
                    <td><input type="text" name="prdRate" [(ngModel)]="inVoiceItems[i].prdRate" style="width:198px;border:0px"/></td>
                    <td><input type="text" name="prdAmt" [(ngModel)]="inVoiceItems[i].prdAmt" style="width:198px;border:0px"/></td>
                    <td><input type="text" name="prdTax" [(ngModel)]="inVoiceItems[i].prdTax" style="width:198px;border:0px"/></td>
                    <td style="text-align:center"><ion-icon ios="ios-trash" md="md-trash" (click)="deleteRow(i)"></ion-icon></td>
                </tr>
        </table>
        <input type="button" value="Add New Row" (click)="addRow()" style="margin-top:5px"/>
    </div>
    <div style="float:right">
            <input type="submit" value="Save">
        </div>
    </form>
</ion-content>
</code>```

invoice.ts code

```<code>  addRow(){
    this.inVoiceItems.push({'prdText':'','prdDesc':'','prdQty':'','prdRate':'','prdAmt':'','prdTax':''});
  }
</code>```

StackBlitz repo

答:
This is because we are dealing with a form. In template driven forms, the name attribute needs to be unique, so that the fields will not be evaluated as one and the same. So what is happening now, is that when you push an empty object, all fields get the empty object values, therefore you loose your data in the DOM. If you'd inspect your array, it actually has the correct values, this just affects the form values.

So solve this by giving the fields unique names, which can be achieved by adding the index, so for example in your iteration do this:

```<code><input name="prdDesc{{i}}" [(ngModel)]="inVoiceItems[i].prdDesc" />
</code>```

where we just add the index {{i}} in the name.

Here's your StackBlitz

Body:
I created invoice form. In order to add products, I have created a table with Add new row button to add products. Now when I am clicking it, it erases already added products.

My requirement is that when I click on Add new Row, my already added products in the table should not get erased.

Below is the image of my invoice.html form

invoice.html code of the table to add products

<ion-header>

  <ion-navbar>
   <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>invoice</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
    <form #invoiceForm="ngForm" (ngSubmit)="onSubmit(invoiceForm.value)">

            <input type="text" name="filterText" [(ngModel)]="filterText" style="float:left" (keypress)="isShow=true" (click)="isShow=true"/>

            <ion-icon ios="ios-arrow-dropdown" md="md-arrow-dropdown"></ion-icon>

Add New Customer

{{list.partyname}}

            Billing Address
            <textarea name="address" [(ngModel)]="address"></textarea>
            Terms
            <select name="terms" ngModel>
                    <option>NET 15</option>
                    <option>NET 30</option>
             </select>
            Invoice Date
            <input type="text" name="invoiceDate" value="{{invoiceDate | date:d}}"/>
            Due date
            <input type="text" name="dueDate" value="{{dueDate | date:d}}"/>

            Place of Supply
            <select name="pos" ngModel>
                <option>Delhi</option>
                <option>Mumbai</option>
                <option>Bengaluru</option>
            </select>

                    Product/Service
                    Description
                    Quantity
                    Rate
                    Amount
                    Tax

                    {{i+1}}

                        <input type="text" name="prdText" [(ngModel)]="inVoiceItems[i].prdText" style="width:198px;border:0px"/>

                    <input type="text" name="prdDesc" [(ngModel)]="inVoiceItems[i].prdDesc" style="width:198px;border:0px"/>
                    <input type="text" name="prdQty" [(ngModel)]="inVoiceItems[i].prdQty" style="width:198px;border:0px"/>
                    <input type="text" name="prdRate" [(ngModel)]="inVoiceItems[i].prdRate" style="width:198px;border:0px"/>
                    <input type="text" name="prdAmt" [(ngModel)]="inVoiceItems[i].prdAmt" style="width:198px;border:0px"/>
                    <input type="text" name="prdTax" [(ngModel)]="inVoiceItems[i].prdTax" style="width:198px;border:0px"/>
                    <ion-icon ios="ios-trash" md="md-trash" (click)="deleteRow(i)"></ion-icon>

        <input type="button" value="Add New Row" (click)="addRow()" style="margin-top:5px"/>

            <input type="submit" value="Save">

    </form>
</ion-content>

invoice.ts code

  addRow(){
    this.inVoiceItems.push({'prdText':'','prdDesc':'','prdQty':'','prdRate':'','prdAmt':'','prdTax':''});
  }

StackBlitz repo

Body:
This is because we are dealing with a form. In template driven forms, the name attribute needs to be unique, so that the fields will not be evaluated as one and the same. So what is happening now, is that when you push an empty object, all fields get the empty object values, therefore you loose your data in the DOM. If you'd inspect your array, it actually has the correct values, this just affects the form values.

So solve this by giving the fields unique names, which can be achieved by adding the index, so for example in your iteration do this:

<input name="prdDesc{{i}}" [(ngModel)]="inVoiceItems[i].prdDesc" />

where we just add the index {{i}} in the name.

Here's your StackBlitz


问:
Xamarin.Forms x:Shared
I have an issue with a Xamarin.Forms application I am currently working on. The resource I have created is being used within multiple controls, the controls are using the same object to render out onto the screen. I thought using the x:Shared="False" attribute (as per https://learn.microsoft.com/en-us/dotnet/framework/xaml-services/x-shared-attribute) would get around this. It does not :( Any ideas how to create the same object in .xaml without having to define multiple resources?

```<code><Grid.Resources>
 <ResourceDictionary>
   <SharedShapes:Circle x:Shared="False" x:Key="SpecCircle" Color="{StaticResource AccentColor}"/>
 </ResourceDictionary>
</Grid.Resources>

<SharedControls:ImageButton Grid.Row="0" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
.
.
.
</code>```

Many thanks in advance!

答:
That's not supported in Xamarin.Forms. To get a new instance you'd have to specify it via property element syntax using something like this:</p>

```<code><SharedControls:ImageButton Grid.Row="0" Grid.Column="0">
  <SharedControls:ImageButton.Shape>
    <SharedShapes:Circle x:Shared="False" x:Key="SpecCircle" Color="...."/>
  </SharedControls:ImageButton.Shape>
</SharedControls:ImageButton>
</code>```

Title: Xamarin.Forms x:Shared

Body:
I have an issue with a Xamarin.Forms application I am currently working on. The resource I have created is being used within multiple controls, the controls are using the same object to render out onto the screen. I thought using the x:Shared="False" attribute (as per https://learn.microsoft.com/en-us/dotnet/framework/xaml-services/x-shared-attribute) would get around this. It does not :( Any ideas how to create the same object in .xaml without having to define multiple resources?

<Grid.Resources>
 <ResourceDictionary>
   <SharedShapes:Circle x:Shared="False" x:Key="SpecCircle" Color="{StaticResource AccentColor}"/>
 </ResourceDictionary>
</Grid.Resources>

<SharedControls:ImageButton Grid.Row="0" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
.
.
.

Many thanks in advance!

Body:
That's not supported in Xamarin.Forms. To get a new instance you'd have to specify it via property element syntax using something like this:

<SharedControls:ImageButton Grid.Row="0" Grid.Column="0">
  <SharedControls:ImageButton.Shape>
    <SharedShapes:Circle x:Shared="False" x:Key="SpecCircle" Color="...."/>
  </SharedControls:ImageButton.Shape>
</SharedControls:ImageButton>


问:
Python 3 changing variable inside function without using global variables
So i am currently working on a university project, therefore i can't really paste my code to be more specific, but we have this stupid rule that global variables are not allowed and using them would lead to points removal. So my question is:
I am making a  roll the dice game, where a couple of players take turns and i need a variable that identifies which player is on turn. I have a function, which represents each turn and a second, which calls the first function multiple times, which is equal to the number of players. Lets say i have 3 players:

```<code>def func1():
    player_on_turn = 1
    result = 0
    print('Player',player_on_turn,'is on turn.')
    #something
    return result

def func2():
    players = 3
    for player in range(1,players+1):
        player = func1()

func2()
</code>```

So this variable player_on_turn has to change 3 times, meaning for each call of the function. The first call it is equal to 1, the second to 2, etc.
I've done this already with global variable, but apparently i can't use them, because "it makes the code hard to read". In the first function i am already using return for a one value which changes inside the function and is being reset each call. Is there a way i could probably do this? Thanks in advance!

答:
You can use Function Parameters to pass data between functions.

You can also use a Class to create objects that store data without global variables.

Body:
So i am currently working on a university project, therefore i can't really paste my code to be more specific, but we have this stupid rule that global variables are not allowed and using them would lead to points removal. So my question is:
I am making a  roll the dice game, where a couple of players take turns and i need a variable that identifies which player is on turn. I have a function, which represents each turn and a second, which calls the first function multiple times, which is equal to the number of players. Lets say i have 3 players:

def func1():
    player_on_turn = 1
    result = 0
    print('Player',player_on_turn,'is on turn.')
    #something
    return result

def func2():
    players = 3
    for player in range(1,players+1):
        player = func1()

func2()

So this variable player_on_turn has to change 3 times, meaning for each call of the function. The first call it is equal to 1, the second to 2, etc.
I've done this already with global variable, but apparently i can't use them, because "it makes the code hard to read". In the first function i am already using return for a one value which changes inside the function and is being reset each call. Is there a way i could probably do this? Thanks in advance!


问:
Full Outer Join self with null values
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

```<code>N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6
</code>```

(where N is a general index column to enable a self-join on sequential groups) and I do:

```<code>SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name
</code>```

I want:

```<code>N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6
</code>```

but what I get is more like a cross-join:

```<code>n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6
</code>```

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

答:
Maybe this:</p>

```<code>SELECT [Name]
       ,[1]
       ,[2]
FROM [table]
PIVOT
(
    MAX([val]) FOR [N] IN ([1], [2])
) PVT;
</code>```

Title: Full Outer Join self with null values

Body:
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6

(where N is a general index column to enable a self-join on sequential groups) and I do:

SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name

I want:

N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6

but what I get is more like a cross-join:

n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

Body:
Maybe this:

SELECT [Name]
       ,[1]
       ,[2]
FROM [table]
PIVOT
(
    MAX([val]) FOR [N] IN ([1], [2])
) PVT;


问:
Spring JWT signature Validation fails
I am building microservice applications with spring cloud, oauth and JWT. My Oauth2 server generates JWT token but when I am trying to validate the token in gateway (implemented using ZUUL) I am getting below Error

Could you please let me know what is wrong and what could be the solution.
I am using Spring 4.3, Spring boot 1.5.8, Spring cloud Dalston.SR4

```<code>org.springframework.security.jwt.crypto.sign.InvalidSignatureException: Calculated signature did not match actual value
    at org.springframework.security.jwt.crypto.sign.MacSigner.verify(MacSigner.java:62) ~[spring-security-jwt-1.0.8.RELEASE.jar:na]
    at org.springframework.security.jwt.JwtImpl.verifySignature(JwtHelper.java:287) ~[spring-security-jwt-1.0.8.RELEASE.jar:na]
    at org.springframework.security.jwt.JwtHelper.decodeAndVerify(JwtHelper.java:77) ~[spring-security-jwt-1.0.8.RELEASE.jar:na]
    at com.debopam.gateway.filter.CustomPostZuulFilter.run(CustomPostZuulFilter.java:57) ~[classes/:na]
    at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:193) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:157) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.postRoute(FilterProcessor.java:92) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.ZuulRunner.postRoute(ZuulRunner.java:87) [zuul-core-1.3.0.jar:1.3.0]
</code>```

I have used signing key 12345AsDfG in both Auth server and gateway server.

Below Are the code snippet
Auth Server

```<code>@Configuration
public class JWTTokenStoreConfig {

    @Autowired
    private ServiceConfig serviceConfig;

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setAccessTokenValiditySeconds(60*30);
        return defaultTokenServices;
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(serviceConfig.getJwtSigningKey());
        return converter;
    }

    @Bean
    public TokenEnhancer jwtTokenEnhancer() {
        return new JWTTokenEnhancer();
    }
}

@Configuration
public class JWTOAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private DefaultTokenServices tokenServices;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private TokenEnhancer jwtTokenEnhancer;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
    {
        //oauthServer.checkTokenAccess("permitAll()");

        oauthServer
        .tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')")
        .checkTokenAccess("permitAll()");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtTokenEnhancer, jwtAccessTokenConverter));

        endpoints.tokenStore(tokenStore)                             //JWT
                .accessTokenConverter(jwtAccessTokenConverter)       //JWT
                .tokenEnhancer(tokenEnhancerChain)                   //JWT
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
                .withClient("uiapp")
                .secret("secret")
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }
}
</code>```

In the Gateway application, I am using below code to verify the Token

```<code>@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    try {
        InputStream is = ctx.getResponseDataStream();
        String responseBody = IOUtils.toString(is);

        if (StringUtils.hasText(responseBody)
                && responseBody.contains("access_token")) {
            Map<String, Object> responseMap = objectMapper.readValue(
                    responseBody, new TypeReference<Map<String, Object>>() {});
            String accesToken = responseMap.get("access_token").toString();

            Jwt jwt = JwtHelper.decodeAndVerify(accesToken, new MacSigner(serviceConfig.getJwtSigningKey()));

            System.out.println(jwt.getClaims());
            //System.out.println(jwt.getBody());

        }
        ctx.setResponseBody(responseBody);
    } catch (Exception e) {
        logger.error("Error occured in zuul post filter", e);
    }
    return null;
}
</code>```

答: There was a signing key mismatch between the services.</p>

Title: Spring JWT signature Validation fails

Body:
I am building microservice applications with spring cloud, oauth and JWT. My Oauth2 server generates JWT token but when I am trying to validate the token in gateway (implemented using ZUUL) I am getting below Error

Could you please let me know what is wrong and what could be the solution.
I am using Spring 4.3, Spring boot 1.5.8, Spring cloud Dalston.SR4

org.springframework.security.jwt.crypto.sign.InvalidSignatureException: Calculated signature did not match actual value
    at org.springframework.security.jwt.crypto.sign.MacSigner.verify(MacSigner.java:62) ~[spring-security-jwt-1.0.8.RELEASE.jar:na]
    at org.springframework.security.jwt.JwtImpl.verifySignature(JwtHelper.java:287) ~[spring-security-jwt-1.0.8.RELEASE.jar:na]
    at org.springframework.security.jwt.JwtHelper.decodeAndVerify(JwtHelper.java:77) ~[spring-security-jwt-1.0.8.RELEASE.jar:na]
    at com.debopam.gateway.filter.CustomPostZuulFilter.run(CustomPostZuulFilter.java:57) ~[classes/:na]
    at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:193) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:157) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.FilterProcessor.postRoute(FilterProcessor.java:92) [zuul-core-1.3.0.jar:1.3.0]
    at com.netflix.zuul.ZuulRunner.postRoute(ZuulRunner.java:87) [zuul-core-1.3.0.jar:1.3.0]

I have used signing key 12345AsDfG in both Auth server and gateway server.

Below Are the code snippet
Auth Server

@Configuration
public class JWTTokenStoreConfig {

    @Autowired
    private ServiceConfig serviceConfig;

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setAccessTokenValiditySeconds(60*30);
        return defaultTokenServices;
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(serviceConfig.getJwtSigningKey());
        return converter;
    }

    @Bean
    public TokenEnhancer jwtTokenEnhancer() {
        return new JWTTokenEnhancer();
    }
}

@Configuration
public class JWTOAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private DefaultTokenServices tokenServices;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private TokenEnhancer jwtTokenEnhancer;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
    {
        //oauthServer.checkTokenAccess("permitAll()");

        oauthServer
        .tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')")
        .checkTokenAccess("permitAll()");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtTokenEnhancer, jwtAccessTokenConverter));

        endpoints.tokenStore(tokenStore)                             //JWT
                .accessTokenConverter(jwtAccessTokenConverter)       //JWT
                .tokenEnhancer(tokenEnhancerChain)                   //JWT
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
                .withClient("uiapp")
                .secret("secret")
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }
}

In the Gateway application, I am using below code to verify the Token

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    try {
        InputStream is = ctx.getResponseDataStream();
        String responseBody = IOUtils.toString(is);

        if (StringUtils.hasText(responseBody)
                && responseBody.contains("access_token")) {
            Map<String, Object> responseMap = objectMapper.readValue(
                    responseBody, new TypeReference<Map<String, Object>>() {});
            String accesToken = responseMap.get("access_token").toString();

            Jwt jwt = JwtHelper.decodeAndVerify(accesToken, new MacSigner(serviceConfig.getJwtSigningKey()));

            System.out.println(jwt.getClaims());
            //System.out.println(jwt.getBody());

        }
        ctx.setResponseBody(responseBody);
    } catch (Exception e) {
        logger.error("Error occured in zuul post filter", e);
    }
    return null;
}


问:
Change the content (different languages) of React Components when clicking on a button
I want to create a React Website where you can click on a button and change the language to German or English. I'm new to React and still learning.

I created a simple JSON that looks like this:

```<code>{
  "de": {
    "header": "Willkommen",
    "footer": "Auf Wiedersehen"
  },
  "eng": {
    "header": "Welcome",
    "footer": "Goodbye"
  }
}
</code>```

I created a button that toggles its state when onClick. But I think state is the wrong way to do this if I want to access it everywhere.

```<code>class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isOn: true};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    if (this.state.isOn) {
      this.setState({isOn: false})
    } else {
      this.setState({isOn: true})
    }
  }
  render() {
    return(
      <button type="button" onClick={this.handleClick}>DE/ENG{JSON.stringify(this.state.isOn)}</button>
    );
  }
}
</code>```

And now I want to import the JSON data and put the right one in the components. This one down here isn't working. I don't know how to do it. Every component should get the German or English data when the button is clicked. I want to use it in many components. (It's working when I use const data = DATA.de for example but that won't change the content when I click the button.)

```<code>import DATA from './data.json';

class Main extends React.Component {
  render() {
    const data = Button.state.isOn ? DATA.de : DATA.eng;
    return (
      <div>
        <Button onIsOnChange={this.buttonChange} />
        <span>{data.header}</span>
      </div>
    );
  }
}
</code>```

Do you know how to do this?

答:
I would suggest to change your design a bit. Create a language change (call it 'onLanguaheChange' for example) method on Main component and pass it as a prop to you Button component,

```<code><Button onClick={this.onLanguageChange}.../>
</code>```

now, inside Button component, you can just call  this.props.onClick(...) and pass it the selected/required language. It will call the Main componemt method onLanguageChange with your parameter. Then you can change Main's state as desired, and pass it to what ever component you'd like.

Body:
I want to create a React Website where you can click on a button and change the language to German or English. I'm new to React and still learning.

I created a simple JSON that looks like this:

{
  "de": {
    "header": "Willkommen",
    "footer": "Auf Wiedersehen"
  },
  "eng": {
    "header": "Welcome",
    "footer": "Goodbye"
  }
}

I created a button that toggles its state when onClick. But I think state is the wrong way to do this if I want to access it everywhere.

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isOn: true};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    if (this.state.isOn) {
      this.setState({isOn: false})
    } else {
      this.setState({isOn: true})
    }
  }
  render() {
    return(
      <button type="button" onClick={this.handleClick}>DE/ENG{JSON.stringify(this.state.isOn)}</button>
    );
  }
}

And now I want to import the JSON data and put the right one in the components. This one down here isn't working. I don't know how to do it. Every component should get the German or English data when the button is clicked. I want to use it in many components. (It's working when I use const data = DATA.de for example but that won't change the content when I click the button.)

import DATA from './data.json';

class Main extends React.Component {
  render() {
    const data = Button.state.isOn ? DATA.de : DATA.eng;
    return (

        <Button onIsOnChange={this.buttonChange} />
        {data.header}

    );
  }
}

Do you know how to do this?

Body:
I would suggest to change your design a bit. Create a language change (call it 'onLanguaheChange' for example) method on Main component and pass it as a prop to you Button component,

<Button onClick={this.onLanguageChange}.../>

now, inside Button component, you can just call  this.props.onClick(...) and pass it the selected/required language. It will call the Main componemt method onLanguageChange with your parameter. Then you can change Main's state as desired, and pass it to what ever component you'd like.


问:
Gradle v4.3.1 for android studio 2.3.3
I'm using Android Studio 2.3.3, Gradle latest release V4.3.1 is not fixing my "re-download dependencies and sync project (requires network)" problem what should i do? </p>

答:
You need to upgrade the Android Studio to 3.0.0 to use gradle-4.1-all.zip

Once upgrade if you want to use the Android Studio 2.3.3 then

go to "File->Setting->Build,Execution,deployment->Gradle"

Select "Use local gradle distribution" and select the gradle path.

Mostly gradle will be present in C:\Users\'your system user name'\.gradle

Title: Gradle v4.3.1 for android studio 2.3.3