问:
How to save lambda function using numpy savez?
I know savez_compressed can save the functions generated from scipy. Is there any way to save lambda functions?

Attempt:

```<code>import numpy as np
from scipy.interpolate import interp1d
xAxis = np.array([1,2,3,4])
data = np.array([1,3,5,6])

yAxisInterp = interp1d(xAxis, data, kind='linear')

np.savez_compressed('myDataLambda.npz', yAxisInterp=yAxisInterp)
print('yAxisInterp is saved')

# Following command does not work
# ------------------------------
yAxisLambda = lambda x : x

np.savez_compressed('myData.npz', yAxisLambda=yAxisLambda)
print('yAxisLambda is saved')
</code>```

答:
No, numpy.savez does not save the functions in scipy, it saves numpy.ndarray objects, which are returned from those scipy functions.

That is, when you do:

```<code>yAxisInterp = interp1d(xAxis, data, kind='linear')
</code>```

You've created an array, and that is what you are saving when you do:

```<code>np.savez_compressed('myDataLambda.npz', yAxisInterp=yAxisInterp)
</code>```

You are not saving the function.

So no, you cannot save functions, any functions, with numpy.savez (and related methods).

Body:
I know savez_compressed can save the functions generated from scipy. Is there any way to save lambda functions?

Attempt:

import numpy as np
from scipy.interpolate import interp1d
xAxis = np.array([1,2,3,4])
data = np.array([1,3,5,6])

yAxisInterp = interp1d(xAxis, data, kind='linear')

np.savez_compressed('myDataLambda.npz', yAxisInterp=yAxisInterp)
print('yAxisInterp is saved')

# Following command does not work
# ------------------------------
yAxisLambda = lambda x : x

np.savez_compressed('myData.npz', yAxisLambda=yAxisLambda)
print('yAxisLambda is saved')

Body:
No, numpy.savez does not save the functions in scipy, it saves numpy.ndarray objects, which are returned from those scipy functions.

That is, when you do:

yAxisInterp = interp1d(xAxis, data, kind='linear')

You've created an array, and that is what you are saving when you do:

np.savez_compressed('myDataLambda.npz', yAxisInterp=yAxisInterp)

You are not saving the function.

So no, you cannot save functions, any functions, with numpy.savez (and related methods).


来源: stackexchange

问:
Merge objects according to their keys and values
I have edited the original question as the example did not make the desired output clear, namely I did not specify that I needed the strings that are common with the object that matches the Rank

I am trying to merge an array of objects into a single object

There are three sets of keys per object, I would like to have just one instance of each set with its lowest number for the Rank value or if the Rank equals '-' on all objects.

let objs = [
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 1,
    'Third Title': 'Title for 1',
    'Third URL': 'https://for-one.example.com'
  },
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': 2,
    'Second Title': 'Title for 2',
    'Second URL': 'https://for-two.example.com',
    'Third Rank': '-',
    'Third Title': '-',
    'Third URL': '-'
  },
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 7,
    'Third Title': 'Title for 7',
    'Third URL': 'https://for-seven.example.com'
  }
]

// I have managed to get the ones with values with this:

const clean = objs.reduce((acc, object) => {
  const clone = (({ Keyword, ...obj }) => obj)(object)

  if (Object.values(clone).some(val => val !== '-')) {
    Object.keys(clone).forEach(key => object[key] === '-' && delete object[key])
    acc.push(object)
  }

  return acc
}, [])

const merged = clean.reduce((result, current) => ({ ...current, ...result }), {})

console.log(merged)```
</div>
</div>
</p>

<p>But I am struggling to add the one with no values, it should look like this:</p>

```{
  'Keyword': 'A keyword',
  'First Rank': '-',
  'First Title': '-',
  'First URL': '-',
  'Second Rank': 2,
  'Second Title': 'Title for 2',
  'Second URL': 'https://for-two.example.com',
  'Third Rank': 1,
  'Third Title': 'Title for 1',
  'Third URL': 'https://for-one.example.com'
}
```

Any ideas? Thanks!

答:
Thanks to everyone who answered this question, however I did not explain in detail some requirements and when I did it was too late to get a follow up response, so I made my own, I am sure there is a better way to do it, but this works.

let objs = [
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 1,
    'Third Title': 'Title for 1',
    'Third URL': 'https://for-one.example.com'
  },
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': 2,
    'Second Title': 'Title for 2',
    'Second URL': 'https://for-two.example.com',
    'Third Rank': '-',
    'Third Title': '-',
    'Third URL': '-'
  },
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 7,
    'Third Title': 'Title for 7',
    'Third URL': 'https://for-seven.example.com'
  }
]

// Remove dashed entries and keep only the ones with data
const removeDashed = objs.reduce((acc, object) => {
  // Clone object except for the keyword key
  const clone = (({ Keyword, ...obj }) => obj)(object)
  if (Object.values(clone).some(val => val !== '-')) {
    Object.keys(object).forEach(key => object[key] === '-' && delete object[key])
    acc.push(object)
  }
  return acc
}, [])

// Merge array into a single object with first entries found first
const merged = removeDashed.reduce((result, current) => ({ ...current, ...result }), {})

// Items that should be present
const items = ['First', 'Second', 'Third']

// Get the existing keys from the unique obj
const keys = Object.keys(merged).map(key => key.split(' ')[0])

// If one or more items are missing insert them and add dashed values
items.forEach(item => {
  if (!keys.includes(item)) {
    merged[`${item} Rank`] = '-'
    merged[`${item} Title`] = '-'
    merged[`${item} URL`] = '-'
  }
})

// Sort function to reorder | thanks to Soc for this
const sorting = item => (a, b) => {
  const alphaOrder = a  b ? 1 : 0

  if (a === 'Keyword') return -1
  if (b === 'Keyword') return 1
  if (a.startsWith(item) && b.startsWith(item)) return alphaOrder
  if (a.startsWith(item)) return -1
  if (b.startsWith(item)) return 1

  return alphaOrder
}

// Implement the sorting
const result = Object.keys(merged)
  .sort(sorting(items[0]))
  .reduce((acc, current) => {
    acc[current] = merged[current]
    return acc
  }, {})

console.log(result)```

ContentLicense: CC BY-SA 4.0

Body:
I have edited the original question as the example did not make the desired output clear, namely I did not specify that I needed the strings that are common with the object that matches the Rank

I am trying to merge an array of objects into a single object

There are three sets of keys per object, I would like to have just one instance of each set with its lowest number for the Rank value or if the Rank equals '-' on all objects.

let objs = [
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 1,
    'Third Title': 'Title for 1',
    'Third URL': 'https://for-one.example.com'
  },
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': 2,
    'Second Title': 'Title for 2',
    'Second URL': 'https://for-two.example.com',
    'Third Rank': '-',
    'Third Title': '-',
    'Third URL': '-'
  },
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 7,
    'Third Title': 'Title for 7',
    'Third URL': 'https://for-seven.example.com'
  }
]

// I have managed to get the ones with values with this:

const clean = objs.reduce((acc, object) => {
  const clone = (({ Keyword, ...obj }) => obj)(object)

  if (Object.values(clone).some(val => val !== '-')) {
    Object.keys(clone).forEach(key => object[key] === '-' && delete object[key])
    acc.push(object)
  }

  return acc
}, [])

const merged = clean.reduce((result, current) => ({ ...current, ...result }), {})

console.log(merged)

But I am struggling to add the one with no values, it should look like this:

{
  'Keyword': 'A keyword',
  'First Rank': '-',
  'First Title': '-',
  'First URL': '-',
  'Second Rank': 2,
  'Second Title': 'Title for 2',
  'Second URL': 'https://for-two.example.com',
  'Third Rank': 1,
  'Third Title': 'Title for 1',
  'Third URL': 'https://for-one.example.com'
}

Any ideas? Thanks!

Body:
Thanks to everyone who answered this question, however I did not explain in detail some requirements and when I did it was too late to get a follow up response, so I made my own, I am sure there is a better way to do it, but this works.

let objs = [
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 1,
    'Third Title': 'Title for 1',
    'Third URL': 'https://for-one.example.com'
  },
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': 2,
    'Second Title': 'Title for 2',
    'Second URL': 'https://for-two.example.com',
    'Third Rank': '-',
    'Third Title': '-',
    'Third URL': '-'
  },
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 7,
    'Third Title': 'Title for 7',
    'Third URL': 'https://for-seven.example.com'
  }
]

// Remove dashed entries and keep only the ones with data
const removeDashed = objs.reduce((acc, object) => {
  // Clone object except for the keyword key
  const clone = (({ Keyword, ...obj }) => obj)(object)
  if (Object.values(clone).some(val => val !== '-')) {
    Object.keys(object).forEach(key => object[key] === '-' && delete object[key])
    acc.push(object)
  }
  return acc
}, [])

// Merge array into a single object with first entries found first
const merged = removeDashed.reduce((result, current) => ({ ...current, ...result }), {})

// Items that should be present
const items = ['First', 'Second', 'Third']

// Get the existing keys from the unique obj
const keys = Object.keys(merged).map(key => key.split(' ')[0])

// If one or more items are missing insert them and add dashed values
items.forEach(item => {
  if (!keys.includes(item)) {
    merged[`${item} Rank`] = '-'
    merged[`${item} Title`] = '-'
    merged[`${item} URL`] = '-'
  }
})

// Sort function to reorder | thanks to Soc for this
const sorting = item => (a, b) => {
  const alphaOrder = a < b ? -1 : a > b ? 1 : 0

  if (a === 'Keyword') return -1
  if (b === 'Keyword') return 1
  if (a.startsWith(item) && b.startsWith(item)) return alphaOrder
  if (a.startsWith(item)) return -1
  if (b.startsWith(item)) return 1

  return alphaOrder
}

// Implement the sorting
const result = Object.keys(merged)
  .sort(sorting(items[0]))
  .reduce((acc, current) => {
    acc[current] = merged[current]
    return acc
  }, {})

console.log(result)


问:
How to combine multiple fviz_dist plots into one plot
I have unsuccessfully tried to combine multiple fviz_dist (factoextra package) plots into one plot using par(mfrow=c(2,2)) and by naming the plots and adding them e.g., PlotA + PlotB (as I have seen with histograms).

looking forward to hearing your tips and tricks

```<code>#Generates 4 individual plots
par(mfrow=c(2,2))
fviz_dist(dist.euclraw)
fviz_dist(dist.euclscaled)
fviz_dist(dist.corraw)
fviz_dist(dist.corscaled)
</code>```

答:
There are 2 ways you can do it like</p>

```<code>library(factoextra)
library(ggpubr)
library(gridExtra)

data(USArrests)
dist.pearson <- get_dist(USArrests, stand = TRUE, method = "pearson")
dist.euclraw <- get_dist(USArrests, stand = TRUE, method = "euclidean")

p1 <- fviz_dist(dist.pearson)
p2 <- fviz_dist(dist.euclraw)
ggpubr::ggarrange(p1,p2)
gridExtra::grid.arrange(p1,p2)
</code>```

Body:
I have unsuccessfully tried to combine multiple fviz_dist (factoextra package) plots into one plot using par(mfrow=c(2,2)) and by naming the plots and adding them e.g., PlotA + PlotB (as I have seen with histograms).

looking forward to hearing your tips and tricks

#Generates 4 individual plots
par(mfrow=c(2,2))
fviz_dist(dist.euclraw)
fviz_dist(dist.euclscaled)
fviz_dist(dist.corraw)
fviz_dist(dist.corscaled)

Body:
There are 2 ways you can do it like

library(factoextra)
library(ggpubr)
library(gridExtra)

data(USArrests)
dist.pearson <- get_dist(USArrests, stand = TRUE, method = "pearson")
dist.euclraw <- get_dist(USArrests, stand = TRUE, method = "euclidean")

p1 <- fviz_dist(dist.pearson)
p2 <- fviz_dist(dist.euclraw)
ggpubr::ggarrange(p1,p2)
gridExtra::grid.arrange(p1,p2)


问:
Gulp throws error 'Must use import to load ES Module'
We're converting our gulpfile.js in node v13.8.0 to ES6 as following:

import { src, dest, series, parallel, watch } from 'gulp'
import nodemon from 'gulp-nodemon' // normal nodemon does not display an error on app crash
import env from 'gulp-env'
import browser from 'browser-sync'
import sass from 'gulp-sass'
// Tasks
export default {
    cssTranspile: cssTranspile,
    jsTranspile: jsTranspile,
    server: series(startNodemon, startBrowserSync),
    default: series(
        parallel(
            cssTranspile,
            jsTranspile
        ),
        startNodemon,
        startBrowserSync,
        function () {
            watch('public/scss/*.scss', cssTranspile)
        }
    )
}
```

<p>The error reported, when simply running <code>gulp</code>, is:</p>

```internal/modules/cjs/loader.js:1160
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: T:\Node\ICP\gulpfile.js
require() of ES modules is not supported.
```

<p>I must be doing something wrong. Anyone an idea on what it might be? </p>

```CLI version: 2.2.0
Local version: 4.0.2
```

<p>The flag <code>"type": "module",</code> is set in <code>package.json</code> as described in the note docs. The issue is very much similar to this issue in the geolib library.</p>

<p>And when we rename <code>gulpfile.js</code> to <code>gulpfile.babel.js</code> as described here we get the same error.</p>

<p>The <code>package.json</code> contain these packages:</p>

<pre class="lang-js prettyprint-override"><code>  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "@babel/register": "^7.8.3",
    "exports-loader": "^0.7.0",
    "gulp": "^4.0.2",
    "gulp-env": "^0.4.0",
    "gulp-nodemon": "^2.4.2",
    "gulp-sass": "^4.0.2",
    "nodemon": "^2.0.2"
  },
  "type": "module",
  "babel": {
    "presets": [
      "@babel/env"
    ]
</code>```

答: In an answer to my own question, when the flag "type": "module" is set in package.json you can't use gulp. More info can be found here.

Body:
We're converting our gulpfile.js in node v13.8.0 to ES6 as following:

import { src, dest, series, parallel, watch } from 'gulp'
import nodemon from 'gulp-nodemon' // normal nodemon does not display an error on app crash
import env from 'gulp-env'
import browser from 'browser-sync'
import sass from 'gulp-sass'
// Tasks
export default {
    cssTranspile: cssTranspile,
    jsTranspile: jsTranspile,
    server: series(startNodemon, startBrowserSync),
    default: series(
        parallel(
            cssTranspile,
            jsTranspile
        ),
        startNodemon,
        startBrowserSync,
        function () {
            watch('public/scss/*.scss', cssTranspile)
        }
    )
}

The error reported, when simply running gulp, is:

internal/modules/cjs/loader.js:1160
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: T:\Node\ICP\gulpfile.js
require() of ES modules is not supported.

I must be doing something wrong. Anyone an idea on what it might be?

CLI version: 2.2.0
Local version: 4.0.2

The flag "type": "module", is set in package.json as described in the note docs. The issue is very much similar to this issue in the geolib library.

And when we rename gulpfile.js to gulpfile.babel.js as described here we get the same error.

The package.json contain these packages:

  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "@babel/register": "^7.8.3",
    "exports-loader": "^0.7.0",
    "gulp": "^4.0.2",
    "gulp-env": "^0.4.0",
    "gulp-nodemon": "^2.4.2",
    "gulp-sass": "^4.0.2",
    "nodemon": "^2.0.2"
  },
  "type": "module",
  "babel": {
    "presets": [
      "@babel/env"
    ]


问:
SQL Find MAX Values for multiple rows
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400
```

<p>SQL Statement as to return the Max Number per Name. </p>

<p>desired outcome </p>

<pre class="lang-none prettyprint-override"><code>Alabama  354    300
Atlas    800    400
</code>```

答:
You can use just max function to find the maximum value

like.

```<code>SELECT Name,MAX(Number),MAX(Value)
FROM myTable
GROUP BY Name
</code>```

Title: SQL Find MAX Values for multiple rows

Body:
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400

SQL Statement as to return the Max Number per Name.

desired outcome

Alabama  354    300
Atlas    800    400

Body:
You can use just max function to find the maximum value

like.

SELECT Name,MAX(Number),MAX(Value)
FROM myTable
GROUP BY Name


问:
How do we extract named entities in scala using any nlp library
I have a huge text file and I have to extract only named entites in from this file. I am using Scala language and Databricks cluster for this.

```<code>val input = sc.textFile('....Mypath...').flatMap(line => line.split("""\W+"""))

val namedEnt = something(input)
</code>```

Can anyone tell what to code to get named entities?

答:
If you convert your input to a DataFrame (ex: .toDF), this is how you can get the Named Entities out:

Just an example of Spark NLP installation

spark-shell --packages JohnSnowLabs:spark-nlp:2.4.0
```

<p>Actual example:</p>

<pre class="lang-scala prettyprint-override"><code>import com.johnsnowlabs.nlp.pretrained.PretrainedPipeline
import com.johnsnowlabs.nlp.SparkNLP

SparkNLP.version()
// make sure you are using the latest release 2.4.x

// Download and load the pre-trained pipeline that has NER in English
// Full list: https://github.com/JohnSnowLabs/spark-nlp-models
val pipeline = PretrainedPipeline("recognize_entities_dl", lang="en")

//Transfrom your DataFrame to a new DataFrame that has NER column
val annotation = pipeline.transform(inputDF)

// This would look something like this:
/*
+---+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
| id|                text|            document|            sentence|               token|          embeddings|                 ner|       entities|
+---+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|  1|Google has announ...|[[document, 0, 10...|[[document, 0, 10...|[[token, 0, 5, Go...|[[word_embeddings...|[[named_entity, 0...|[[chunk, 0, 5, Go...|
|  2|Donald John Trump...|[[document, 0, 92...|[[document, 0, 92...|[[token, 0, 5, Do...|[[word_embeddings...|[[named_entity, 0...|[[chunk, 0, 16, D...|
+---+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
*/

// This is where the results for entities are:

annotation.select("entities.result").show

</code>```

Let me know if you have any questions or problems with your input data and I'll update my answer.

References:

https://github.com/JohnSnowLabs/spark-nlp

https://github.com/JohnSnowLabs/spark-nlp-models

https://github.com/JohnSnowLabs/spark-nlp-workshop

Body:
I have a huge text file and I have to extract only named entites in from this file. I am using Scala language and Databricks cluster for this.

val input = sc.textFile('....Mypath...').flatMap(line => line.split("""\W+"""))

val namedEnt = something(input)

Can anyone tell what to code to get named entities?

Body:
If you convert your input to a DataFrame (ex: .toDF), this is how you can get the Named Entities out:

Just an example of Spark NLP installation

spark-shell --packages JohnSnowLabs:spark-nlp:2.4.0

Actual example:

import com.johnsnowlabs.nlp.pretrained.PretrainedPipeline
import com.johnsnowlabs.nlp.SparkNLP

SparkNLP.version()
// make sure you are using the latest release 2.4.x

// Download and load the pre-trained pipeline that has NER in English
// Full list: https://github.com/JohnSnowLabs/spark-nlp-models
val pipeline = PretrainedPipeline("recognize_entities_dl", lang="en")

//Transfrom your DataFrame to a new DataFrame that has NER column
val annotation = pipeline.transform(inputDF)

// This would look something like this:
/*
+---+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
| id|                text|            document|            sentence|               token|          embeddings|                 ner|       entities|
+---+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|  1|Google has announ...|[[document, 0, 10...|[[document, 0, 10...|[[token, 0, 5, Go...|[[word_embeddings...|[[named_entity, 0...|[[chunk, 0, 5, Go...|
|  2|Donald John Trump...|[[document, 0, 92...|[[document, 0, 92...|[[token, 0, 5, Do...|[[word_embeddings...|[[named_entity, 0...|[[chunk, 0, 16, D...|
+---+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
*/

// This is where the results for entities are:

annotation.select("entities.result").show

Let me know if you have any questions or problems with your input data and I'll update my answer.

References:

https://github.com/JohnSnowLabs/spark-nlp

https://github.com/JohnSnowLabs/spark-nlp-models

https://github.com/JohnSnowLabs/spark-nlp-workshop


问:
How can I have my angular component update when new data is added to sessionStorage?
I'm using a service to communicate between two components. The idea is that when I click 'add to clipboard' on component A, this gets added to sessionStorage. Component B should then retrieve it and update the view.

I've managed to get most of it working so that my items appear in Component B and persist - but only after the page is reset. How can I have Component B refresh each time something is added.

method in component A (sender)

```<code>  addToClipboard() {

    let item: Item = {id : this.itemId, collection : this.collectionName, database : this.dbName, name: itemTitle };

    this.clipboardService.addItemToClipboard(item);
  }
</code>```

Service

```<code>@Injectable({
  providedIn: 'root'
})
export class ClipboardService {

  // items$: Observable<Item []>;
  // private itemSubject = new Subject<Item []>();

  constructor() {
    // this.items$ = this.itemSubject.asObservable();
  }

  addItemToClipboard(item: Item) {
    console.log(item);
    // this.itemSubject.next(item);
    if (sessionStorage.getItem('clipItems') !==  null) {
      console.log(sessionStorage.length);
      const storedItems: Item [] = JSON.parse(sessionStorage.getItem('clipItems'));
      storedItems.push(item);
      sessionStorage.setItem('clipItems', JSON.stringify(storedItems));
    } else {
      const items: Item [] = [];
      items.push(item);
      sessionStorage.setItem('clipItems', JSON.stringify(items));
    }
  }

  getItemsFromClipBoard(): Item [] {
    const storedItems: Item [] = JSON.parse(sessionStorage.getItem('clipItems'));
    return storedItems;
  }

}
</code>```

component B (reciever)

```<code>import { Component, OnInit, OnChanges, ChangeDetectionStrategy } from '@angular/core';
import { Item } from 'src/app/models/item';
import { ClipboardService } from '../clipboard.service';

@Component({
  selector: 'app-clipboard',
  templateUrl: './clipboard.component.html',
  styleUrls: ['./clipboard.component.css'],
})
export class ClipboardComponent implements OnInit {

  items: Item [] = [];

  constructor(private clipboardService: ClipboardService) {
   }

  ngOnInit() {
    this.items = this.clipboardService.getItemsFromClipBoard();
  }

}
</code>```

Ideally, every time the 'items' list refreshes I'd like to update the component (I've had to use session in the service because the items need to persist until the user logs out).

答:
Store in service variable instead of session and make available as BehaviourSubject so can be subscribed to from any component.

This will persist and you could just have a function to clear the service variable on log out if needed. e.g:

Service:

```<code>itemsSubject = new BehaviorSubject<Item[]>(this.getItems());

addItem(item)
  {
    this.items.push(item);
  }

  getItems()
  {
    return this.items;
  }
</code>```

Component:

```<code>export class MyComponent
   items: Item[];

//constructor
 this.clipboardService.itemsSubject.subscribe(res =>
        {
          this.items= res;
        });
</code>```

Some auth service:

```<code>LogOut()
{
   //clear session then:
   this.clipboardService.items = [];

}
</code>```

Body:
I'm using a service to communicate between two components. The idea is that when I click 'add to clipboard' on component A, this gets added to sessionStorage. Component B should then retrieve it and update the view.

I've managed to get most of it working so that my items appear in Component B and persist - but only after the page is reset. How can I have Component B refresh each time something is added.

method in component A (sender)

  addToClipboard() {

    let item: Item = {id : this.itemId, collection : this.collectionName, database : this.dbName, name: itemTitle };

    this.clipboardService.addItemToClipboard(item);
  }

Service

@Injectable({
  providedIn: 'root'
})
export class ClipboardService {

  // items$: Observable<Item []>;
  // private itemSubject = new Subject<Item []>();

  constructor() {
    // this.items$ = this.itemSubject.asObservable();
  }

  addItemToClipboard(item: Item) {
    console.log(item);
    // this.itemSubject.next(item);
    if (sessionStorage.getItem('clipItems') !==  null) {
      console.log(sessionStorage.length);
      const storedItems: Item [] = JSON.parse(sessionStorage.getItem('clipItems'));
      storedItems.push(item);
      sessionStorage.setItem('clipItems', JSON.stringify(storedItems));
    } else {
      const items: Item [] = [];
      items.push(item);
      sessionStorage.setItem('clipItems', JSON.stringify(items));
    }
  }

  getItemsFromClipBoard(): Item [] {
    const storedItems: Item [] = JSON.parse(sessionStorage.getItem('clipItems'));
    return storedItems;
  }

}

component B (reciever)

import { Component, OnInit, OnChanges, ChangeDetectionStrategy } from '@angular/core';
import { Item } from 'src/app/models/item';
import { ClipboardService } from '../clipboard.service';

@Component({
  selector: 'app-clipboard',
  templateUrl: './clipboard.component.html',
  styleUrls: ['./clipboard.component.css'],
})
export class ClipboardComponent implements OnInit {

  items: Item [] = [];

  constructor(private clipboardService: ClipboardService) {
   }

  ngOnInit() {
    this.items = this.clipboardService.getItemsFromClipBoard();
  }

}

Ideally, every time the 'items' list refreshes I'd like to update the component (I've had to use session in the service because the items need to persist until the user logs out).

Body:
Store in service variable instead of session and make available as BehaviourSubject so can be subscribed to from any component.

This will persist and you could just have a function to clear the service variable on log out if needed. e.g:

Service:

itemsSubject = new BehaviorSubject<Item[]>(this.getItems());

addItem(item)
  {
    this.items.push(item);
  }

  getItems()
  {
    return this.items;
  }

Component:

export class MyComponent
   items: Item[];

//constructor
 this.clipboardService.itemsSubject.subscribe(res =>
        {
          this.items= res;
        });

Some auth service:

LogOut()
{
   //clear session then:
   this.clipboardService.items = [];

}


问:
Gradle Zip task to do multiple sub-trees?
We're trying to build up a minorly complicated Zip file in Gradle from multiple filesystem source trees, but no matter how many into specifications we give, it all puts them in the same one.  Is this possible to do in Gradle?

```<code>build/libs/foo.jar --> foo.jar
bar/*              --> bar/*
</code>```

We're getting this instead:

```<code>build/libs/foo.jar --> bar/foo.jar
bar/*              --> bar/*
</code>```

Using this:

```<code>task installZip(type: Zip, dependsOn: jar) {
    from('build/libs/foo.jar').into('.')
    from('bar').into('bar')
}
</code>```

Any help would be appreciated.

EDIT: Gradle 1.0-milestone-3

答:
Try this:

```<code>task zip(type: Zip) {
    from jar.outputs.files
    from('bar/') {
        into('bar')
    }
}
</code>```

First... the jar should be in the root / of the zip (which seems to be what you want). Second, by specifying the from jar.outputs.files, there is an implicit dependsOn on the jar task, so this shows another way of accomplishing what you want. Except with this approach if the jar name changes over time it doesn't matter. Let me know if you need additional help.

ContentLicense: CC BY-SA 3.0

Body:
We're trying to build up a minorly complicated Zip file in Gradle from multiple filesystem source trees, but no matter how many into specifications we give, it all puts them in the same one.  Is this possible to do in Gradle?

build/libs/foo.jar --> foo.jar
bar/*              --> bar/*

We're getting this instead:

build/libs/foo.jar --> bar/foo.jar
bar/*              --> bar/*

Using this:

task installZip(type: Zip, dependsOn: jar) {
    from('build/libs/foo.jar').into('.')
    from('bar').into('bar')
}

Any help would be appreciated.

EDIT: Gradle 1.0-milestone-3

Body:
Try this:

task zip(type: Zip) {
    from jar.outputs.files
    from('bar/') {
        into('bar')
    }
}

First... the jar should be in the root / of the zip (which seems to be what you want). Second, by specifying the from jar.outputs.files, there is an implicit dependsOn on the jar task, so this shows another way of accomplishing what you want. Except with this approach if the jar name changes over time it doesn't matter. Let me know if you need additional help.


问:
Local Video Renderer in Android WebRTC
I am using this library: https://bintray.com/google/webrtc/google-webrtc

What I want to achieve (at least, at the beginning of my project) is render video locally. I am using this tutorial (which is the only one around the Internet) https://vivekc.xyz/getting-started-with-webrtc-for-android-daab1e268ff4. Unfortunately, the last line of code is not up-to-date anymore. The constructor needs a callback which I have no idea how to implement:

localVideoTrack.addRenderer(new VideoRenderer(i420Frame -> {
            // no idea what to put here
        }));

My code is exactly the same as in the posted tutorial. This is the very first step to make familiar with WebRTC technology in Android which I cannot figure out. My camera is capturing the video because I can see it in my log:

I/org.webrtc.Logging: CameraStatistics: Camera fps: 28.

The main issue is that I have no idea how to pass it to my SurfaceViewRenderer through a callback. Did anyone meet that problem? I'll really appreciate any help or suggestions.

Here is the official example app which is the only source but it is done differently than one in the tutorial, it's much more complicated:
https://webrtc.googlesource.com/src/+/master/examples/androidapp/src/org/appspot/apprtc

答:
```<code>private static class ProxyVideoSink implements VideoSink {
    private VideoSink target;

    @Override
    synchronized public void onFrame(VideoFrame frame) {
        if (target == null) {
            Logging.d("TAG", "Dropping frame in proxy because target is null.");
            return;
        }

        target.onFrame(frame);
    }

    synchronized public void setTarget(VideoSink target) {
        this.target = target;
    }
}

ProxyVideoSink localVideoSink = new ProxyVideoSink();
videoTrack.addSink(localVideoSink);
localVideoSink.setTarget(localSurfaceView);
</code>```

try this code as directly assigning videoTrack.addSink(localSurfaceView) might crash on next initialization.

Title: Local Video Renderer in Android WebRTC

Body:
private static class ProxyVideoSink implements VideoSink {
    private VideoSink target;

    @Override
    synchronized public void onFrame(VideoFrame frame) {
        if (target == null) {
            Logging.d("TAG", "Dropping frame in proxy because target is null.");
            return;
        }

        target.onFrame(frame);
    }

    synchronized public void setTarget(VideoSink target) {
        this.target = target;
    }
}

ProxyVideoSink localVideoSink = new ProxyVideoSink();
videoTrack.addSink(localVideoSink);
localVideoSink.setTarget(localSurfaceView);

try this code as directly assigning videoTrack.addSink(localSurfaceView) might crash on next initialization.


问:
How to display different title depends on action?
I have got two methods that redirect to the same .html file.
First method is method responsible for saving, the second method is for updating.
It has got the same view so I just wanted to move user to the same view.
I have
..
 in .html I would like to have title "New Mapping" for adding new mapping and "Update mapping" when we want to update mapping.
These are methods that do all the stuff (redirecting to the .html file)

```<code>@RequestMapping(path = "/.../update", method = RequestMethod.GET)
    public String updatePage(@RequestParam("...") String ..., Model model) {
        String[] tokens = ....split("_");
        Template template= class.method(...);
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save")
    public String newMappingPage(Model model) {
        Template template = new Template();
        template.setCostIndex("10");
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save", method = RequestMethod.POST)
    public String saveMapping(@ModelAttribute Template template) {
        class.method(template);
        return "redirect:/main-page";
    }
</code>```

save.hml file

```<code><html>
<head>
    <title>Engine</title>
    <link rel="stylesheet" th:href="@{/css/file.css}"/>
</head>
<body>
<h1>New/Update mapping</h1>
<form action="save" method="post" th:object="${template}">
    <fieldset>
        <label for="...">....[min]</label>
        <input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
        <label for="...">...</label>
        <input type="number" id="...." th:field="*{...}" required="true"/>
        <label for="...">....</label>
        <input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
        <br/>
        <br/>
        <label for="response">Response</label>
        <br/>
        <textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
        <br/>
        <input id="submit" type="submit" class="primary" value="Submit"/>
    </fieldset>
</form>
</body>
</html>
</code>```

答:
You do not need to create two separate methods for add and update as you are storing data into DB from JSP page. use only one /save API.

```<code>@PostMapping(path = "/.../{}/save")
public String newMappingPage(Model model) {
  Template template = new Template();
  template.setCostIndex("10");
  model = new Model();
  if (model.getId() > 0) {
    model = findById(model.getId());
    model.addAttribute("heading", "Update Mapping");
  } else {
    model.addAttribute("heading", "New Mapping");
  }
  //Call method to store data from jsp file
  return "save";
}
</code>```

In JSP :

```<code><html>
<head>
    <title>Engine</title>
    <link rel="stylesheet" th:href="@{/css/file.css}"/>
</head>
<body>
<h1>${heading}</h1>
<form action="save" method="post" th:object="${template}">
    <fieldset>
        <label for="...">....[min]</label>
        <input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
        <label for="...">...</label>
        <input type="number" id="...." th:field="*{...}" required="true"/>
        <label for="...">....</label>
        <input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
        <br/>
        <br/>
        <label for="response">Response</label>
        <br/>
        <textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
        <br/>
        <input id="submit" type="submit" class="primary" value="Submit"/>
    </fieldset>
</form>
</body>
</html>
</code>```

Body:
I have got two methods that redirect to the same .html file.
First method is method responsible for saving, the second method is for updating.
It has got the same view so I just wanted to move user to the same view.
I have
..
 in .html I would like to have title "New Mapping" for adding new mapping and "Update mapping" when we want to update mapping.
These are methods that do all the stuff (redirecting to the .html file)

@RequestMapping(path = "/.../update", method = RequestMethod.GET)
    public String updatePage(@RequestParam("...") String ..., Model model) {
        String[] tokens = ....split("_");
        Template template= class.method(...);
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save")
    public String newMappingPage(Model model) {
        Template template = new Template();
        template.setCostIndex("10");
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save", method = RequestMethod.POST)
    public String saveMapping(@ModelAttribute Template template) {
        class.method(template);
        return "redirect:/main-page";
    }

save.hml file

    <title>Engine</title>
    <link rel="stylesheet" th:href="@{/css/file.css}"/>

New/Update mapping

<form action="save" method="post" th:object="${template}">
    <fieldset>
        ....[min]
        <input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
        ...
        <input type="number" id="...." th:field="*{...}" required="true"/>
        ....
        <input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>

        Response

        <textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>

        <input id="submit" type="submit" class="primary" value="Submit"/>
    </fieldset>
</form>

Body:
You do not need to create two separate methods for add and update as you are storing data into DB from JSP page. use only one /save API.

@PostMapping(path = "/.../{}/save")
public String newMappingPage(Model model) {
  Template template = new Template();
  template.setCostIndex("10");
  model = new Model();
  if (model.getId() > 0) {
    model = findById(model.getId());
    model.addAttribute("heading", "Update Mapping");
  } else {
    model.addAttribute("heading", "New Mapping");
  }
  //Call method to store data from jsp file
  return "save";
}

In JSP :

<html>
<head>
    <title>Engine</title>
    <link rel="stylesheet" th:href="@{/css/file.css}"/>
</head>
<body>
<h1>${heading}</h1>
<form action="save" method="post" th:object="${template}">
    <fieldset>
        <label for="...">....[min]</label>
        <input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
        <label for="...">...</label>
        <input type="number" id="...." th:field="*{...}" required="true"/>
        <label for="...">....</label>
        <input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
        <br/>
        <br/>
        <label for="response">Response</label>
        <br/>
        <textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
        <br/>
        <input id="submit" type="submit" class="primary" value="Submit"/>
    </fieldset>
</form>
</body>
</html>


问:
How to use animation on angular 8?
I am trying to use a simple rotation animation. I get the style done, but it's happens immediately, without any actual animation.

HTML:

```<code><img class="icon" [@rotation]="liked? 'rotate' : 'straight'" (click)="liked = ! liked" src="mySource"/>
</code>```

TS:

```<code>import { Component, OnInit, Input } from '@angular/core';
import {trigger, state, style, animate, transition,} from '@angular/animations';

@Component({
  selector: 'app-info-window',
  animations: [
    trigger('rotation', [
      state('straight', style({ transform: 'rotate(0)' })),
      state('rotate', style({ transform: 'rotate(180deg)' })),
      transition('rotated => straight', animate('400ms ease-out')),
      transition('straight => rotated', animate('400ms ease-in'))
    ]),
  ],
  templateUrl: './info-window.component.html',
  styleUrls: ['./info-window.component.css']
})
export class InfoWindowComponent implements OnInit {
  liked = false;
</code>```

I imported the BrowserAnimationsModule in the app.module.
What am i doing wrong?

答:
You have a typo in transition definition. It should be

```<code>  transition('rotate => straight', animate('400ms ease-out')),
  transition('straight => rotate', animate('400ms ease-in'))
</code>```

Notice rotate instead of rotated.

Title: How to use animation on angular 8?

Body:
I am trying to use a simple rotation animation. I get the style done, but it's happens immediately, without any actual animation.

HTML:

TS:

import { Component, OnInit, Input } from '@angular/core';
import {trigger, state, style, animate, transition,} from '@angular/animations';

@Component({
  selector: 'app-info-window',
  animations: [
    trigger('rotation', [
      state('straight', style({ transform: 'rotate(0)' })),
      state('rotate', style({ transform: 'rotate(180deg)' })),
      transition('rotated => straight', animate('400ms ease-out')),
      transition('straight => rotated', animate('400ms ease-in'))
    ]),
  ],
  templateUrl: './info-window.component.html',
  styleUrls: ['./info-window.component.css']
})
export class InfoWindowComponent implements OnInit {
  liked = false;

I imported the BrowserAnimationsModule in the app.module.
What am i doing wrong?

Body:
You have a typo in transition definition. It should be

  transition('rotate => straight', animate('400ms ease-out')),
  transition('straight => rotate', animate('400ms ease-in'))

Notice rotate instead of rotated.


问:
Multiple testng.xmls in the same IntelliJ run configuration?
I have a project that has two different modules each with its own set of testng tests.  I have separate run config's with code coverage enabled for each.  I need to run both to gather coverage statistics and was wondering if there was a way to consolidate the coverage data in to a single session.

Is it possible to create a run configuration in IntelliJ that executes the two different testng.xml's?

答:
First, your two testng xml files should be the same name in both module.
Then run Maven as usual: </p>

```<code>mvn test -pl module1,module2 -Dtestng.suite.xml=testng.xml
</code>```

ContentLicense: CC BY-SA 2.5

Body:
First, your two testng xml files should be the same name in both module.
Then run Maven as usual:

mvn test -pl module1,module2 -Dtestng.suite.xml=testng.xml


问:
Update grouped rows with ID of newly inserted grouping row
I want to group several rows of table A and insert a new row into table B for each bunch of grouped rows.
Next to that I want to update the rows of table A with the ID of the newly inserted row.

Inserting the lines into the table with 'grouplines' is like:

```<code>INSERT INTO B(...,...,...)
SELECT col1, col2 FROM A
GROUP BY col1,col2
</code>```

This will produce a list of IDs in table B. I want to update the rows of table A with the ID of the corresponding group-row of table B.

Is there a possibilty to do this?

Some sample data:

After grouping table B looks like:

And then table A should look like:

答:
As it is, your query potentially inserts more than one row.

I think that one solution would to use two queries: first insert in table b from table a, the update table a with newly created id(s) from table b.

```<code>
INSERT INTO B(col1, col2, col3)
SELECT DISTINCT col1, col2, col3 FROM A

UPDATE A
SET A.B_ID = B.B_ID
FROM A
INNER JOIN B
    ON  A.col1 = B.col1
    AND A.col2 = B.col2
    AND A.col3 = B.col3
</code>```

Body:
I want to group several rows of table A and insert a new row into table B for each bunch of grouped rows.
Next to that I want to update the rows of table A with the ID of the newly inserted row.

Inserting the lines into the table with 'grouplines' is like:

INSERT INTO B(...,...,...)
SELECT col1, col2 FROM A
GROUP BY col1,col2

This will produce a list of IDs in table B. I want to update the rows of table A with the ID of the corresponding group-row of table B.

Is there a possibilty to do this?

Some sample data:

After grouping table B looks like:

And then table A should look like:

Body:
As it is, your query potentially inserts more than one row.

I think that one solution would to use two queries: first insert in table b from table a, the update table a with newly created id(s) from table b.

INSERT INTO B(col1, col2, col3)
SELECT DISTINCT col1, col2, col3 FROM A

UPDATE A
SET A.B_ID = B.B_ID
FROM A
INNER JOIN B
    ON  A.col1 = B.col1
    AND A.col2 = B.col2
    AND A.col3 = B.col3


问:
adding dynamic content to _Layout.vbhtml
So moving over to MVC finally from web forms

so within my main _Layout.vbhtml I have a menu as follows:

```<code>                        <a href="#" class="has-arrow"><i class="material-icons">person</i> Account</a>
                        <ul>
                            <li><a href="account-signin.aspx">Sign In / Sign Up</a></li>
                            <li><a href="account-profile.aspx">Profile Page</a></li>
                            <li><a href="account-orders.aspx">Orders List</a></li>
                            <li><a href="account-order-detail.aspx">Order Detail</a></li>
                            <li><a href="account-wishlist.aspx" class="has-badge">Wishlist <span class="badge badge-primary badge-pill">3</span></a></li>
                            <li><a href="account-address.aspx">Address</a></li>
                        </ul>
</code>```

I want this to now come from the DB dynamically

in the web forms world this would have been a master page, I would have then added a literal and then populated it on the page load in the code behind.

But how do I archive the same now in MVC

答:
ended up doing this in _layout.html, works but unsure if its the correct way :-)

@Code
    Dim listGroups As List(Of ProductGroups) = ProductGroups.MenuList()
End Code

then further down the page:

```<code>                    <li>
                        <a href="#" class="has-arrow"><i class="material-icons">shopping_cart</i> Shop</a>
                        <ul>
                            @For Each item In listGroups
                                @<li><a href="@Html.DisplayFor(Function(modelItem) item.GroupURL)" title="@Html.DisplayFor(Function(modelItem) item.Group)">@Html.DisplayFor(Function(modelItem) item.Group)</a></li>
                            Next
                        </ul>
                    </li>
</code>```

as I said does what i expect but not sure if that's how your 'supposed' to do it?

Body:
So moving over to MVC finally from web forms

so within my main _Layout.vbhtml I have a menu as follows:

                        person Account

Sign In / Sign Up

Profile Page

Orders List

Order Detail

Wishlist 3

Address

I want this to now come from the DB dynamically

in the web forms world this would have been a master page, I would have then added a literal and then populated it on the page load in the code behind.

But how do I archive the same now in MVC

Body:
ended up doing this in _layout.html, works but unsure if its the correct way :-)

@Code
    Dim listGroups As List(Of ProductGroups) = ProductGroups.MenuList()
End Code

then further down the page:

                    <li>
                        <a href="#" class="has-arrow"><i class="material-icons">shopping_cart</i> Shop</a>
                        <ul>
                            @For Each item In listGroups
                                @<li><a href="@Html.DisplayFor(Function(modelItem) item.GroupURL)" title="@Html.DisplayFor(Function(modelItem) item.Group)">@Html.DisplayFor(Function(modelItem) item.Group)</a></li>
                            Next
                        </ul>
                    </li>

as I said does what i expect but not sure if that's how your 'supposed' to do it?


问:
Allow one concurrent user per login with JWT
We are developing an application with Laravel/PHP and we want to use an pay-per-user pricing model. For that we have to ensure that an account can only used by only one concurrent user. We use JWT for authentication and it is stateless so I can't use sessions.

To ensure one concurrent login I can enclose the Browser-agent or IP, but both aren't unique and it is possible that they occur multiple times in e.g. an office. Also I can send the MAC address, but that is not the easiest way.

Are there other solutions to ensure one concurrent login per user with JWT?

答:
Anyway you need to store token in db.

For that purpose you will need super fast storage. Redis will be perfect.

On new login just replace token with new one.

Every time user makes request check if token matches the one you have in redis. If not then kick him out.


问:
Ansible how use with_dict by extra_vars?
how can I use with_dict by extra_vars?

I try I know everything but all output with_dict expects a dict :(

This is all files

```<code># vars.yml
rd1:
  Terry:
    user_name:terry_liu
    user_birth:1994/05/11
  Cary:
    user_name:cary_lin
    user_birth:1992/02/19
rd6:
  Jessie:
    user_name:jessie_chen
    user_birth:1996/11/20
  Sherry:
    user_name:sherry_hsu
    user_birth:1989/07/23
</code>```

-

```<code># test.yml
- name: demo
  hosts: test
  vars_files:
    - vars.yml

  tasks:
    - name: show data
      debug:
        msg: "{{ item }}"
      with_dict: "{{ dep }}"
</code>```

-

```<code>#command
ansible-playbook -i inventory test.yml --extra-vars 'dep=rd1'
</code>```

-

Inventory's host is my test vm, just have an ip and it can be ssh.

When run command, it output： fatal: [172.16.1.227]: FAILED! => {"msg": "with_dict expects a dict"}

I think it's need var in var, but I try many different way, all fail.

My demand is send a float dep var and get correspond data from vars.yml.

Thanks all, have a good day!

答:
The problem is that "{{ dep }}" evaluates to the string "rd1"

```<code>with_dict: "{{ dep }}"
</code>```

This is the reason for the error "with_dict expects a dict".

Instead, you need lookup and vars plugin. For example

```<code>with_dict: "{{ lookup('vars', dep) }}"
</code>```

Body:
how can I use with_dict by extra_vars?

I try I know everything but all output with_dict expects a dict :(

This is all files

# vars.yml
rd1:
  Terry:
    user_name:terry_liu
    user_birth:1994/05/11
  Cary:
    user_name:cary_lin
    user_birth:1992/02/19
rd6:
  Jessie:
    user_name:jessie_chen
    user_birth:1996/11/20
  Sherry:
    user_name:sherry_hsu
    user_birth:1989/07/23

-

# test.yml
- name: demo
  hosts: test
  vars_files:
    - vars.yml

  tasks:
    - name: show data
      debug:
        msg: "{{ item }}"
      with_dict: "{{ dep }}"

-

#command
ansible-playbook -i inventory test.yml --extra-vars 'dep=rd1'

-

Inventory's host is my test vm, just have an ip and it can be ssh.

When run command, it output： fatal: [172.16.1.227]: FAILED! => {"msg": "with_dict expects a dict"}

I think it's need var in var, but I try many different way, all fail.

My demand is send a float dep var and get correspond data from vars.yml.

Thanks all, have a good day!

Body:
The problem is that "{{ dep }}" evaluates to the string "rd1"

with_dict: "{{ dep }}"

This is the reason for the error "with_dict expects a dict".

Instead, you need lookup and vars plugin. For example

with_dict: "{{ lookup('vars', dep) }}"


问:
ES6 Import Scenario
There are multiple way to import modules. What is the difference between import {House} and import House?

答:
There are two way to import in ES6 module, based on the export option.

Named Import

```<code>//filename - simple.js

export function Simple() {}

import {Simple} from "./simple.js"
</code>```

Default Import

```<code>//filename - simple.js
export default Class Simple {}

import Simple from "./simple.js"
</code>```

For more, refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

UPDATE
You can also export both from a single file and import them. Important caveat here is there can be only one default export in a module.

```<code>//filename - simple.js

export function Simple1() {}
export default function Simple2() { }

import Simple2, { Simple1 } from "./simple.js"
</code>```

Title: ES6 Import Scenario

Body:
There are two way to import in ES6 module, based on the export option.

Named Import

//filename - simple.js

export function Simple() {}

import {Simple} from "./simple.js"

Default Import

//filename - simple.js
export default Class Simple {}

import Simple from "./simple.js"

For more, refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

UPDATE
You can also export both from a single file and import them. Important caveat here is there can be only one default export in a module.

//filename - simple.js

export function Simple1() {}
export default function Simple2() { }

import Simple2, { Simple1 } from "./simple.js"


问:
In Unity, how to tell if it's the first time a game is being opened?
I want a script to run,

whenever my game in Unity is opened for the first time.

答:
My code:

public class LoadSaveManager : MonoBehaviour
{
    public int IsFirst;

    void Start ()
    {
        IsFirst = PlayerPrefs.GetInt("IsFirst") ;
        if (IsFirst == 0)
        {
            //Do stuff on the first time
            Debug.Log("first run");
            PlayerPrefs.SetInt("IsFirst", 1);
        } else {
            //Do stuff other times
            Debug.Log("welcome again!");
        }
    }
}```


答:
Nevermind, I've figured out that it would be way easier to filter the output sent to ansible directly from bash. In the end I came up with this:

```<code> awk '!seen[$0]++' /var/lib/dhcp/dhcpd.leases | grep -vE -- 'ends|starts|tstp|cltt|uid|bind|hardware' | grep -B1 storage | awk '{print $2}' | grep '^[0-9]'
</code>```

Which results in 2 ip addresses for the storage nodes (out of 8).

```<code>10.241.55.148
10.241.55.235
</code>```

This doesn't solve the initial question but at least provides the desired answer.

Title: Ansible map filter from a registered var output

Body:
I'm getting with ansible through a registered variable a full copy of the dhcpd.leases file from one server. The output with ansible debug looks like this:

TASK [Show passive storage nodes info] *************************************************************************************************************************************************************
ok: [10.241.55.2] => {
    "msg": [
        "# The format of this file is documented in the dhcpd.leases(5) manual page.",
        "# This lease file was written by isc-dhcp-4.2.2",
        "",
        "lease 10.241.55.165 {",
        "  starts 4 2019/12/12 09:30:37;",
        "  ends 4 2019/12/12 21:30:37;",
        "  tstp 4 2019/12/12 21:30:37;",
        "  cltt 4 2019/12/12 09:30:37;",
        "  binding state free;",
        "  hardware ethernet b4:d1:35:00:04:50;",
        "  uid \"\\001\\264\\3215\\000\\004P\";",
        "}",
        "lease 10.241.55.163 {",
        "  starts 1 2019/12/16 08:10:56;",
        "  ends 1 2019/12/16 20:10:56;",
        "  tstp 1 2019/12/16 20:10:56;",
        "  cltt 1 2019/12/16 08:10:56;",
        "  binding state free;",
        "  hardware ethernet b4:d1:35:00:03:d7;",
        "}",
        "lease 10.241.55.159 {",
        "  starts 1 2019/12/16 08:52:20;",
        "  ends 1 2019/12/16 20:52:20;",
        "  tstp 1 2019/12/16 20:52:20;",
        "  cltt 1 2019/12/16 08:52:20;",
        "  binding state free;",
        "  hardware ethernet b4:d1:35:00:03:b4;",
        "}",
        "lease 10.241.55.166 {",
        "  starts 1 2019/12/16 08:54:38;",
        "  ends 1 2019/12/16 20:54:38;",
        "  tstp 1 2019/12/16 20:54:38;",
        "  cltt 1 2019/12/16 08:54:38;",
        "  binding state free;",
        "  hardware ethernet b4:d1:35:00:04:63;",
        "}",
        "lease 10.241.55.164 {",
        "  starts 1 2019/12/16 10:48:10;",
        "  ends 1 2019/12/16 22:48:10;",
        "  tstp 1 2019/12/16 22:48:10;",
        "  cltt 1 2019/12/16 10:48:10;",
        "  binding state free;",
        "  hardware ethernet b4:d1:35:00:04:4e;",
        "}",
        "lease 10.241.55.143 {",
        "  starts 5 2020/02/14 04:38:09;",
        "  ends 5 2020/02/14 16:38:09;",
        "  cltt 5 2020/02/14 04:38:09;",
        "  binding state active;",
        "  next binding state free;",
        "  rewind binding state free;",
        "  hardware ethernet 08:94:ef:9c:80:4a;",
        "  client-hostname \"linux-compute-e7d573cb9fda4e689939e21a7843c4fb\";",
        "}",
        "lease 10.241.55.148 {",
        "  starts 5 2020/02/14 05:03:08;",
        "  ends 5 2020/02/14 17:03:08;",
        "  cltt 5 2020/02/14 05:03:08;",
        "  binding state active;",
        "  next binding state free;",
        "  rewind binding state free;",
        "  hardware ethernet 00:e0:ec:ca:44:84;",
        "  client-hostname \"linux-storage-4391fc6548764de5a15a46b432d3cd37\";",
        "}",
        "lease 10.241.55.235 {",
        "  starts 5 2020/02/14 05:20:28;",
        "  ends 5 2020/02/14 17:20:28;",
        "  cltt 5 2020/02/14 05:20:28;",
        "  binding state active;",
        "  next binding state free;",
        "  rewind binding state free;",
        "  hardware ethernet 00:e0:ec:ca:45:74;",
        "  client-hostname \"linux-storage-58aba44ac09d4f639b9374b9142b1a53\";",
        "}",
        "lease 10.241.55.141 {",
        "  starts 5 2020/02/14 06:01:04;",
        "  ends 5 2020/02/14 18:01:04;",
        "  cltt 5 2020/02/14 06:01:04;",
        "  binding state active;",
        "  next binding state free;",
        "  rewind binding state free;",
        "  hardware ethernet 08:94:ef:9c:80:6c;",
        "  client-hostname \"linux-compute-d228bc79357c4c8b87c280f9efae6ba6\";",
        "}",
        "lease 10.241.55.236 {",
        "  starts 5 2020/02/14 06:12:28;",
        "  ends 5 2020/02/14 18:12:28;",
        "  cltt 5 2020/02/14 06:12:28;",
        "  binding state active;",
        "  next binding state free;",
        "  rewind binding state free;",
        "  hardware ethernet 00:e0:ec:ca:45:75;",
        "  client-hostname \"linux-storage-58aba44ac09d4f639b9374b9142b1a53\";",
        "}",
        "lease 10.241.55.140 {",
        "  starts 5 2020/02/14 06:13:18;",
        "  ends 5 2020/02/14 18:13:18;",
        "  cltt 5 2020/02/14 06:13:18;",
        "  binding state active;",
        "  next binding state free;",
        "  rewind binding state free;",
        "  hardware ethernet 08:94:ef:9c:80:24;",
        "  client-hostname \"linux-compute-d0a9a76a7b5249048f78642220a1958c\";",
        "}",

Is there anyway to map the filed lease ip + client-hostname then based on that to do filtering and put strictly the ips in an inventory file? I know I can get the ips directly but there are servers which have 4 ips so they have the same hostname. Rather than put all 4 ips in the inventory I only need one of their ips (doesn't matter which one) and I'm trying to make the filtering based on the hostname. Also there are entries in the output that have no client-hostname so ideally those should be ignored.

The question is similar with another one I've posted here:
Ansible jina2 template, filter output based on uniqueness

But with this, I'm trying a different approach.

What I've tried so far is this:

 debug:
   msg: "{{ p_storage_ips.stdout | map(attribute='client-hostname' | list) }}"

But I get nothing:
TASK [Show passive storage nodes info]

ok: [10.241.55.2] => {
    "msg": "<generator object do_map at 0x7f40e52785f0>"
}

Also tried like this:

   - set_fact:
       dhcp_hosts: "{{ dhcp.stdout_lines | selectattr('client-hostname', 'defined') | map(attribute='lease') | list }}"

Any help would be really appreciated!

Body:
Nevermind, I've figured out that it would be way easier to filter the output sent to ansible directly from bash. In the end I came up with this:

 awk '!seen[$0]++' /var/lib/dhcp/dhcpd.leases | grep -vE -- 'ends|starts|tstp|cltt|uid|bind|hardware' | grep -B1 storage | awk '{print $2}' | grep '^[0-9]'

Which results in 2 ip addresses for the storage nodes (out of 8).

10.241.55.148
10.241.55.235

This doesn't solve the initial question but at least provides the desired answer.


问:
Creating a live checkers-like web app with PHP, JS, CSS and HTML?
I want to create a live, checkers-like app, which will work like this: There will be multiple icons/avatars displayed on this checkerboard like surface. I want to have a command prompt beneath this board, or some other sort of interface, that will allow them to control a certain avatar, and get it to preform actions. Multiple users will be using it at one time, and I will all be able to view the other user's changes/actions to the checkerboard.

What I'm wondering is: what's the best way to do this? I've got my HTML, CSS, and JS approach down, but not my data storage method. I know that, using PHP, I've got the choices to use either: file-based storage, MYSQL, or some other method. I need to know which is better, because I don't want to have server-lag, poor-response time, or some other issue, especially in this case since actions will be preformed every other second 2 or so, by these multiple users.

I've done similar stuff before, but I'm wanting to hear how others would handle it (advice, etc.) from more experienced programmers.

答:
MySQL and XCache !!!!

Make sure you use predefined statements so MySQL does not need to compile the SQL again. Also memtables could be used to use memory storage

Of course make use of indexes appropriately.

If the 'gamestate' is not that important you can even store everything in XCache.
 Remember that XCache does not store data persistently (after Apache restart)


问:
"Cannot start compilation: the output path is not specified for module..."
I have a very simple Java + Gradle project. It builds fine. It runs fine from the shell with "gradle run". However, if I try to run inside of IntelliJ, I get:

```<code>Cannot start compilation: the output path is not specified for module "xyz" Specify the output path in Configure Project.
</code>```

My "Compiler output" is set to "Inherit project compile output path". I don't want a custom output path, whatever that is, just do a normal gradle build and run.

答: Bugs caused by missing predefined folder for store compiled class file which is normally is /out folder by default. You can give a try to close Intellij > Import Project > From existing source. This will solve this problem.</p>

Body:
I have a very simple Java + Gradle project. It builds fine. It runs fine from the shell with "gradle run". However, if I try to run inside of IntelliJ, I get:

Cannot start compilation: the output path is not specified for module "xyz" Specify the output path in Configure Project.

My "Compiler output" is set to "Inherit project compile output path". I don't want a custom output path, whatever that is, just do a normal gradle build and run.


问:
How to set ylim of pyplot manually rather than allowing it to scale automatially?
I want to have my y-axis like this

But, if I do plt.ylim(0.001, 1000), it scales it like this

How can I get it fixed?

答: Try semilogy(x, y), and then set your y-limit as you have shown.


问:
Object not callable error | Where function
I am trying to run below query:

```<code>df3 = df1.join(df2, df1["DID"] == df2["JID"],'inner')\
          .select(df1["DID"],df1["amt"]-df2["amt"]\
          .where(df1["DID"]== "BIG123")).show()
</code>```

I get error as shown below:

TypeError: 'Column' object is not callable TypeError

  Traceback (most recent call last)

What is the issue with the query and how do I fix it?

答:
Try this code :

```<code> from pyspark.sql import functions as F

 df3 = df1.join(df2, df1["DID"] == df2["JID"] ,how = 'inner')\
      .select("DID",df1["amt"]-df2["amt"])\
      .where(F.col("DID")== "BIG123" ).show()
</code>```

Best,

Abakar

Body:
I am trying to run below query:

df3 = df1.join(df2, df1["DID"] == df2["JID"],'inner')\
          .select(df1["DID"],df1["amt"]-df2["amt"]\
          .where(df1["DID"]== "BIG123")).show()

I get error as shown below:

TypeError: 'Column' object is not callable TypeError

  Traceback (most recent call last)

What is the issue with the query and how do I fix it?

Body:
Try this code :

 from pyspark.sql import functions as F

 df3 = df1.join(df2, df1["DID"] == df2["JID"] ,how = 'inner')\
      .select("DID",df1["amt"]-df2["amt"])\
      .where(F.col("DID")== "BIG123" ).show()

Best,

Abakar


问:
Simple Ad-Server
I'm in the middle of a project where we have created the backend for handling ad campaigns in Grails and I am trying to figure out the best way to create the ad-server part. I.e. the part that is going to serve the actual ads to the end users (browsers).

In my last three projects I have been using Grails, which I have come to enjoy very much for it's rapid development and good support from the Java community through Spring and Hibernate. However, Grails still has some performance issues, and I'm not sure it is the right choice for this task. I have been looking at other alternatives, but can't decide which way to go. The server needs to be able to handle around a couple of thousand requests per second, plus needs to be robust. The DB structure is as follows (simplified):

```<code>Ad ==> site, position, percent of view (percent of time the ad is shown)
</code>```

So basically, the Ad Server needs to get the necessary rows from the DB for the specific site and position and choose which Ad to display (depending on percentage).

Bellow are the different choices I am considering (all of which should have multiple instances and use a load balancer).

Grails together with Redis and
MongoDB - I haven't found any reports
on performance with this trio. In my
previous projects we have found that
Grails has lots of performance
issues, a lot of them we have handled
in different ways, but for an Ad
Server, I'm not sure it will do.

Node.js together with a key-value
store - Node.js is supposedly very
fast, but it would be a bit risky to
implement it at this stage since it
is not yet stabilized.

Ruby on Rails    together with a
key-value store -    Haven't done any
Ruby on Rails    development yet, but
from what I can    gather from
googling around, Ruby on    Rails has
a lot better performance    than
Grails.

PHP with a key-value store - Haven't
done any PHP programming either, but
there are a lot of big sites using
PHP that have good performance, so it
should be considered a good
alternative.

Any suggestion or recommendations are warmly welcomed.

答:
I found these comparing Java to node.js, concerning performance:

http://www.olympum.com/java/quick-benchmark-java-nodejs/

http://www.olympum.com/java/java-aio-vs-nodejs/

They suggest Java is twice as fast, but do your own trials.

How many combinations of site, position, percent, etc. will you have? How many new dimensions will you add in the future?  Probably worth loading all of them at startup to avoid constantly hitting the database.  You could use the combination of them to build a key fast, which you lookup the address of the ad in memory.  This should be fast enough in Grails.

For thousands of requests a second, you are probably looking at a clustered farm, with a load balancer up front.  Depends on the complexity of the logic that builds the content of the page.

Once you have determined the URL which the browser should use to load the ad, I like the idea of a CDN, but that could get expensive!

If it were me, I would stick to the one technology (Grails) and iron out the problems as I face them.

Title: Simple Ad-Server

Body:
I'm in the middle of a project where we have created the backend for handling ad campaigns in Grails and I am trying to figure out the best way to create the ad-server part. I.e. the part that is going to serve the actual ads to the end users (browsers).

In my last three projects I have been using Grails, which I have come to enjoy very much for it's rapid development and good support from the Java community through Spring and Hibernate. However, Grails still has some performance issues, and I'm not sure it is the right choice for this task. I have been looking at other alternatives, but can't decide which way to go. The server needs to be able to handle around a couple of thousand requests per second, plus needs to be robust. The DB structure is as follows (simplified):

Ad ==> site, position, percent of view (percent of time the ad is shown)

So basically, the Ad Server needs to get the necessary rows from the DB for the specific site and position and choose which Ad to display (depending on percentage).

Bellow are the different choices I am considering (all of which should have multiple instances and use a load balancer).

Grails together with Redis and
MongoDB - I haven't found any reports
on performance with this trio. In my
previous projects we have found that
Grails has lots of performance
issues, a lot of them we have handled
in different ways, but for an Ad
Server, I'm not sure it will do.

Node.js together with a key-value
store - Node.js is supposedly very
fast, but it would be a bit risky to
implement it at this stage since it
is not yet stabilized.

Ruby on Rails    together with a
key-value store -    Haven't done any
Ruby on Rails    development yet, but
from what I can    gather from
googling around, Ruby on    Rails has
a lot better performance    than
Grails.

PHP with a key-value store - Haven't
done any PHP programming either, but
there are a lot of big sites using
PHP that have good performance, so it
should be considered a good
alternative.

Any suggestion or recommendations are warmly welcomed.


问:
How do I make Bootstrap popover work with HTML content in a seperate element
I am in the process of combining Bootstrap panels with Bootstrap popover functionality. The goal is to show a popover when the user hovers the panel's header. I've already got this to work, except that the data-content="" part becomes quite unmanageable when it has a lot of HTML inside.

Below is some sample HTML I am working with. The part that says "LOADS OF HTML" contains div's, table's, p's, etc.

```<code><div class="panel panel-default">
    <div class="panel-heading">
        <i class="fa fa-briefcase fa-fw"></i>
        <abbr title="Panel title" data-container="body" data-toggle="popover"
              data-placement="bottom" data-trigger="hover" data-html="true"
              data-content="<div>LOADS OF HTML HERE</div>">
          Panel title
        </abbr>
        <div class="col-xs-6 col-md-4 pull-right" style="margin-top: -4px;">
            <!-- some buttons go here -->
        </div>
    </div>
    <!-- /.panel-heading -->
    </div>
    <!-- some panel content goes here -->
</div>
</code>```

Other Bootstrap plugins solve this issue by allowing you to put the HTML in a separate element and then  reference that element with a "data-target" attribute. Unfortunately, Popover does not support this. How do I mimic this behavior without writing element specific JavaScript?

答:
About Alexus1024 solution : I had to add a "#" before data.target in order to have jquery correctly selecting the target :</p>

```<code>var contentElementId = "#"+data.target;
</code>```

Body:
I am in the process of combining Bootstrap panels with Bootstrap popover functionality. The goal is to show a popover when the user hovers the panel's header. I've already got this to work, except that the data-content="" part becomes quite unmanageable when it has a lot of HTML inside.

Below is some sample HTML I am working with. The part that says "LOADS OF HTML" contains div's, table's, p's, etc.

          Panel title

Other Bootstrap plugins solve this issue by allowing you to put the HTML in a separate element and then  reference that element with a "data-target" attribute. Unfortunately, Popover does not support this. How do I mimic this behavior without writing element specific JavaScript?

Body:
About Alexus1024 solution : I had to add a "#" before data.target in order to have jquery correctly selecting the target :

var contentElementId = "#"+data.target;


问:
Not able to get the text property of custom stepper used in the xaml file to its cs file in xamarin forms
Here group binding is done and the products are listed under the corresponding dealers. I want to multiply the price and quantity of each products under one dealer and store it in a List_model-OrderModel when the View Order button is clicked. I am not able to access the quantity value in the custom stepper text in my cs file.
I tried var qty = stepper.Text. but the name stepper is not coming. CustomStepper and Stepper is coming the dropdown.

This is my custom stepper:

```<code>/*Created this class to make a custon stepper to add quantity */
public class CustomStepper : StackLayout
{
    Button PlusBtn;
    Button MinusBtn;
    Label QtyLbl;

    public static readonly BindableProperty TextProperty =
      BindableProperty.Create(
         propertyName: "Text",
          returnType: typeof(int),
          declaringType: typeof(CustomStepper),
          defaultValue: 0,
          defaultBindingMode: BindingMode.TwoWay);

    public int Text
    {
        get { return (int)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public CustomStepper()
    {
        PlusBtn = new Button { Text = "+", WidthRequest = 23, HeightRequest = 25, FontSize = 11, BackgroundColor = Color.LightGray, Padding = 0};
        MinusBtn = new Button { Text = "-", WidthRequest = 23, HeightRequest = 25, FontSize = 11, BackgroundColor = Color.LightGray, Padding = 0};

        Orientation = StackOrientation.Horizontal;
        PlusBtn.Clicked += PlusBtn_Clicked;
        MinusBtn.Clicked += MinusBtn_Clicked;

        QtyLbl = new Label { FontSize = 11, VerticalTextAlignment = TextAlignment.Center, HorizontalTextAlignment = TextAlignment.Center, WidthRequest = 20   };
        QtyLbl.SetBinding(Entry.TextProperty, new Binding(nameof(Text), BindingMode.TwoWay, source:this));

        Children.Add(MinusBtn);
        Children.Add(QtyLbl);
        Children.Add(PlusBtn);
    }

    private void MinusBtn_Clicked(object sender, EventArgs e)
    {
        if (Text > 0)
            Text--;
    }

    private void PlusBtn_Clicked(object sender, EventArgs e)
    {
        if (Text < 10)
            Text++;
    }
}
</code>```

This is my Model class code:

```<code>public partial class AllProductListview
{
    public decimal PK { get; set; }
    public decimal VendorFK { get; set; }
    public string Vendorname { get; set; }
    public string distance { get; set; }
    public string NameE { get; set; }
    public string NameC { get; set; }
    public float SalesPrice { get; set; }
    public int Quantity { get; set; }
    public decimal DChargeMode { get; set; }
    public string VatForm { get; set; }
    public float TotalAmount { get; set; }
    public string DeliveryCharge { get; set; }

  }

public class OrderModel
{
    public int PK { get; set; }
    public int VendorFK { get; set; }

    public string NameE { get; set; }
    public string NameC { get; set; }
    public float SalesPrice { get; set; }
    public int DChargeMode { get; set; }
    public string VatForm { get; set; }
    public string DeliveryCharge { get; set; }
    public int Quantity { get; set; }
    public float TotalAmount { get; set; }
    public string Delete { get; set; }
}
</code>```

I have this in my button click in the corresponding cs file:

```<code>private async void viewOrderBtn_Clicked(object sender, EventArgs e)
    {
        var item = (Button)sender;

        /*item.BindingContext contains all the values [whn i did step by step debugging] as in AllProductListview..now I have to put it in a loop and calculate the total by multiplying the price and quantity and store it in OrderModel by adding the record into the Orderlist*/
        var productList = item.BindingContext as AllProductListview;
        List<OrderModel> Orderlist = new List<OrderModel>();
    }
</code>```

My xaml file :

```<code><Grid Grid.Row="3">
            <Frame HasShadow="True"
                   BackgroundColor="White"
                   Margin="1"
                   Padding="5"> <!--@ambi : changed margin from 2 to 1 padding-10-->
                <ListView
                        x:Name="Prodlistview"
                        IsGroupingEnabled="True"
                        ItemsSource="{Binding GroupedData}"
                        GroupDisplayBinding="{Binding Key}"
                        ItemSelected="Prodlistview_ItemSelected"
                        SeparatorVisibility="Default">

                    <ListView.GroupHeaderTemplate>
                        <DataTemplate>
                            <ViewCell Height="5"><!--@ambi : height-15-->
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Padding="0,0"
                                             Orientation="Horizontal"

                                            BackgroundColor="#e3e2de">
                                    <!--padding - 10  FontAttributes="Bold"-->
                                    <Label Text="{Binding Key}"
                                           TextColor="Black"
                                           VerticalOptions="CenterAndExpand"
                                           HorizontalOptions="CenterAndExpand"
                                           FontSize="12"
                                           Style="{StaticResource listlabel}"/>

                                    <Button x:Name="viewOrderBtn"
                                            Text= "{lang:Translate DriverViewOrder}"
                                            HorizontalOptions="EndAndExpand"
                                            FontAttributes="None"
                                            CommandParameter="{Binding Key}"
                                            Clicked="viewOrderBtn_Clicked"
                                            Margin="2,5"
                                            Padding="1"
                                            FontSize="12"/> <!--@ambi : added button in the group view-->
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>

                    </ListView.GroupHeaderTemplate>

                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <local:ListViewSelectionColorRender SelectedBackgroundColor="Transparent">
                                <ViewCell.View>
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="*"/>    <!--qty..width 0.55-->
                                        </Grid.ColumnDefinitions>
                                        <Label Grid.Column="0" Text="{Binding NameE}"
                                               Style="{StaticResource listlabel}" MaxLines="1"
                                               HorizontalTextAlignment="Start"
                                               LineBreakMode="TailTruncation"/>
                                        <!--@ambi : HorizontalTextAlignment="Start"-->
                                        <Label Grid.Column="1" Text="{Binding distance}" Style="{StaticResource listlabel}"
                                               TextColor="DarkGoldenrod"/>

                                        <Label Grid.Column="2" Text="{Binding SalesPrice}"
                                               Padding="0,0,15,0"
                                               HorizontalTextAlignment="End"
                                               Style="{StaticResource listlabel}"/>

                                        <StackLayout Grid.Column="3" VerticalOptions="Center" x:Name="Container">
                                            <!--<Frame BorderColor="Gray" HeightRequest="30" WidthRequest="40"
                                                   CornerRadius="7" Padding="5,0" Margin="0,0" HasShadow="False">
                                                <local:BorderlessPicker x:Name="picker"
                                                                        Title="{lang:Translate Select}"
                                                                        Style="{StaticResource picker}"
                                                                        SelectedIndex="{Binding Pickerindex}"
                                                                        ItemsSource="{Binding QtyListModel}"
                                                                        SelectedIndexChanged="QtyPicker_SelectedIndexChanged"
                                                                        ItemDisplayBinding="{Binding Quantity}"
                                                                        TextColor="Black"/>
                                            </Frame>-->
                                            <!--@ambi : Custom stepper added to check a different method-->
                                                <local:CustomStepper x:Name="stepper"
                                                                     Text="{Binding Quantity, Mode=TwoWay}"
                                                                     Padding="3,0" />
                                        </StackLayout>
                                    </Grid>
                                </ViewCell.View>
                            </local:ListViewSelectionColorRender>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Frame>
        </Grid>
</code>```

Image :
My screen

Update :
I have attached the pic of my debug window. Please walk me from here. I could bring the data from the xaml. I'm new to xamarin forms. No idea how to go from here.

```<code>private async void viewOrderBtn_Clicked(object sender, EventArgs e)
    {
        /*item.BindingContext contains all the values [whn i did step by step *debugging] as in AllProductListview..now I have to put it in a loop and *calculate the total by multiplying the price and quantity and store it in *OrderModel by adding the record into the Orderlist*/
        var item = (Button)sender;
        var itemobj = item?.BindingContext as AllProductListview;
        List<OrderModel> Orderlist = new List<OrderModel>();
        int ID = Convert.ToInt32(itemobj.PK); //showing no value assigned
        int vendorfk = Convert.ToInt32(itemobj.VendorFK); //showing no value assigned
        float price = itemobj.SalesPrice; //showing no value assigned
        int quantity = itemobj.Quantity; //showing no value assigned
        float total = price * quantity;
    }
</code>```

Debug window

答:
Try This Code</p>

```<code> private async void viewOrderBtn_Clicked(object sender, EventArgs e)
 {
            var item = (Button)sender;  //no idea if this is correct
            var qty = item.BindingContext as ViewModelName or ModelName;

 }
</code>```

Body:
Here group binding is done and the products are listed under the corresponding dealers. I want to multiply the price and quantity of each products under one dealer and store it in a List_model-OrderModel when the View Order button is clicked. I am not able to access the quantity value in the custom stepper text in my cs file.
I tried var qty = stepper.Text. but the name stepper is not coming. CustomStepper and Stepper is coming the dropdown.

This is my custom stepper:

/*Created this class to make a custon stepper to add quantity */
public class CustomStepper : StackLayout
{
    Button PlusBtn;
    Button MinusBtn;
    Label QtyLbl;

    public static readonly BindableProperty TextProperty =
      BindableProperty.Create(
         propertyName: "Text",
          returnType: typeof(int),
          declaringType: typeof(CustomStepper),
          defaultValue: 0,
          defaultBindingMode: BindingMode.TwoWay);

    public int Text
    {
        get { return (int)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public CustomStepper()
    {
        PlusBtn = new Button { Text = "+", WidthRequest = 23, HeightRequest = 25, FontSize = 11, BackgroundColor = Color.LightGray, Padding = 0};
        MinusBtn = new Button { Text = "-", WidthRequest = 23, HeightRequest = 25, FontSize = 11, BackgroundColor = Color.LightGray, Padding = 0};

        Orientation = StackOrientation.Horizontal;
        PlusBtn.Clicked += PlusBtn_Clicked;
        MinusBtn.Clicked += MinusBtn_Clicked;

        QtyLbl = new Label { FontSize = 11, VerticalTextAlignment = TextAlignment.Center, HorizontalTextAlignment = TextAlignment.Center, WidthRequest = 20   };
        QtyLbl.SetBinding(Entry.TextProperty, new Binding(nameof(Text), BindingMode.TwoWay, source:this));

        Children.Add(MinusBtn);
        Children.Add(QtyLbl);
        Children.Add(PlusBtn);
    }

    private void MinusBtn_Clicked(object sender, EventArgs e)
    {
        if (Text > 0)
            Text--;
    }

    private void PlusBtn_Clicked(object sender, EventArgs e)
    {
        if (Text < 10)
            Text++;
    }
}

This is my Model class code:

public partial class AllProductListview
{
    public decimal PK { get; set; }
    public decimal VendorFK { get; set; }
    public string Vendorname { get; set; }
    public string distance { get; set; }
    public string NameE { get; set; }
    public string NameC { get; set; }
    public float SalesPrice { get; set; }
    public int Quantity { get; set; }
    public decimal DChargeMode { get; set; }
    public string VatForm { get; set; }
    public float TotalAmount { get; set; }
    public string DeliveryCharge { get; set; }

  }

public class OrderModel
{
    public int PK { get; set; }
    public int VendorFK { get; set; }

    public string NameE { get; set; }
    public string NameC { get; set; }
    public float SalesPrice { get; set; }
    public int DChargeMode { get; set; }
    public string VatForm { get; set; }
    public string DeliveryCharge { get; set; }
    public int Quantity { get; set; }
    public float TotalAmount { get; set; }
    public string Delete { get; set; }
}

I have this in my button click in the corresponding cs file:

private async void viewOrderBtn_Clicked(object sender, EventArgs e)
    {
        var item = (Button)sender;

        /*item.BindingContext contains all the values [whn i did step by step debugging] as in AllProductListview..now I have to put it in a loop and calculate the total by multiplying the price and quantity and store it in OrderModel by adding the record into the Orderlist*/
        var productList = item.BindingContext as AllProductListview;
        List<OrderModel> Orderlist = new List<OrderModel>();
    }

My xaml file :

<Grid Grid.Row="3">
            <Frame HasShadow="True"
                   BackgroundColor="White"
                   Margin="1"
                   Padding="5">
                <ListView
                        x:Name="Prodlistview"
                        IsGroupingEnabled="True"
                        ItemsSource="{Binding GroupedData}"
                        GroupDisplayBinding="{Binding Key}"
                        ItemSelected="Prodlistview_ItemSelected"
                        SeparatorVisibility="Default">

                    <ListView.GroupHeaderTemplate>
                        <DataTemplate>
                            <ViewCell Height="5">
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Padding="0,0"
                                             Orientation="Horizontal"

                                            BackgroundColor="#e3e2de">

                                    <Button x:Name="viewOrderBtn"
                                            Text= "{lang:Translate DriverViewOrder}"
                                            HorizontalOptions="EndAndExpand"
                                            FontAttributes="None"
                                            CommandParameter="{Binding Key}"
                                            Clicked="viewOrderBtn_Clicked"
                                            Margin="2,5"
                                            Padding="1"
                                            FontSize="12"/>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>

                    </ListView.GroupHeaderTemplate>

                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <local:ListViewSelectionColorRender SelectedBackgroundColor="Transparent">
                                <ViewCell.View>
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="*"/>
                                        </Grid.ColumnDefinitions>

                                        <StackLayout Grid.Column="3" VerticalOptions="Center" x:Name="Container">

                                                <local:CustomStepper x:Name="stepper"
                                                                     Text="{Binding Quantity, Mode=TwoWay}"
                                                                     Padding="3,0" />
                                        </StackLayout>
                                    </Grid>
                                </ViewCell.View>
                            </local:ListViewSelectionColorRender>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Frame>
        </Grid>

Image :
My screen

Update :
I have attached the pic of my debug window. Please walk me from here. I could bring the data from the xaml. I'm new to xamarin forms. No idea how to go from here.

private async void viewOrderBtn_Clicked(object sender, EventArgs e)
    {
        /*item.BindingContext contains all the values [whn i did step by step *debugging] as in AllProductListview..now I have to put it in a loop and *calculate the total by multiplying the price and quantity and store it in *OrderModel by adding the record into the Orderlist*/
        var item = (Button)sender;
        var itemobj = item?.BindingContext as AllProductListview;
        List<OrderModel> Orderlist = new List<OrderModel>();
        int ID = Convert.ToInt32(itemobj.PK); //showing no value assigned
        int vendorfk = Convert.ToInt32(itemobj.VendorFK); //showing no value assigned
        float price = itemobj.SalesPrice; //showing no value assigned
        int quantity = itemobj.Quantity; //showing no value assigned
        float total = price * quantity;
    }

Debug window

Body:
Try This Code

 private async void viewOrderBtn_Clicked(object sender, EventArgs e)
 {
            var item = (Button)sender;  //no idea if this is correct
            var qty = item.BindingContext as ViewModelName or ModelName;

 }


问:
SQL Find MAX Values for multiple rows
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400
```

<p>SQL Statement as to return the Max Number per Name. </p>

<p>desired outcome </p>

<pre class="lang-none prettyprint-override"><code>Alabama  354    300
Atlas    800    400
</code>```

答:
You can first Order by Number and then GROUP BY name like this:</p>

```<code>SELECT DISTINCT
name, MAX(number) AS number, MAX(value) AS value
FROM table
GROUP BY name
</code>```

Title: SQL Find MAX Values for multiple rows

Body:
Data Set

Name    Number  Value
Alabama  254    100
Atlas    156    200
Alabama  354    300
Atlas    800    400

SQL Statement as to return the Max Number per Name.

desired outcome

Alabama  354    300
Atlas    800    400

Body:
You can first Order by Number and then GROUP BY name like this:

SELECT DISTINCT
name, MAX(number) AS number, MAX(value) AS value
FROM table
GROUP BY name


问:
How can I remove the Seaborn FacetGrid's legend title?
I am using Seaborn's FacetGrid to combine many plots in one figure and I want to remove the legend title. For instance, in the example below, I want to remove the title "sex".

```<code>import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')

g = sns.FacetGrid(tips, col= 'day')
g.map(sns.lineplot, 'total_bill', 'tip', 'sex', ci = False)
g.add_legend()
</code>```

I am aware of the discussion how to change the title in, e.g., How can I change the Seaborn FacetGrid's legend title? However, I have not seen how to remove the legend title

答:
I tried using the hack provided in this answer by ImportanceOfBeingErnest and it works for your purpose

```<code>tips = sns.load_dataset('tips')
tips.columns = [n if n != "sex" else "" for n in tips.columns]

g = sns.FacetGrid(tips, col= 'day')
g.map(sns.lineplot, 'total_bill', 'tip', '', ci = False)
leg = g.add_legend()
</code>```

Body:
I am using Seaborn's FacetGrid to combine many plots in one figure and I want to remove the legend title. For instance, in the example below, I want to remove the title "sex".

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')

g = sns.FacetGrid(tips, col= 'day')
g.map(sns.lineplot, 'total_bill', 'tip', 'sex', ci = False)
g.add_legend()

I am aware of the discussion how to change the title in, e.g., How can I change the Seaborn FacetGrid's legend title? However, I have not seen how to remove the legend title

Body:
I tried using the hack provided in this answer by ImportanceOfBeingErnest and it works for your purpose

tips = sns.load_dataset('tips')
tips.columns = [n if n != "sex" else "" for n in tips.columns]

g = sns.FacetGrid(tips, col= 'day')
g.map(sns.lineplot, 'total_bill', 'tip', '', ci = False)
leg = g.add_legend()