问:
Pyspark convert df to array of objects
```<code>from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.getOrCreate()

simpleData = [("James", "Sales", "NY", 90000, 34, 10000),
                ("Michael", "Sales", "NY", 86000, 56, 20000),
                ("Robert", "Sales", "CA", 81000, 30, 23000),
                ("Maria", "Finance", "CA", 90000, 24, 23000),
                ("Raman", "Finance", "CA", 99000, 40, 24000),
                ("Scott", "Finance", "NY", 83000, 36, 19000),
                ("Jen", "Finance", "NY", 79000, 53, 15000),
                ("Jeff", "Marketing", "CA", 80000, 25, 18000),
                ("Kumar", "Marketing", "NY", 91000, 50, 21000)
                ]
schema = ["employee_name", "department",
            "state", "salary", "age", "bonus"]
df = spark.createDataFrame(data=simpleData, schema=schema)
data = df.groupBy("department").count() \
    .select(col("department").alias("name"), col("count").alias("value")) \
    .toJSON().collect()
print(data)

spark.stop()
</code>```

When I ran the code it gives an array string:

```<code>[
 '{"name":"Sales","value":3}',
 '{"name":"Finance","value":4}',
 '{"name":"Marketing","value":2}'
]
</code>```

but I don't want an array string, I want an array object to send to frontend

```<code>[
 {"name":"Sales","value":3},
 {"name":"Finance","value":4},
 {"name":"Marketing","value":2}
]
</code>```

Can anyone help me?

答:
You need to deserialize the json on the driver side:

```<code>import json
deserialized_data = [json.loads(s) for s in data]

print(deserialized_data)
print(deserialized_data[0]["name"])
</code>```

If you add the above lines after the collect, then deserialized_data will be a list of dictionary objects.

Output of the two prints with your provided data:

```<code>[{'name': 'Finance', 'value': 4}, {'name': 'Sales', 'value': 3}, {'name': 'Marketing', 'value': 2}]
Finance
</code>```

Title: Pyspark convert df to array of objects

Body:
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.getOrCreate()

simpleData = [("James", "Sales", "NY", 90000, 34, 10000),
                ("Michael", "Sales", "NY", 86000, 56, 20000),
                ("Robert", "Sales", "CA", 81000, 30, 23000),
                ("Maria", "Finance", "CA", 90000, 24, 23000),
                ("Raman", "Finance", "CA", 99000, 40, 24000),
                ("Scott", "Finance", "NY", 83000, 36, 19000),
                ("Jen", "Finance", "NY", 79000, 53, 15000),
                ("Jeff", "Marketing", "CA", 80000, 25, 18000),
                ("Kumar", "Marketing", "NY", 91000, 50, 21000)
                ]
schema = ["employee_name", "department",
            "state", "salary", "age", "bonus"]
df = spark.createDataFrame(data=simpleData, schema=schema)
data = df.groupBy("department").count() \
    .select(col("department").alias("name"), col("count").alias("value")) \
    .toJSON().collect()
print(data)

spark.stop()

When I ran the code it gives an array string:

[
 '{"name":"Sales","value":3}',
 '{"name":"Finance","value":4}',
 '{"name":"Marketing","value":2}'
]

but I don't want an array string, I want an array object to send to frontend

[
 {"name":"Sales","value":3},
 {"name":"Finance","value":4},
 {"name":"Marketing","value":2}
]

Can anyone help me?

Body:
You need to deserialize the json on the driver side:

import json
deserialized_data = [json.loads(s) for s in data]

print(deserialized_data)
print(deserialized_data[0]["name"])

If you add the above lines after the collect, then deserialized_data will be a list of dictionary objects.

Output of the two prints with your provided data:

[{'name': 'Finance', 'value': 4}, {'name': 'Sales', 'value': 3}, {'name': 'Marketing', 'value': 2}]
Finance


来源: stackexchange

问:
Querying keys in a docs on mongoDB by prefix
At the moment, i have this data in mongo

```<code>{
   "_id" : ObjectId("62021f4cbd7796d438622245"),
    "id" : "MyData",
    "Mode" : "txtx",
    "MinCost" : "0.2",
    "R:1" : "info1",
    "R:13" : "info2",
    "R:3" : "info3",
    "R:4 : "info4",
    "R:5" : "info5",
    "Cost" : "100"
}

</code>```

I want to return back just the keys from this data that has prefix, for example, "R" or "R:1". Basically, want to return just the keys that matches a prefix that i'm giving.

答:
$expr

$gte

$size

$filter

$replaceRoot

$arrayToObject

$objectToArray

$regexFind

```<code>db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$gte": [
          {
            $size: {
              "$filter": {
                "input": { "$objectToArray": "$$ROOT"},
                "as": "s",
                "cond": { "$regexFind": { "input": "$$s.k", "regex": "R:1" } }
              }
            }
          },
          1
        ]
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": {
          "$filter": {
            "input": { "$objectToArray": "$$ROOT" },
            "as": "s",
            "cond": { "$regexFind": { "input": "$$s.k", "regex": "R:1" } }
          }
        }
      }
    }
  }
])
</code>```

mongoplayground

ContentLicense: CC BY-SA 4.0

Body:
At the moment, i have this data in mongo

{
   "_id" : ObjectId("62021f4cbd7796d438622245"),
    "id" : "MyData",
    "Mode" : "txtx",
    "MinCost" : "0.2",
    "R:1" : "info1",
    "R:13" : "info2",
    "R:3" : "info3",
    "R:4 : "info4",
    "R:5" : "info5",
    "Cost" : "100"
}

I want to return back just the keys from this data that has prefix, for example, "R" or "R:1". Basically, want to return just the keys that matches a prefix that i'm giving.

Body:
$expr

$gte

$size

$filter

$replaceRoot

$arrayToObject

$objectToArray

$regexFind

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$gte": [
          {
            $size: {
              "$filter": {
                "input": { "$objectToArray": "$$ROOT"},
                "as": "s",
                "cond": { "$regexFind": { "input": "$$s.k", "regex": "R:1" } }
              }
            }
          },
          1
        ]
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": {
          "$filter": {
            "input": { "$objectToArray": "$$ROOT" },
            "as": "s",
            "cond": { "$regexFind": { "input": "$$s.k", "regex": "R:1" } }
          }
        }
      }
    }
  }
])

mongoplayground


问:
Is there a way to access the "previous row" value in a SELECT statement?
I need to calculate the difference of a column between two lines of a table. Is there any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.

I'm looking for something like this:

```<code>SELECT value - (previous.value) FROM table
</code>```

Imagining that the "previous" variable reference the latest selected row. Of course with a select like that I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.

Is that possible in some way?

答:
Oracle, PostgreSQL, SQL Server and many more RDBMS engines have analytic functions called LAG and LEAD that do this very thing.

In SQL Server prior to 2012 you'd need to do the following:

```<code>SELECT  value - (
        SELECT  TOP 1 value
        FROM    mytable m2
        WHERE   m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND m2.pk < m1.pk)
        ORDER BY
                col1, pk
        )
FROM mytable m1
ORDER BY
      col1, pk
</code>```

, where COL1 is the column you are ordering by.

Having an index on (COL1, PK) will greatly improve this query.

OwnerDisplayName: Augusto Radtke

ContentLicense: CC BY-SA 3.0

Body:
I need to calculate the difference of a column between two lines of a table. Is there any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.

I'm looking for something like this:

SELECT value - (previous.value) FROM table

Imagining that the "previous" variable reference the latest selected row. Of course with a select like that I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.

Is that possible in some way?

Body:
Oracle, PostgreSQL, SQL Server and many more RDBMS engines have analytic functions called LAG and LEAD that do this very thing.

In SQL Server prior to 2012 you'd need to do the following:

SELECT  value - (
        SELECT  TOP 1 value
        FROM    mytable m2
        WHERE   m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND m2.pk < m1.pk)
        ORDER BY
                col1, pk
        )
FROM mytable m1
ORDER BY
      col1, pk

, where COL1 is the column you are ordering by.

Having an index on (COL1, PK) will greatly improve this query.

OwnerDisplayName: Quassnoi

LastEditorDisplayName: Quassnoi


问:
Java Regex not matching?
I have this code, but it does not seem to be working.

```<code>Pattern pattern=Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);");
Matcher matcher=pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com");
System.out.println(matcher.matches());
</code>```

Would anyone know why?

答:
Assuming your aim is to extract the IMGURSESSION:

```<code>import java.util.regex.*;

Pattern pattern = Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);.*");
Matcher matcher = pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com");
if (matcher.find()) {
    System.out.println(matcher.group(1));
}
</code>```

Just make sure you put in a match all pattern at the end to satisfy the "matcher" semantics.

Title: Java Regex not matching?

Body:
I have this code, but it does not seem to be working.

Pattern pattern=Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);");
Matcher matcher=pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com");
System.out.println(matcher.matches());

Would anyone know why?

Body:
Assuming your aim is to extract the IMGURSESSION:

import java.util.regex.*;

Pattern pattern = Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);.*");
Matcher matcher = pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com");
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Just make sure you put in a match all pattern at the end to satisfy the "matcher" semantics.


问:
How can javaScript library and css files load before component load in reactjs
How can javaScript library and css files load before reactjs component load.

I am converting dataTable Html template  to react component but javaScript library and css files are isn't loaded with components.

How can I solved it. Can any one help me?

答:
You can use these lines at your very first component like app.js which renders first ater index.js(for class based components)

```<code>    componentDidMount () {
    const script = document.createElement("script");

    script.src = "https://use.typekit.net/foobar.js";
    script.async = true;

    document.body.appendChild(script);
}
</code>```

And for functional components

```<code>useEffect(() => {
    const script = document.createElement("script");

    script.src = "https://use.typekit.net/foobar.js";
    script.async = true;

    document.body.appendChild(script);
}, []);
</code>```

Body:
You can use these lines at your very first component like app.js which renders first ater index.js(for class based components)

    componentDidMount () {
    const script = document.createElement("script");

    script.src = "https://use.typekit.net/foobar.js";
    script.async = true;

    document.body.appendChild(script);
}

And for functional components

useEffect(() => {
    const script = document.createElement("script");

    script.src = "https://use.typekit.net/foobar.js";
    script.async = true;

    document.body.appendChild(script);
}, []);


问:
How to sum value in javascript array obj from specific search category to useState
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

```<code>const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]
</code>```

How can i interate arr to get this effect ?

```<code>const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)
</code>```

Thanks you for your help ;-)

答:
You can create the function with reduce. Like this:

const arr = [
  { id: "222", cost: 2, category: "fit" },
  { id: "333", cost: 3, category: "fat" },
  { id: "11", cost: 1, category: "fat" },
  { id: "11", cost: 0, category: "fit" },
  { id: "33", cost: 55, category: "slim" },
  { id: "55", cost: 33, category: "slim" },
  { id: "123", cost: 4, category: "slim" }
];
const sumArrBy = (arr = [], category = "") =>
  arr.reduce(
    (prev, { cost, category: cat }) =>
      cat === category ? prev + cost : prev,
    0
  );

console.log(sumArrBy(arr, 'fit'))
console.log(sumArrBy(arr, 'fat'))
console.log(sumArrBy(arr, 'slim'))```
</div>
</div>
</p>
<p>Then you can set your state like this:</p>
<pre class="lang-js prettyprint-override"><code>const [fit] = useState(sumArrBy(arr, "fit"));
const [fat] = useState(sumArrBy(arr, "fat"));
const [slim] = useState(sumArrBy(arr, "slim"));
</code>```

Full code:

export default function App() {
  const arr = [
    { id: "222", cost: 2, category: "fit" },
    { id: "333", cost: 3, category: "fat" },
    { id: "11", cost: 1, category: "fat" },
    { id: "11", cost: 0, category: "fit" },
    { id: "33", cost: 55, category: "slim" },
    { id: "55", cost: 33, category: "slim" },
    { id: "123", cost: 4, category: "slim" }
  ];
  const sumArrBy = (arr = [], category = "") =>
    arr.reduce(
      (prev, { cost, category: cat }) =>
        cat === category ? prev + cost : prev,
      0
    );

  const [fit] = useState(sumArrBy(arr, "fit"));
  const [fat] = useState(sumArrBy(arr, "fat"));
  const [slim] = useState(sumArrBy(arr, "slim"));

  return (

Hello CodeSandbox

Start editing to see some magic happen!

        {fit}, {fat}, {slim}{" "}

  );
}
```

The working demo you can find here - codesandbox

EDIT:
Other solutions for this issue have the "filter" function, which is not necessarily, because it makes another loop to filter values. In my case, I don't use the "filter". My solution is checking the category directly in the "reduce". It checks the category, and if the category is true, the function adds value cost to the results, if not, it skips and returns the previous correctly value.

Body:
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]

How can i interate arr to get this effect ?

const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)

Thanks you for your help ;-)

Body:
You can create the function with reduce. Like this:

const arr = [
  { id: "222", cost: 2, category: "fit" },
  { id: "333", cost: 3, category: "fat" },
  { id: "11", cost: 1, category: "fat" },
  { id: "11", cost: 0, category: "fit" },
  { id: "33", cost: 55, category: "slim" },
  { id: "55", cost: 33, category: "slim" },
  { id: "123", cost: 4, category: "slim" }
];
const sumArrBy = (arr = [], category = "") =>
  arr.reduce(
    (prev, { cost, category: cat }) =>
      cat === category ? prev + cost : prev,
    0
  );

console.log(sumArrBy(arr, 'fit'))
console.log(sumArrBy(arr, 'fat'))
console.log(sumArrBy(arr, 'slim'))

Then you can set your state like this:

const [fit] = useState(sumArrBy(arr, "fit"));
const [fat] = useState(sumArrBy(arr, "fat"));
const [slim] = useState(sumArrBy(arr, "slim"));

Full code:

export default function App() {
  const arr = [
    { id: "222", cost: 2, category: "fit" },
    { id: "333", cost: 3, category: "fat" },
    { id: "11", cost: 1, category: "fat" },
    { id: "11", cost: 0, category: "fit" },
    { id: "33", cost: 55, category: "slim" },
    { id: "55", cost: 33, category: "slim" },
    { id: "123", cost: 4, category: "slim" }
  ];
  const sumArrBy = (arr = [], category = "") =>
    arr.reduce(
      (prev, { cost, category: cat }) =>
        cat === category ? prev + cost : prev,
      0
    );

  const [fit] = useState(sumArrBy(arr, "fit"));
  const [fat] = useState(sumArrBy(arr, "fat"));
  const [slim] = useState(sumArrBy(arr, "slim"));

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div>
        {fit}, {fat}, {slim}{" "}
      </div>
    </div>
  );
}

The working demo you can find here - codesandbox

EDIT:
Other solutions for this issue have the "filter" function, which is not necessarily, because it makes another loop to filter values. In my case, I don't use the "filter". My solution is checking the category directly in the "reduce". It checks the category, and if the category is true, the function adds value cost to the results, if not, it skips and returns the previous correctly value.


问:
Previous & next page link in Gatsby Blog
I wonder what I'm doing wrong trying to create previous & next page link in my Gatsby website, below is the bug I'm trying to solve.

when I click the previous or next link instead of going to the requested page it creates the below route which is not suppose to do!

that's if i click previous

as well as in next

my code for Gatsby-node.js as below

```<code>const { createFilePath } = require(`gatsby-source-filesystem`)
const path = require("path")

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `Mdx`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const results1 = await graphql(`
    query content {
      allMdx(filter: { frontmatter: { key: { eq: "projects" } } }) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const results2 = await graphql(`
    query content {
      allMdx(
        filter: { frontmatter: { key: { eq: "article" } } }
        sort: { fields: frontmatter___date, order: ASC }
      ) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const projectTemplate = path.resolve(`./src/templates/project-details.js`)
  const blogTemplate = path.resolve(`./src/templates/blog-details.js`)
  if (results1.errors || results2.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  const posts = results2.data.allMdx.nodes

  posts.forEach((post, index) => {
    const previous = index === 0 ? null : posts[index - 1]
    const next = index === posts.length - 1 ? null : posts[index + 1]
    createPage({
      path: `/blog/${post.frontmatter.slug}`,
      component: blogTemplate,
      context: {
        slug: post.frontmatter.slug,
        previous,
        next,
      },
    })
  })

  results1.data.allMdx.nodes.forEach(node => {
    createPage({
      path: `/projects/${node.frontmatter.slug}`,
      component: projectTemplate,
      context: { slug: node.frontmatter.slug },
    })
  })
}
</code>```

and My code for blog posts page as below

```<code>import React from "react"
import { graphql, Link } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
import Layout from "../components/Layout"
import * as styles from "../styles/blog-details.module.css"

const BlogPosts = ({ data, pageContext }) => {
  console.log(pageContext)
  const { body } = data.article
  const { title, date, stack, featuredImg } = data.article.frontmatter
  const { previous, next } = pageContext

  return (
    <Layout>
      <div className={styles.details}>
        <h2>{title}</h2>
        <p>{date}</p>
        <p>{stack}</p>
        <div className={styles.featured}>
          <GatsbyImage
            image={getImage(featuredImg.childImageSharp.gatsbyImageData)}
            alt={title}
          />
        </div>
        <article className={styles.body}>
          <MDXRenderer>{body}</MDXRenderer>
        </article>
        {previous && (
          <Link to={previous.frontmatter.slug}>
            <h5>{previous.frontmatter.title}</h5>
          </Link>
        )}
        {next && (
          <Link to={next.frontmatter.slug}>
            <h5>{next.frontmatter.title}</h5>
          </Link>
        )}
      </div>
    </Layout>
  )
}

export default BlogPosts

export const query = graphql`
  query BlogDetails($slug: String) {
    article: mdx(frontmatter: { slug: { eq: $slug }, key: { eq: "article" } }) {
      body
      frontmatter {
        slug
        key
        title
        date
        stack
        featuredImg {
          childImageSharp {
            gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
          }
        }
      }
    }
  }
`
</code>```

thanks in advance for your help on this.

答:
If I understood you correctly, the URL that is generated when clicking the previous and next buttons is "concatenating" the slug of the post to the current URL instead of replacing it, isn't it?

So, instead of creating a URL like localhost:8000/blog/next-article is generating a localhost:8000/blog/current-article/next-article.

This is because of the way you generate the links. You can spot the links route just by hovering the links to see that the URL of the previous/next article is being added at the end of the URL instead of replacing it.

This is because you are not adding the correct relativity to the links. Simply use:

```<code>{previous && (
  <Link to={`/blog/${previous.frontmatter.slug}`}>
    <h5>{previous.frontmatter.title}</h5>
  </Link>
)}
{next && (
  <Link to={`/blog/${next.frontmatter.slug}`}>
    <h5>{next.frontmatter.title}</h5>
  </Link>
)}
</code>```

Starting the to property with a slash (/) fixes the relativity. Because your article is inside the /blog/ page you need to add it to the path.

This is the way the anchors () work in HTML as well.

Body:
I wonder what I'm doing wrong trying to create previous & next page link in my Gatsby website, below is the bug I'm trying to solve.

when I click the previous or next link instead of going to the requested page it creates the below route which is not suppose to do!

that's if i click previous

as well as in next

my code for Gatsby-node.js as below

const { createFilePath } = require(`gatsby-source-filesystem`)
const path = require("path")

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `Mdx`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const results1 = await graphql(`
    query content {
      allMdx(filter: { frontmatter: { key: { eq: "projects" } } }) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const results2 = await graphql(`
    query content {
      allMdx(
        filter: { frontmatter: { key: { eq: "article" } } }
        sort: { fields: frontmatter___date, order: ASC }
      ) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const projectTemplate = path.resolve(`./src/templates/project-details.js`)
  const blogTemplate = path.resolve(`./src/templates/blog-details.js`)
  if (results1.errors || results2.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  const posts = results2.data.allMdx.nodes

  posts.forEach((post, index) => {
    const previous = index === 0 ? null : posts[index - 1]
    const next = index === posts.length - 1 ? null : posts[index + 1]
    createPage({
      path: `/blog/${post.frontmatter.slug}`,
      component: blogTemplate,
      context: {
        slug: post.frontmatter.slug,
        previous,
        next,
      },
    })
  })

  results1.data.allMdx.nodes.forEach(node => {
    createPage({
      path: `/projects/${node.frontmatter.slug}`,
      component: projectTemplate,
      context: { slug: node.frontmatter.slug },
    })
  })
}

and My code for blog posts page as below

import React from "react"
import { graphql, Link } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
import Layout from "../components/Layout"
import * as styles from "../styles/blog-details.module.css"

const BlogPosts = ({ data, pageContext }) => {
  console.log(pageContext)
  const { body } = data.article
  const { title, date, stack, featuredImg } = data.article.frontmatter
  const { previous, next } = pageContext

  return (
    <Layout>

{title}

{date}

{stack}

          <GatsbyImage
            image={getImage(featuredImg.childImageSharp.gatsbyImageData)}
            alt={title}
          />

          <MDXRenderer>{body}</MDXRenderer>

        {previous && (
          <Link to={previous.frontmatter.slug}>

{previous.frontmatter.title}

          </Link>
        )}
        {next && (
          <Link to={next.frontmatter.slug}>

{next.frontmatter.title}

          </Link>
        )}

    </Layout>
  )
}

export default BlogPosts

export const query = graphql`
  query BlogDetails($slug: String) {
    article: mdx(frontmatter: { slug: { eq: $slug }, key: { eq: "article" } }) {
      body
      frontmatter {
        slug
        key
        title
        date
        stack
        featuredImg {
          childImageSharp {
            gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
          }
        }
      }
    }
  }
`

thanks in advance for your help on this.

Body:
If I understood you correctly, the URL that is generated when clicking the previous and next buttons is "concatenating" the slug of the post to the current URL instead of replacing it, isn't it?

So, instead of creating a URL like localhost:8000/blog/next-article is generating a localhost:8000/blog/current-article/next-article.

This is because of the way you generate the links. You can spot the links route just by hovering the links to see that the URL of the previous/next article is being added at the end of the URL instead of replacing it.

This is because you are not adding the correct relativity to the links. Simply use:

{previous && (
  <Link to={`/blog/${previous.frontmatter.slug}`}>
    <h5>{previous.frontmatter.title}</h5>
  </Link>
)}
{next && (
  <Link to={`/blog/${next.frontmatter.slug}`}>
    <h5>{next.frontmatter.title}</h5>
  </Link>
)}

Starting the to property with a slash (/) fixes the relativity. Because your article is inside the /blog/ page you need to add it to the path.

This is the way the anchors (<a>) work in HTML as well.


问:
C++ check if entered value is unsigned integer
I'm trying to get unsigned integer from std::cin.

When enter a char or string my program stucks

```<code>#include <iostream>
#include <climits>

using namespace std;

int main()
{
    unsigned int number;
    do
    {
        cout << "Enter a unsigned number\t";
        cin >> number;

        if (0 < number && number < 65535 && std::cin.good())
        {
            cout << "It's a number";
            break;
        }
        cout << "Not a number";
    } while (true);
}
</code>```

How to do that ?

答:
You can use getline() function of string class and achieve it as below:

```<code>#include <iostream>
#include <climits>
#include <sstream>

using namespace std;

int main()
{
    string number;
    do
    {
        cout << "Enter an unsigned number\t";

        unsigned int num;
        while (getline(cin, number))
        {
            if(number.at(0) != '-')
            {
                stringstream ss(number);
                if (ss >> num)
                {
                    if (ss.eof())
                    {   // Success as found numbers
                        break;
                    }
                }
                cout << "Error in input!" << endl;
            }
            cout << "Error as -ve number!" << endl;
        }

        cout << "Entered num " << num << endl;
    } while (true);
}
</code>```

Further you can modify this function as per your need to add constraint for accepting numbers. This solution is to avoid your infinite loop and accepting numbers.

Body:
I'm trying to get unsigned integer from std::cin.

When enter a char or string my program stucks

#include <iostream>
#include <climits>

using namespace std;

int main()
{
    unsigned int number;
    do
    {
        cout << "Enter a unsigned number\t";
        cin >> number;

        if (0 < number && number < 65535 && std::cin.good())
        {
            cout << "It's a number";
            break;
        }
        cout << "Not a number";
    } while (true);
}

How to do that ?

Body:
You can use getline() function of string class and achieve it as below:

#include <iostream>
#include <climits>
#include <sstream>

using namespace std;

int main()
{
    string number;
    do
    {
        cout << "Enter an unsigned number\t";

        unsigned int num;
        while (getline(cin, number))
        {
            if(number.at(0) != '-')
            {
                stringstream ss(number);
                if (ss >> num)
                {
                    if (ss.eof())
                    {   // Success as found numbers
                        break;
                    }
                }
                cout << "Error in input!" << endl;
            }
            cout << "Error as -ve number!" << endl;
        }

        cout << "Entered num " << num << endl;
    } while (true);
}

Further you can modify this function as per your need to add constraint for accepting numbers. This solution is to avoid your infinite loop and accepting numbers.


问:
Button element in array with onClick property to change state the specific button that is clicked
I have an array of button that is rendered using .map to print out the rows in data table. Each row have button that trigger the Edit panel popup. The problem that I currently have is when one button is clicked, the Edit panel on all rows.

The code:

```<code>          const [showEdit, setShowEdit] = useState([]);

          <tbody>
            {appSettingsList.map((appSettings, i) => (
              <tr key={i}>
                <td>{appSettings.Name}</td>
                <td>{appSettings.BackgroundColor}</td>
                <td>{appSettings.FontSize}</td>
                <td>{appSettings.FontFamily}</td>
                <td>{appSettings.Theme}</td>
                <td>{appSettings.NavigationBar}</td>
                <td className="action-column">
                  <button
                    key={i}
                    className="button-green"
                    onClick={() => setShowEdit(!showEdit)}
                  >
                    Edit
                  </button>
                </td>
                <td>{showEdit ? <EditApplicationSettings /> : null}</td>
              </tr>
            ))}
          </tbody>
</code>```

How can I make that each button have different state?

答:
Your state should be index of active row</p>
```<code>      const [activeIndex, setActiveIndex] = useState(null);

      <tbody>
        {appSettingsList.map((appSettings, i) => (
          <tr key={i}>
            <td>{appSettings.Name}</td>
            <td>{appSettings.BackgroundColor}</td>
            <td>{appSettings.FontSize}</td>
            <td>{appSettings.FontFamily}</td>
            <td>{appSettings.Theme}</td>
            <td>{appSettings.NavigationBar}</td>
            <td className="action-column">
              <button
                key={i}
                className="button-green"
                onClick={() => setActiveIndex(i)}
              >
                Edit
              </button>
            </td>
            <td>{activeIndex === i ? ( <button key={i} className="button-green" onClick={() => setActiveIndex(null)} > Edit </button> ) : ( <button key={i} className="button-green" onClick={() => setActiveIndex(i)} > Edit </button> )}</td>
          </tr>
        ))}
      </tbody>
</code>```

Body:
I have an array of button that is rendered using .map to print out the rows in data table. Each row have button that trigger the Edit panel popup. The problem that I currently have is when one button is clicked, the Edit panel on all rows.

The code:

          const [showEdit, setShowEdit] = useState([]);

            {appSettingsList.map((appSettings, i) => (

                {appSettings.Name}
                {appSettings.BackgroundColor}
                {appSettings.FontSize}
                {appSettings.FontFamily}
                {appSettings.Theme}
                {appSettings.NavigationBar}

                  <button
                    key={i}
                    className="button-green"
                    onClick={() => setShowEdit(!showEdit)}
                  >
                    Edit
                  </button>

                {showEdit ? <EditApplicationSettings /> : null}

            ))}

How can I make that each button have different state?

Body:
Your state should be index of active row

      const [activeIndex, setActiveIndex] = useState(null);

      <tbody>
        {appSettingsList.map((appSettings, i) => (
          <tr key={i}>
            <td>{appSettings.Name}</td>
            <td>{appSettings.BackgroundColor}</td>
            <td>{appSettings.FontSize}</td>
            <td>{appSettings.FontFamily}</td>
            <td>{appSettings.Theme}</td>
            <td>{appSettings.NavigationBar}</td>
            <td className="action-column">
              <button
                key={i}
                className="button-green"
                onClick={() => setActiveIndex(i)}
              >
                Edit
              </button>
            </td>
            <td>{activeIndex === i ? ( <button key={i} className="button-green" onClick={() => setActiveIndex(null)} > Edit </button> ) : ( <button key={i} className="button-green" onClick={() => setActiveIndex(i)} > Edit </button> )}</td>
          </tr>
        ))}
      </tbody>


问:
Using environment variable for volumes in docker compose
I'm trying to bind environment variables and values that I set in docker compose, however I don't understand how to reference them, I'm trying like this but it doesn't work</p>
```<code>version: "3.8"

services:
  myapp:
    build: .
    environment:
      LOG_PATH_HOST: C:/Users/Anton/Data
      LOG_PATH_CONTAINER: /var/log/kotlin_logger/
    volumes:
      - LOG_PATH_HOST:LOG_PATH_CONTAINER
</code>```

答:
You put environment variables for docker-compose into a file called .env in the same directory as the docker-compose file.

Example:

.env file

```<code>DOCKER_COMPOSE_VARIABLE=MyValue
</code>```

docker-compose.yml file

```<code>version: '3.9'
services:
  myservice:
    image: my_image
    environment:
      CONTAINER_VARIABLE: ${DOCKER_COMPOSE_VARIABLE}
</code>```

Now, when the container runs, it'll have an environment variable called CONTAINER_VARIABLE with the value 'MyValue'.

Body:
I'm trying to bind environment variables and values that I set in docker compose, however I don't understand how to reference them, I'm trying like this but it doesn't work

version: "3.8"

services:
  myapp:
    build: .
    environment:
      LOG_PATH_HOST: C:/Users/Anton/Data
      LOG_PATH_CONTAINER: /var/log/kotlin_logger/
    volumes:
      - LOG_PATH_HOST:LOG_PATH_CONTAINER

Body:
You put environment variables for docker-compose into a file called .env in the same directory as the docker-compose file.

Example:

.env file

DOCKER_COMPOSE_VARIABLE=MyValue

docker-compose.yml file

version: '3.9'
services:
  myservice:
    image: my_image
    environment:
      CONTAINER_VARIABLE: ${DOCKER_COMPOSE_VARIABLE}

Now, when the container runs, it'll have an environment variable called CONTAINER_VARIABLE with the value 'MyValue'.


问:
Slicing Error when using custom cost function in Keras
I have example data. This data is used to set the predictor (x) and response (y) variables:

x has an Age_Years feature and y has Age_Years and target features:

I have a custom cost function that accepts multiple parameters:

```<code># this gives the y_pred values
def calc_prob(param1, param2, param3, age):
    prob = (((100*param1*pow((100/param3),-(pow((age/param2),param1))))*pow(age/param2,param1)*math.log(100/param3))/age)/100
    return prob

# this serves as the custom cost function
def brier_score(y_pred, y_true):
  prob = calc_prob(y_pred[:, 0], y_pred[:, 1], y_pred[:, 2], y_true['Age_Years'])
  brier_score = tf.reduce_mean((prob - y_true['target']) ** 2, axis=1)
  return brier_score
</code>```

Ultimately, I want an output that builds a 3-parameter model that minimizes the brier_score() function. If I try to build and run the model, I get an error:

```<code>from keras import models
from keras import layers

def build_model():
    model = models.Sequential()
    model.add(layers.Dense(1, activation='relu', input_shape=(x.shape[1],)))
    model.add(layers.Dense(5, activation='relu'))
    model.add(layers.Dense(3, activation='softmax'))
    model.compile(loss=losses, optimizer='adam', metrics=['accuracy'])
    return model

model = build_model()
losses=[brier_score]
model.compile(loss=losses, optimizer='adam', metrics=['accuracy'])
# this line causes the error
model.fit(x=x, y=y, epochs=100, verbose=0)
</code>```

ValueError: slice index 2 of dimension 1 out of bounds. for '{{node brier_score/strided_slice_2}} = StridedSlice[Index=DT_INT32, T=DT_FLOAT, begin_mask=1, ellipsis_mask=0, end_mask=1, new_axis_mask=0, shrink_axis_mask=2](Cast, brier_score/strided_slice_2/stack, brier_score/strided_slice_2/stack_1, brier_score/strided_slice_2/stack_2)' with input shapes: [?,2], [2], [2], [2] and with computed input tensors: input[1] = <0 2>, input[2] = <0 3>, input[3] = <1 1>.

答:
You are mixing up the order of y_true and y_pred in brier_score. Here is a working example:

import tensorflow as tf
from keras import models
from keras import layers
import pandas as pd
import numpy as np

x = np.random.random((500, 1))
y = {'Age_Years': np.squeeze(x, axis=1), 'target': np.random.randint(2, size=500)}

def calc_prob(param1, param2, param3, age):
    prob = (((100*param1*tf.math.pow((100/param3),-(tf.math.pow((age/param2),param1))))*tf.math.pow(age/param2,param1)*tf.math.log(100/param3))/age)/100
    return prob

# this serves as the custom cost function
def brier_score(y_true, y_pred):
  prob = calc_prob(y_pred[:, 0], y_pred[:, 1], y_pred[:, 2], tf.cast(y_true['Age_Years'], dtype=tf.float32))
  brier_score = tf.reduce_mean((prob - tf.cast(y_true['target'], dtype=tf.float32)) ** 2, axis=-1, keepdims=True)
  return brier_score

def build_model():
    model = models.Sequential()
    model.add(layers.Dense(1, activation='relu', input_shape=(x.shape[1],)))
    model.add(layers.Dense(5, activation='relu'))
    model.add(layers.Dense(3, activation='softmax'))
    return model

model = build_model()
optimizer = tf.keras.optimizers.Adam()
batch_size = 10
dataset = tf.data.Dataset.from_tensor_slices((x,y)).batch(batch_size)

epochs = 2
for epoch in range(epochs):
    print("\nStart of epoch %d" % (epoch,))

    for step, (x_batch_train, y_batch_train) in enumerate(dataset):
        with tf.GradientTape() as tape:
            logits = model(x_batch_train, training=True)
            loss_value = brier_score(y_batch_train, logits)

        grads = tape.gradient(loss_value, model.trainable_weights)
        optimizer.apply_gradients(zip(grads, model.trainable_weights))
```

Body:
I have example data. This data is used to set the predictor (x) and response (y) variables:

x has an Age_Years feature and y has Age_Years and target features:

I have a custom cost function that accepts multiple parameters:

# this gives the y_pred values
def calc_prob(param1, param2, param3, age):
    prob = (((100*param1*pow((100/param3),-(pow((age/param2),param1))))*pow(age/param2,param1)*math.log(100/param3))/age)/100
    return prob

# this serves as the custom cost function
def brier_score(y_pred, y_true):
  prob = calc_prob(y_pred[:, 0], y_pred[:, 1], y_pred[:, 2], y_true['Age_Years'])
  brier_score = tf.reduce_mean((prob - y_true['target']) ** 2, axis=1)
  return brier_score

Ultimately, I want an output that builds a 3-parameter model that minimizes the brier_score() function. If I try to build and run the model, I get an error:

from keras import models
from keras import layers

def build_model():
    model = models.Sequential()
    model.add(layers.Dense(1, activation='relu', input_shape=(x.shape[1],)))
    model.add(layers.Dense(5, activation='relu'))
    model.add(layers.Dense(3, activation='softmax'))
    model.compile(loss=losses, optimizer='adam', metrics=['accuracy'])
    return model

model = build_model()
losses=[brier_score]
model.compile(loss=losses, optimizer='adam', metrics=['accuracy'])
# this line causes the error
model.fit(x=x, y=y, epochs=100, verbose=0)

ValueError: slice index 2 of dimension 1 out of bounds. for '{{node brier_score/strided_slice_2}} = StridedSlice[Index=DT_INT32, T=DT_FLOAT, begin_mask=1, ellipsis_mask=0, end_mask=1, new_axis_mask=0, shrink_axis_mask=2](Cast, brier_score/strided_slice_2/stack, brier_score/strided_slice_2/stack_1, brier_score/strided_slice_2/stack_2)' with input shapes: [?,2], [2], [2], [2] and with computed input tensors: input[1] = <0 2>, input[2] = <0 3>, input[3] = <1 1>.


问:
Include external header file for C on Compiler Explorer
I want to run a C project on Compiler Explorer (godbolt.org) which includes some external header files. What is the procedure to include these third-party header files on there?

Screenshot of the project

Suppose I want to run this code which includes snipmath.h file. Also, snipmath.h header includes other lib files. How can I include all of them in godbolt? like we usually do in a offline compiler.

答:
You can use Compiler Explorer with Cmake and have multiple header and source files. You could even have some other files to read from (like *.ini). Try it here reading *.ini in Compiler Explorer

Note: the examples are with C++, but it must be straightforward to do it with C.


问:
Powershell start-process running windows explorer does not wait
I have a PS script to monitor a logging file for a specific list of servers in the network.  If the script logic finds the issue I'm monitoring for, I want to interrupt the script process with a launch and wait of windows explorer for the related server network folder path.

Windows explorer does show the requested folder, however PS doesn't wait for it to close.

This is the script I'm testing with:

```<code># Sample networkfolderpath
$networkfolderpath = '\\server\d$\parent\child'

Start-Process explorer.exe -ArgumentList $networkfolderpath -Wait
</code>```

FYI: I have a RDP function that is setup the same way and it does wait as expected.

```<code>Start-Process mstsc /v:$computername -Wait
</code>```

I'm presuming at this point that windows explorer just behaves differently than some other exe.

What am I missing?

答:
Here is some proof-of-concept code that opens the given folder and waits until the new shell (Explorer) window has been closed.

This is made possible by the Shell.Application COM object. Its Windows() method returns a list of currently open shell windows. We can query the LocationURL property of each shell window to find the window for a given folder path. Since there could already be a shell window that shows the folder we want to open, I check the number of shell windows to be sure a new window has been opened. Alternatively you could choose to bring an existing shell window to front. Then just loop until the Visible property of the shell window equals $False to wait until the Window has been closed.

```<code>Function Start-Explorer {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)] [String] $Path,
        [Parameter()]          [Switch] $Wait
    )

    $shell = New-Object -ComObject Shell.Application

    $shellWndCountBefore = $shell.Windows().Count

    Invoke-Item $Path

    if( $wait ) {
        Write-Verbose 'Waiting for new shell window...'

        $pathUri = ([System.Uri] (Convert-Path $Path)).AbsoluteUri

        $explorerWnd = $null

        # Loop until the new shell window is found or timeout (30 s) is exceeded.
        foreach( $i in 0..300 ) {
            if( $shell.Windows().Count -gt $shellWndCountBefore ) {
                if( $explorerWnd = $shell.Windows() | Where-Object { $_.Visible -and $_.LocationURL -eq $pathUri }) {
                    break
                }
            }
            Start-Sleep -Milliseconds 100
        }

        if( -not $explorerWnd ) {
            $PSCmdlet.WriteError( [Management.Automation.ErrorRecord]::new(
                [Exception]::new( 'Could not find shell window' ), 'Start-Explorer', [Management.Automation.ErrorCategory]::OperationTimeout, $Path ) )
            return
        }

        Write-Verbose "Found $($explorerWnd.Count) matching explorer window(s)"
        #Write-Verbose ($explorerWnd | Out-String)

        Write-Verbose 'Waiting for user to close explorer window(s)...'

        try {
            while( $explorerWnd.Visible -eq $true ) {
                Start-Sleep -Milliseconds 100
            }
        }
        catch {
            # There might be an exception when the COM object dies before we see Visible = false
            Write-Verbose "Catched exception: $($_.Exception.Message)"
        }

        Write-Verbose 'Explorer window(s) closed'
    }
}

Start-Explorer 'c:\' -Wait -Verbose -EA Stop
</code>```

Body:
I have a PS script to monitor a logging file for a specific list of servers in the network.  If the script logic finds the issue I'm monitoring for, I want to interrupt the script process with a launch and wait of windows explorer for the related server network folder path.

Windows explorer does show the requested folder, however PS doesn't wait for it to close.

This is the script I'm testing with:

# Sample networkfolderpath
$networkfolderpath = '\\server\d$\parent\child'

Start-Process explorer.exe -ArgumentList $networkfolderpath -Wait

FYI: I have a RDP function that is setup the same way and it does wait as expected.

Start-Process mstsc /v:$computername -Wait

I'm presuming at this point that windows explorer just behaves differently than some other exe.

What am I missing?

Body:
Here is some proof-of-concept code that opens the given folder and waits until the new shell (Explorer) window has been closed.

This is made possible by the Shell.Application COM object. Its Windows() method returns a list of currently open shell windows. We can query the LocationURL property of each shell window to find the window for a given folder path. Since there could already be a shell window that shows the folder we want to open, I check the number of shell windows to be sure a new window has been opened. Alternatively you could choose to bring an existing shell window to front. Then just loop until the Visible property of the shell window equals $False to wait until the Window has been closed.

Function Start-Explorer {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)] [String] $Path,
        [Parameter()]          [Switch] $Wait
    )

    $shell = New-Object -ComObject Shell.Application

    $shellWndCountBefore = $shell.Windows().Count

    Invoke-Item $Path

    if( $wait ) {
        Write-Verbose 'Waiting for new shell window...'

        $pathUri = ([System.Uri] (Convert-Path $Path)).AbsoluteUri

        $explorerWnd = $null

        # Loop until the new shell window is found or timeout (30 s) is exceeded.
        foreach( $i in 0..300 ) {
            if( $shell.Windows().Count -gt $shellWndCountBefore ) {
                if( $explorerWnd = $shell.Windows() | Where-Object { $_.Visible -and $_.LocationURL -eq $pathUri }) {
                    break
                }
            }
            Start-Sleep -Milliseconds 100
        }

        if( -not $explorerWnd ) {
            $PSCmdlet.WriteError( [Management.Automation.ErrorRecord]::new(
                [Exception]::new( 'Could not find shell window' ), 'Start-Explorer', [Management.Automation.ErrorCategory]::OperationTimeout, $Path ) )
            return
        }

        Write-Verbose "Found $($explorerWnd.Count) matching explorer window(s)"
        #Write-Verbose ($explorerWnd | Out-String)

        Write-Verbose 'Waiting for user to close explorer window(s)...'

        try {
            while( $explorerWnd.Visible -eq $true ) {
                Start-Sleep -Milliseconds 100
            }
        }
        catch {
            # There might be an exception when the COM object dies before we see Visible = false
            Write-Verbose "Catched exception: $($_.Exception.Message)"
        }

        Write-Verbose 'Explorer window(s) closed'
    }
}

Start-Explorer 'c:\' -Wait -Verbose -EA Stop


问:
How to serve an interactive jupyter notebook cell via desktop or web app?
I'm aware of similar previous questions such as:

What is the easiest way to create a webapp from an interactive Jupyter Notebook?

Exporting Interactive Jupyter Notebook to html

However they are old and outdated (for example dashboards_bundlers is no longer supported...)

Is there any recent progress allowing to turn an interactive notebook into a web/desktop app easily?

答:
There is a framework Mercury that allows to easily convert the notebook to web application. You need to add the YAML header as RAW cell to your notebook.

The example notebook:

```<code>---
title: My app
description: My first notebook shared on Mercury
params:
    greetings:
        input: select
        label: Select greetings
        value: Cześć
        choices: [Cześć, Hello, Hi, Salut, Ciao]
    year:
        input: slider
        label: Select year
        value: 2022
        min: 2021
        max: 2030
---
</code>```

greetings = "Cześć"
year = 2022
```
<pre class="lang-py prettyprint-override"><code>print(f"{greetings} {year}")
</code>```

The above notebook will generate a web app like in the screenshot below:

There is an option to hide the code and only show the output to non-programming users.

The Mercury is built on top of Django, can be easily deployed to any server/cloud.

Body:
There is a framework Mercury that allows to easily convert the notebook to web application. You need to add the YAML header as RAW cell to your notebook.

The example notebook:

---
title: My app
description: My first notebook shared on Mercury
params:
    greetings:
        input: select
        label: Select greetings
        value: Cześć
        choices: [Cześć, Hello, Hi, Salut, Ciao]
    year:
        input: slider
        label: Select year
        value: 2022
        min: 2021
        max: 2030
---

greetings = "Cześć"
year = 2022

print(f"{greetings} {year}")

The above notebook will generate a web app like in the screenshot below:

There is an option to hide the code and only show the output to non-programming users.

The Mercury is built on top of Django, can be easily deployed to any server/cloud.


问:
user = discord.utils.get(client.users, name="name", discriminator="0000") comes back with none
So i want to be able to mention a user when I input there name and discriminator but I cant get it to work as it keeps return none

```<code>import discord

intents = discord.Intents.default()
intents.members = True

client = discord.Client(token=config.TOKEN, intents=intents)

@bot.event
async def on_message(message):
  if message.content == "$test"
     user = discord.utils.get(client.users, name="killogee", discriminator="0141")
     print(user)
</code>```

I've also tried:

user = message.guild.get_member_named("Killogee")

but everytime comes back with none

答:
Set out your txt file like this:

```<code>user1#8583
user2#0637
user3#9729
</code>```

Then just use this

```<code>f = open('names.txt','r').splitlines() # Opens the text file and turns it into a list
for i in f: # Iterate through that list
    i = i.split('#') # Split the line in two via the hashtag
    user = discord.utils.get(client.users, name=i[0], discriminator=i[1])
    # i[0] is the name, such as user1 and i[1] is the discriminator after the hashtag
    print(user)
</code>```

It should work, so make sure that your names are correct and up to date

Body:
So i want to be able to mention a user when I input there name and discriminator but I cant get it to work as it keeps return none

import discord

intents = discord.Intents.default()
intents.members = True

client = discord.Client(token=config.TOKEN, intents=intents)

@bot.event
async def on_message(message):
  if message.content == "$test"
     user = discord.utils.get(client.users, name="killogee", discriminator="0141")
     print(user)

I've also tried:

user = message.guild.get_member_named("Killogee")

but everytime comes back with none

Body:
Set out your txt file like this:

user1#8583
user2#0637
user3#9729

Then just use this

f = open('names.txt','r').splitlines() # Opens the text file and turns it into a list
for i in f: # Iterate through that list
    i = i.split('#') # Split the line in two via the hashtag
    user = discord.utils.get(client.users, name=i[0], discriminator=i[1])
    # i[0] is the name, such as user1 and i[1] is the discriminator after the hashtag
    print(user)

It should work, so make sure that your names are correct and up to date


问:
Imported module not available when using remote WSL (Win10 -> Ubuntu)
I have used this tutorial to setup remote development in WSL: https://code.visualstudio.com/docs/remote/wsl-tutorial

All works well until I want to load a .py file that imports an external modal.
E.g. I've cloned this repo: https://github.com/AI4Finance-Foundation/FinRL_Podracer/

I can run it successfully using command line.

But when trying to debug I get an error:

Exception has occurred: ModuleNotFoundError - No module named 'gym'

Visual Studio Code also shows an error when hovering over it:

I've obviously tried to run pip install gym in the WSL console. But that doesn't seem to register.

Does anyone know what I'm doing wrong?

答:
I recommend creating an environment instead of using the global environment. Activate that environment and install gym in it. Then try setting your python interpreter in VSCode to run your python file in:

https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment


问:
How do I create a telegram bot ? Error by implementing modul from deno in first line?
```<code>import { TelegramBot, UpdateType } from "https://deno.land/x/telegram_chatbot/mod.ts";   <--- ERROR
import "https://deno.land/x/dot_env@0.2.0/load.ts"

const TOKEN = ("MYTOKENID");
if (!TOKEN) throw new Error("Bot token is not provided");
const bot = new TelegramBot(TOKEN);

bot.on(UpdateType.Message, async (message: any) => {

    const text = message.message.text || "I can't hear you";

    await bot.sendMessage({ chat_id: message.message.chat.id, text: `echo ${text}` })

});

bot.run({
    polling: true,
});
</code>```

[{
"resource": "/Users/bgrnaymane/Documents/GitHub/crypto_price_api/telegrambot.ts",
"owner": "typescript",
"code": "2691",
"severity": 8,
"message": "Ein Importpfad darf nicht mit einer Erweiterung ".ts" enden. Importieren Sie ggf. stattdessen "https://deno.land/x/telegram_chatbot/mod".",
"source": "ts",
"startLineNumber": 2,
"startColumn": 41,
"endLineNumber": 2,
"endColumn": 86
}]

Ein Importpfad darf nicht mit einer Erweiterung ".ts" enden. Importieren Sie ggf. stattdessen "https://deno.land/x/telegram_chatbot/mod".

答:
A better alternative

I don't know much about the library you are using currently but there is a much better option availaible for making telegram bots and it's written in deno and typescript, but it supports deno and node both due to transpiling.
The library is called grammy also it has a ton of plugins and a wonderful team of devs working to improve it.

A code snippet from the official docs to show how cleaner the code is in grammy.

```<code>import { Bot } from "https://deno.land/x/grammy/mod.ts";

// Create an instance of the `Bot` class and pass your authentication token to it.
const bot = new Bot(""); // <-- put your authentication token between the ""

// You can now register listeners on your bot object `bot`.
// grammY will call the listeners when users send messages to your bot.

// Handle the /start command.
bot.command("start", (ctx) => ctx.reply("Welcome! Up and running."));
// Handle other messages.
bot.on("message", (ctx) => ctx.reply("Got another message!"));

// Now that you specified how to handle messages, you can start your bot.
// This will connect to the Telegram servers and wait for messages.

// Start the bot.
bot.start();
</code>```

you can give it a try if you want ...also the link to the community chat.

Body:
import { TelegramBot, UpdateType } from "https://deno.land/x/telegram_chatbot/mod.ts";   <--- ERROR
import "https://deno.land/x/dot_env@0.2.0/load.ts"

const TOKEN = ("MYTOKENID");
if (!TOKEN) throw new Error("Bot token is not provided");
const bot = new TelegramBot(TOKEN);

bot.on(UpdateType.Message, async (message: any) => {

    const text = message.message.text || "I can't hear you";

    await bot.sendMessage({ chat_id: message.message.chat.id, text: `echo ${text}` })

});

bot.run({
    polling: true,
});

[{
"resource": "/Users/bgrnaymane/Documents/GitHub/crypto_price_api/telegrambot.ts",
"owner": "typescript",
"code": "2691",
"severity": 8,
"message": "Ein Importpfad darf nicht mit einer Erweiterung ".ts" enden. Importieren Sie ggf. stattdessen "https://deno.land/x/telegram_chatbot/mod".",
"source": "ts",
"startLineNumber": 2,
"startColumn": 41,
"endLineNumber": 2,
"endColumn": 86
}]

Ein Importpfad darf nicht mit einer Erweiterung ".ts" enden. Importieren Sie ggf. stattdessen "https://deno.land/x/telegram_chatbot/mod".

Body:
A better alternative

I don't know much about the library you are using currently but there is a much better option availaible for making telegram bots and it's written in deno and typescript, but it supports deno and node both due to transpiling.
The library is called grammy also it has a ton of plugins and a wonderful team of devs working to improve it.

A code snippet from the official docs to show how cleaner the code is in grammy.

import { Bot } from "https://deno.land/x/grammy/mod.ts";

// Create an instance of the `Bot` class and pass your authentication token to it.
const bot = new Bot(""); // <-- put your authentication token between the ""

// You can now register listeners on your bot object `bot`.
// grammY will call the listeners when users send messages to your bot.

// Handle the /start command.
bot.command("start", (ctx) => ctx.reply("Welcome! Up and running."));
// Handle other messages.
bot.on("message", (ctx) => ctx.reply("Got another message!"));

// Now that you specified how to handle messages, you can start your bot.
// This will connect to the Telegram servers and wait for messages.

// Start the bot.
bot.start();

you can give it a try if you want ...also the link to the community chat.


问:
SSH clone/push to Bitbucket Forbidden
When I clone through ssh, I have the error like this:

Forbidden fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository
exists.

I have followed up a few tutorials. The pub key is added to my account in personal settings => security => SSH keys

There is a trouble shooting page. I loaded the key by using

ssh-add

If I run

```<code>ssh -T git@bitbucket.org
</code>```

I got

authenticated via ssh key.

You can use git to connect to Bitbucket. Shell access is disabled

This response doesn't fit to any cases, it doesn't show pubkey errors, etc. The closest case, which is the correct response is:

```<code>authenticated via ssh key.
"conq: logged in as username."
You can use git to connect to Bitbucket. Shell access is disabled
</code>```

The "" part is missing in my case.

That is why I can't find a solution through other posts.

My port 22 is not blocked, I can ssh to my server or other places well. I am doing this at home, there isn't any extra firewall. I can ssh clone on Github using keys.

Update:

I removed the key in Bitbucket and tried to add the same key. It shows a duplication error:

Someone has already added that SSH key.

After removed the key, I tried the ssh command again, it shows

authenticated via ssh key.

Theoretically, there exists no duplicated keys. If I added this key, no one else can add it again.
When I remove it, this key shouldn't exist in their database anymore, so that the ssh command should gives invalid pubkey error and there shouldn't be a duplication error when I tried to add it agin.

I really feel there is a bug on my account on Bitbucket, but I really believe this can happen.

答:
If you have multiple private keys in your $HOME/.ssh to access remote repositories, your git command might be using the wrong one (even if you added correct key to ssh-agent and removed others and ssh -T git@bitbucket.org is successfull). Try explicitly specifying which SSH key to use with environment variable:

```<code>GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example
</code>```

If it works, learn How to tell git which private key to use and save the setting permanently.

Title: SSH clone/push to Bitbucket Forbidden

Body:
When I clone through ssh, I have the error like this:

Forbidden fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository
exists.

I have followed up a few tutorials. The pub key is added to my account in personal settings => security => SSH keys

There is a trouble shooting page. I loaded the key by using

ssh-add

If I run

ssh -T git@bitbucket.org

I got

authenticated via ssh key.

You can use git to connect to Bitbucket. Shell access is disabled

This response doesn't fit to any cases, it doesn't show pubkey errors, etc. The closest case, which is the correct response is:

authenticated via ssh key.
"conq: logged in as username."
You can use git to connect to Bitbucket. Shell access is disabled

The "" part is missing in my case.

That is why I can't find a solution through other posts.

My port 22 is not blocked, I can ssh to my server or other places well. I am doing this at home, there isn't any extra firewall. I can ssh clone on Github using keys.

Update:

I removed the key in Bitbucket and tried to add the same key. It shows a duplication error:

Someone has already added that SSH key.

After removed the key, I tried the ssh command again, it shows

authenticated via ssh key.

Theoretically, there exists no duplicated keys. If I added this key, no one else can add it again.
When I remove it, this key shouldn't exist in their database anymore, so that the ssh command should gives invalid pubkey error and there shouldn't be a duplication error when I tried to add it agin.

I really feel there is a bug on my account on Bitbucket, but I really believe this can happen.

Body:
If you have multiple private keys in your $HOME/.ssh to access remote repositories, your git command might be using the wrong one (even if you added correct key to ssh-agent and removed others and ssh -T git@bitbucket.org is successfull). Try explicitly specifying which SSH key to use with environment variable:

GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example

If it works, learn How to tell git which private key to use and save the setting permanently.


问:
How to parse a string of version numbers in Groovy?
I have a string containing a version number like major.minor.patch.build but I only want to keep major.minor.patch where each number can have 1-3 digits.
How can I do this in groovy?

Examples for a result:
1.20.30.44 -> 1.20.30
or
1.21.1.1 -> 1.21.1

答:
This will work for provided examples.

```<code>def majorMinorPatchBuild = '1.20.30.44'
def majorMinorPatch
if (majorMinorPatchBuild.toList().count('.') < 3) {
    majorMinorPatch = majorMinorPatchBuild
} else {
    majorMinorPatch = majorMinorPatchBuild.split('\\.')[0..-2].join('.')
}
assert majorMinorPatch == '1.20.30'
</code>```

Note, you'll have to implement some error handling if the input data will have some format deviations.

Test on more data:

```<code>[
        '1.2.3',
        '1.2.3.4',
        '11.22.33.44',
        '111.222.333.444'
].each {
    def majorMinorPatchBuild = it
    def majorMinorPatch
    if (majorMinorPatchBuild.toList().count('.') < 3) {
        majorMinorPatch = majorMinorPatchBuild
    } else {
        majorMinorPatch = majorMinorPatchBuild.split('\\.')[0..-2].join('.')
    }

    println("major.minor.patch: '$it' -> '$majorMinorPatch'")
}
</code>```

Output:

```<code>major.minor.patch: '1.2.3' -> '1.2.3'
major.minor.patch: '1.2.3.4' -> '1.2.3'
major.minor.patch: '11.22.33.44' -> '11.22.33'
major.minor.patch: '111.222.333.444' -> '111.222.333'
</code>```

Body:
This will work for provided examples.

def majorMinorPatchBuild = '1.20.30.44'
def majorMinorPatch
if (majorMinorPatchBuild.toList().count('.') < 3) {
    majorMinorPatch = majorMinorPatchBuild
} else {
    majorMinorPatch = majorMinorPatchBuild.split('\\.')[0..-2].join('.')
}
assert majorMinorPatch == '1.20.30'

Note, you'll have to implement some error handling if the input data will have some format deviations.

Test on more data:

[
        '1.2.3',
        '1.2.3.4',
        '11.22.33.44',
        '111.222.333.444'
].each {
    def majorMinorPatchBuild = it
    def majorMinorPatch
    if (majorMinorPatchBuild.toList().count('.') < 3) {
        majorMinorPatch = majorMinorPatchBuild
    } else {
        majorMinorPatch = majorMinorPatchBuild.split('\\.')[0..-2].join('.')
    }

    println("major.minor.patch: '$it' -> '$majorMinorPatch'")
}

Output:

major.minor.patch: '1.2.3' -> '1.2.3'
major.minor.patch: '1.2.3.4' -> '1.2.3'
major.minor.patch: '11.22.33.44' -> '11.22.33'
major.minor.patch: '111.222.333.444' -> '111.222.333'


答:
You need to handle the edit logic for each row independently.

Create a TableRow component with toggling Edit View logic.

```<code>const TableRow = ({ appSettings, i }) => {
    const [showEdit, setShowEdit] = useState([]);

    return (
        <tr key={i}>
            <td>{appSettings.Name}</td>
            <td>{appSettings.BackgroundColor}</td>
            <td>{appSettings.FontSize}</td>
            <td>{appSettings.FontFamily}</td>
            <td>{appSettings.Theme}</td>
            <td>{appSettings.NavigationBar}</td>
            <td className="action-column">
                <button
                    key={i}
                    className="button-green"
                    onClick={() => setShowEdit(!showEdit)}
                >
                    Edit
                </button>
            </td>
            <td>{showEdit ? <EditApplicationSettings /> : null}</td>
        </tr>
    );
};
</code>```

Iterate over TableRow elements.

```<code><tbody>
    {appSettingsList.map((appSettings, i) => (
        <TableRow appSettings={appSettings} i={i} />
    ))}
</tbody>
</code>```

Title: Button element in array with onClick property to change state the specific button that is clicked

Body:
You need to handle the edit logic for each row independently.

Create a TableRow component with toggling Edit View logic.

const TableRow = ({ appSettings, i }) => {
    const [showEdit, setShowEdit] = useState([]);

    return (
        <tr key={i}>
            <td>{appSettings.Name}</td>
            <td>{appSettings.BackgroundColor}</td>
            <td>{appSettings.FontSize}</td>
            <td>{appSettings.FontFamily}</td>
            <td>{appSettings.Theme}</td>
            <td>{appSettings.NavigationBar}</td>
            <td className="action-column">
                <button
                    key={i}
                    className="button-green"
                    onClick={() => setShowEdit(!showEdit)}
                >
                    Edit
                </button>
            </td>
            <td>{showEdit ? <EditApplicationSettings /> : null}</td>
        </tr>
    );
};

Iterate over TableRow elements.

<tbody>
    {appSettingsList.map((appSettings, i) => (
        <TableRow appSettings={appSettings} i={i} />
    ))}
</tbody>


问:
Multiple modals overlay
I need that the overlay shows above the first modal, not in the back.

$('#openBtn').click(function(){
 $('#myModal').modal({show:true})
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Launch modal

<div class="modal" id="myModal">
 <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title">Modal title</h4>
        </div><div class="container"></div>
        <div class="modal-body">
          Content for the dialog / modal goes here.
          <br>
          <br>
          <br>
          <br>
          <br>
          Launch modal
        </div>
        <div class="modal-footer">
          Close
          Save changes
        </div>
      </div>
    </div>
</div>
<div class="modal" id="myModal2" data-backdrop="static">
 <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title">Second Modal title</h4>
        </div><div class="container"></div>
        <div class="modal-body">
          Content for the dialog / modal goes here.
        </div>
        <div class="modal-footer">
          Close
          Save changes
        </div>
      </div>
    </div>
</div>

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

I tried to change the z-index of .modal-backdrop, but it becomes a mess.

In some cases I have more than two modals on the same page.

答:
z-index and modal-backdrop corrections with css

```<code>.modal.fade {
  z-index: 10000000 !important;
  background: rgba(0, 0, 0, 0.5);
}
.modal-backdrop.fade {
  opacity: 0;
}
</code>```

Title: Multiple modals overlay

Body:
I need that the overlay shows above the first modal, not in the back.

$('#openBtn').click(function(){
 $('#myModal').modal({show:true})
});

Launch modal

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

          Content for the dialog / modal goes here.

          Launch modal

          Close
          Save changes

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Second Modal title

          Content for the dialog / modal goes here.

          Close
          Save changes

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" />

I tried to change the z-index of .modal-backdrop, but it becomes a mess.

In some cases I have more than two modals on the same page.

Body:
z-index and modal-backdrop corrections with css

.modal.fade {
  z-index: 10000000 !important;
  background: rgba(0, 0, 0, 0.5);
}
.modal-backdrop.fade {
  opacity: 0;
}


问:
Role Assignment to Resources on Azure
I am logged on to Azure using a Global Admin Account (account I signed up with). There I have created a resource group and it shows I have Contributor access. Why was I not assigned Owner Role instead? How did Azure assign that role to me when that resource group was created.

答: You don't become Owner automatically but if you are a Global Admin, you can elevate access to become a User Access Administrator on the root level (and all underlying subscriptions which are associated to the AAD tenant you are Global Admin at). And with this role, you can assign yourself the Owner role on the resource group. When a new resource group is created, Azure simply inherits the roles assigned to the subscription and management groups above so if you'd assign yourself the Owner role on a subscription, all resource groups that are created in this subscription will inherit you as an Owner.

Title: Role Assignment to Resources on Azure


问:
c# .net framework web api controller error 404 not found
I am an noob in .net framework web api c# so my question is when i try to recieve webhook data the web hook test function that sends data gives a 404 error. I try to call the webhook reciever controller with ...:3001/api/USIAccountWebhook. I can call ...:3001/api/Values with no problem at all.

Beginning of the controller code where i think I'm going wrong:

```<code>public class USIAccountWebhookController : ApiController
{

    [System.Web.Http.Route("webhooks/accountupdated")]
    public async Task<GenericResponseDTO> AccountUpdatedAsync(AccountDTO value)
    {
        string EPrelationID;
        //SecretKey from the notification should always be checked for security.
        if (value.SecretKey != SecretKey)
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
</code>```

<<
Does anyone maybe have an idea or tips?
Thanks!

Best regards,
Jeroen

答:
404 is a very common error that says you taht the URI you're calling did't exist, the Controller code you shared informs us that the correct route for the method you're trying to call is:

```<code>...:3001/api/webhooks/accountupdated
</code>```

as stated here:

```<code>[System.Web.Http.Route("webhooks/accountupdated")]
</code>```

Just to bne sure, also search for something like:

```<code> [RoutePrefix("some_url_chunks_more")]
</code>```

(you need to call the method, not the class)

Body:
I am an noob in .net framework web api c# so my question is when i try to recieve webhook data the web hook test function that sends data gives a 404 error. I try to call the webhook reciever controller with ...:3001/api/USIAccountWebhook. I can call ...:3001/api/Values with no problem at all.

Beginning of the controller code where i think I'm going wrong:

public class USIAccountWebhookController : ApiController
{

    [System.Web.Http.Route("webhooks/accountupdated")]
    public async Task<GenericResponseDTO> AccountUpdatedAsync(AccountDTO value)
    {
        string EPrelationID;
        //SecretKey from the notification should always be checked for security.
        if (value.SecretKey != SecretKey)
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }

<<
Does anyone maybe have an idea or tips?
Thanks!

Best regards,
Jeroen

Body:
404 is a very common error that says you taht the URI you're calling did't exist, the Controller code you shared informs us that the correct route for the method you're trying to call is:

...:3001/api/webhooks/accountupdated

as stated here:

[System.Web.Http.Route("webhooks/accountupdated")]

Just to bne sure, also search for something like:

 [RoutePrefix("some_url_chunks_more")]

(you need to call the method, not the class)


问:
Spring Boot and OAuth2 server
I'm trying to implement a simple OAuth2 server with Spring Boot.
In the first step I added in the main class the annotation @EnableAuthorizationServer

```<code>@SpringBootApplication
@EnableAuthorizationServer
public class PocApplication {

    public static void main(String[] args) {
        SpringApplication.run(PocApplication.class, args);
    }
}
</code>```

and I use the "application.yml" file to configure all the OAuth2 elements.

```<code>server:
  port: 8282
spring:
  security:
    user:
      name: root
      password: root
      roles: ADMIN,USER
security:
  oauth2:
    client:
      client-id: mobile
      client-secret: pin
      access-token-validity-seconds: 3600
      authorized-grant-types: client_credential,password
      scope: READ, WRITE
    authorization:
      check-token-access: permitAll
</code>```

With this configuration everything works fine.

In the second step I tried to switch the configuration from yml file to java class.

These are the classes that I created

```<code>@Configuration
public class AuthServerConfigurations extends WebSecurityConfigurerAdapter implements AuthorizationServerConfigurer {

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    AuthenticationManager authenticationManager;

    PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

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

    @Override
    public void configure(ClientDetailsServiceConfigurer client) throws Exception {
        client.inMemory().withClient("mobile").secret(passwordEncoder.encode("pin")).scopes("READ", "WRITE").authorizedGrantTypes("password", "client_credential");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoint) throws Exception {
        endpoint.authenticationManager(authenticationManager);
    }
}
</code>```

and

```<code>@Configuration
public class UserConfiguration extends GlobalAuthenticationConfigurerAdapter {

    PasswordEncoder passwordEncoder=PasswordEncoderFactories.createDelegatingPasswordEncoder();

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("root").password(passwordEncoder.encode("root")).roles("USER","ADMIN");
    }
}
</code>```

With this configuration the app doesn't work.
When I run the project via maven I see that Spring generate a new "client-id" and "client-secret" instead to use "mobile" and "pin"

```<code>security.oauth2.client.client-id = 27234511-14a5-4b94-9cd3-ffc77c5189f3
security.oauth2.client.client-secret = 5895bf76-6b30-4160-9f13-1cbad7b986e5
</code>```

this is the log

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.0)

2022-02-02 09:55:12.291  INFO 113288 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8282 (http)
2022-02-02 09:55:12.413  INFO 113288 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-02 09:55:12.414  INFO 113288 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.55]
2022-02-02 09:55:12.711  INFO 113288 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-02 09:55:12.712  INFO 113288 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 5978 ms
2022-02-02 09:55:13.407  INFO 113288 --- [           main] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 940524c4-8efa-4d7d-826b-864ff4b48392

2022-02-02 09:55:13.826  INFO 113288 --- [           main] a.OAuth2AuthorizationServerConfiguration : Initialized OAuth2 Client

security.oauth2.client.client-id = 27234511-14a5-4b94-9cd3-ffc77c5189f3
security.oauth2.client.client-secret = 5895bf76-6b30-4160-9f13-1cbad7b986e5

2022-02-02 09:55:15.130  INFO 113288 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Or [Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']] with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@41bfa9e9, org.springframework.security.web.context.SecurityContextPersistenceFilter@13ed066e, org.springframework.security.web.header.HeaderWriterFilter@68ef01a5, org.springframework.security.web.authentication.logout.LogoutFilter@5ae15, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@1bbddada, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@590765c4, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@64b018f3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@68b7d0ef, org.springframework.security.web.session.SessionManagementFilter@7126e26, org.springframework.security.web.access.ExceptionTranslationFilter@4872669f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@59c500f7]
2022-02-02 09:55:15.301  INFO 113288 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8282 (http) with context path ''
</code>```

Why the java class configuration  doesn't work?

Thanks

答:
The solution of the problem is at this link

Spring Boot: Configuration Class is simply ignored and not loaded

My config files were in a different package so I added the

@ComponentScan(basePackages = "my.config.package")

in the main class after

@SpringBootApplication

and it works.

Title: Spring Boot and OAuth2 server

Body:
I'm trying to implement a simple OAuth2 server with Spring Boot.
In the first step I added in the main class the annotation @EnableAuthorizationServer

@SpringBootApplication
@EnableAuthorizationServer
public class PocApplication {

    public static void main(String[] args) {
        SpringApplication.run(PocApplication.class, args);
    }
}

and I use the "application.yml" file to configure all the OAuth2 elements.

server:
  port: 8282
spring:
  security:
    user:
      name: root
      password: root
      roles: ADMIN,USER
security:
  oauth2:
    client:
      client-id: mobile
      client-secret: pin
      access-token-validity-seconds: 3600
      authorized-grant-types: client_credential,password
      scope: READ, WRITE
    authorization:
      check-token-access: permitAll

With this configuration everything works fine.

In the second step I tried to switch the configuration from yml file to java class.

These are the classes that I created

@Configuration
public class AuthServerConfigurations extends WebSecurityConfigurerAdapter implements AuthorizationServerConfigurer {

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    AuthenticationManager authenticationManager;

    PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

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

    @Override
    public void configure(ClientDetailsServiceConfigurer client) throws Exception {
        client.inMemory().withClient("mobile").secret(passwordEncoder.encode("pin")).scopes("READ", "WRITE").authorizedGrantTypes("password", "client_credential");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoint) throws Exception {
        endpoint.authenticationManager(authenticationManager);
    }
}

and

@Configuration
public class UserConfiguration extends GlobalAuthenticationConfigurerAdapter {

    PasswordEncoder passwordEncoder=PasswordEncoderFactories.createDelegatingPasswordEncoder();

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("root").password(passwordEncoder.encode("root")).roles("USER","ADMIN");
    }
}

With this configuration the app doesn't work.
When I run the project via maven I see that Spring generate a new "client-id" and "client-secret" instead to use "mobile" and "pin"

security.oauth2.client.client-id = 27234511-14a5-4b94-9cd3-ffc77c5189f3
security.oauth2.client.client-secret = 5895bf76-6b30-4160-9f13-1cbad7b986e5

this is the log

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.0)

2022-02-02 09:55:12.291  INFO 113288 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8282 (http)
2022-02-02 09:55:12.413  INFO 113288 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-02 09:55:12.414  INFO 113288 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.55]
2022-02-02 09:55:12.711  INFO 113288 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-02 09:55:12.712  INFO 113288 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 5978 ms
2022-02-02 09:55:13.407  INFO 113288 --- [           main] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 940524c4-8efa-4d7d-826b-864ff4b48392

2022-02-02 09:55:13.826  INFO 113288 --- [           main] a.OAuth2AuthorizationServerConfiguration : Initialized OAuth2 Client

security.oauth2.client.client-id = 27234511-14a5-4b94-9cd3-ffc77c5189f3
security.oauth2.client.client-secret = 5895bf76-6b30-4160-9f13-1cbad7b986e5

2022-02-02 09:55:15.130  INFO 113288 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure Or [Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']] with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@41bfa9e9, org.springframework.security.web.context.SecurityContextPersistenceFilter@13ed066e, org.springframework.security.web.header.HeaderWriterFilter@68ef01a5, org.springframework.security.web.authentication.logout.LogoutFilter@5ae15, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@1bbddada, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@590765c4, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@64b018f3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@68b7d0ef, org.springframework.security.web.session.SessionManagementFilter@7126e26, org.springframework.security.web.access.ExceptionTranslationFilter@4872669f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@59c500f7]
2022-02-02 09:55:15.301  INFO 113288 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8282 (http) with context path ''

Why the java class configuration  doesn't work?

Thanks


问:
ESLint not reporting TypeScript compiler type checking errors
Looking for help in getting the type errors, reported by the TypeScript compiler, into the output of ESLint. The library typescript-eslint (https://github.com/typescript-eslint/typescript-eslint/blob/master/docs/getting-started/linting/TYPED_LINTING.md) makes me think that this should be possible.

File structure

```<code>src/
  ... source files
  tsconfig.json
test/
  ... testing files
.eslintrc.js
package.json
tsconfig.json (symlink to src/tsconfig.json)
</code>```

.eslintrc.js

```<code>module.exports = {
  'env': {
    'jest': true,
    'node': true,
  },
  'extends': [
    'airbnb-typescript/base',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
    'plugin:jest/recommended',
  ],
  'parser': '@typescript-eslint/parser',
  'parserOptions': {
    'project': ['./tsconfig.json'],
    'tsconfigRootDir': __dirname,
  },
  'plugins': [
    '@typescript-eslint',
    'jest',
  ],
  'root': true,
};
</code>```

package.json

```<code>{
  "name": "...",
  "version": "...",
  "description": "...",
  "scripts": {},
  "devDependencies": {
    "@types/jest": "^25.1.3",
    "@typescript-eslint/eslint-plugin": "^2.21.0",
    "@typescript-eslint/parser": "^2.21.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb-typescript": "^7.0.0",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jest": "^23.8.1",
    "jest": "^25.1.0",
    "nock": "^12.0.2",
    "ts-jest": "^25.2.1"
  },
  "dependencies": {
    "@types/node": "^13.7.7",
    "aws-sdk": "^2.630.0",
    "jsonschema": "^1.2.5",
    "typescript": "^3.8.3"
  }
}
</code>```

The output of ESLint is empty - no errors - but when running the TypeScript compiler, to build the project, there are many errors reported; for instance:

```<code>src/file.ts:xx:xx - error TS2339: Property 'body' does not exist on type 'object'.
src/file.ts:xx:xx - error TS2314: Generic type 'Promise<T>' requires 1 type argument(s).
src/filets:xx:xx - error TS7006: Parameter 'err' implicitly has an 'any' type.
</code>```

Am I missing something in the configuration or is it improper in some way? Or is this not something that is actually possible?

I'd like to get the errors reporting through ESLint because I have the linting errors showing in my editor as I work on the project. I am using Atom (https://atom.io/) but I would also like this to work for VSCode and possibly VIM as well; team members prefer different editors.

答:
You can use the following to setup reporting TypeScript type-checking errors:

```<code>  "scripts": {
     "lint": "eslint src/**/*.{ts,tsx}",
     "lint:fix": "eslint src/**/*.{ts,tsx} --fix",
     "prettify": "prettier --write src/**/*.{ts,tsx}",
     "type-check": "tsc --noEmit",
   },
  "lint-staged": {
     "*.{ts,tsx}": [
       "eslint",
       "prettier --write",
       "git add"
     ]
   },
</code>```

And finally to run the script to check both linting and type-checking errors, you can use the following command:

```<code>yarn type-check && lint-staged
</code>```

Body:
Looking for help in getting the type errors, reported by the TypeScript compiler, into the output of ESLint. The library typescript-eslint (https://github.com/typescript-eslint/typescript-eslint/blob/master/docs/getting-started/linting/TYPED_LINTING.md) makes me think that this should be possible.

File structure

src/
  ... source files
  tsconfig.json
test/
  ... testing files
.eslintrc.js
package.json
tsconfig.json (symlink to src/tsconfig.json)

.eslintrc.js

module.exports = {
  'env': {
    'jest': true,
    'node': true,
  },
  'extends': [
    'airbnb-typescript/base',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
    'plugin:jest/recommended',
  ],
  'parser': '@typescript-eslint/parser',
  'parserOptions': {
    'project': ['./tsconfig.json'],
    'tsconfigRootDir': __dirname,
  },
  'plugins': [
    '@typescript-eslint',
    'jest',
  ],
  'root': true,
};

package.json

{
  "name": "...",
  "version": "...",
  "description": "...",
  "scripts": {},
  "devDependencies": {
    "@types/jest": "^25.1.3",
    "@typescript-eslint/eslint-plugin": "^2.21.0",
    "@typescript-eslint/parser": "^2.21.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb-typescript": "^7.0.0",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jest": "^23.8.1",
    "jest": "^25.1.0",
    "nock": "^12.0.2",
    "ts-jest": "^25.2.1"
  },
  "dependencies": {
    "@types/node": "^13.7.7",
    "aws-sdk": "^2.630.0",
    "jsonschema": "^1.2.5",
    "typescript": "^3.8.3"
  }
}

The output of ESLint is empty - no errors - but when running the TypeScript compiler, to build the project, there are many errors reported; for instance:

src/file.ts:xx:xx - error TS2339: Property 'body' does not exist on type 'object'.
src/file.ts:xx:xx - error TS2314: Generic type 'Promise<T>' requires 1 type argument(s).
src/filets:xx:xx - error TS7006: Parameter 'err' implicitly has an 'any' type.

Am I missing something in the configuration or is it improper in some way? Or is this not something that is actually possible?

I'd like to get the errors reporting through ESLint because I have the linting errors showing in my editor as I work on the project. I am using Atom (https://atom.io/) but I would also like this to work for VSCode and possibly VIM as well; team members prefer different editors.

Body:
You can use the following to setup reporting TypeScript type-checking errors:

  "scripts": {
     "lint": "eslint src/**/*.{ts,tsx}",
     "lint:fix": "eslint src/**/*.{ts,tsx} --fix",
     "prettify": "prettier --write src/**/*.{ts,tsx}",
     "type-check": "tsc --noEmit",
   },
  "lint-staged": {
     "*.{ts,tsx}": [
       "eslint",
       "prettier --write",
       "git add"
     ]
   },

And finally to run the script to check both linting and type-checking errors, you can use the following command:

yarn type-check && lint-staged


问:
Cannot execute scp with QProcess
I'm trying to get-modidy-send a file from/to a remote host.
It's Windows 10, By the way.

I've reduced code to be easier:

```<code>#include <QCoreApplication>
#include <QProcess>

bool getFile(QStringList &logTextList)
{
    QProcess scp;

    scp.start( "scp", QStringList() );
    if( scp.waitForStarted(1000) )
    {
        if( scp.waitForFinished(10000) == true )
        {
            if( scp.exitCode() == 0 )
            {
                logTextList.append(scp.readAllStandardError());
                return true;
            }
        }
        else
            logTextList.append("Not finished");
    }
    else
        logTextList.append( "Not Started" );
    logTextList.append( scp.readAllStandardError() );
    logTextList.append( scp.readAllStandardOutput() );
    logTextList.append( QString("Exitcode = %1\n").arg(scp.exitCode()) );
    return false;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QStringList logTextList;

    getFile(logTextList);

    return a.exec();
}
</code>```

QProcess never starts with "scp" or even "dir" (remember, it's windows 10 host)
But with "cmd" or "ping" command works.
Also tried to execute "cmd" and write to stdin "scp". But command prompt reports that "scp" is an unkknown command.

[EDIT] Just found that "dir" is not an external executable. So, need to be execute within "cmd.exe". And works.
But "scp" still doesn't.

Any clue?

Thanks in advance.

答:
When you spawn process by name it is searched in all paths in PATH environment variable, if it's not there it wont work.

You can fix it by adding scp path to PATH temporary or permanently before starting your application.

Or you can spawn process using full path:

QString command = "scp";
#ifdef Q_OS_WIN
command = "C:\\Program Files\\Git\\usr\\bin\\scp.exe";
#endif
scp.start(command, {});
```
<p>Or you can spawn scp through shell with modified environment:</p>
```QProcess scp;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QString PATH = env.value("PATH") + ";C:\\msys64\\usr\\bin;C:\\Program Files\\Git\\usr\\bin";
env.insert("PATH", PATH);
scp.setProcessEnvironment(env);
scp.start("cmd",{"/c","scp"});
```

Title: Cannot execute scp with QProcess

Body:
I'm trying to get-modidy-send a file from/to a remote host.
It's Windows 10, By the way.

I've reduced code to be easier:

#include <QCoreApplication>
#include <QProcess>

bool getFile(QStringList &logTextList)
{
    QProcess scp;

    scp.start( "scp", QStringList() );
    if( scp.waitForStarted(1000) )
    {
        if( scp.waitForFinished(10000) == true )
        {
            if( scp.exitCode() == 0 )
            {
                logTextList.append(scp.readAllStandardError());
                return true;
            }
        }
        else
            logTextList.append("Not finished");
    }
    else
        logTextList.append( "Not Started" );
    logTextList.append( scp.readAllStandardError() );
    logTextList.append( scp.readAllStandardOutput() );
    logTextList.append( QString("Exitcode = %1\n").arg(scp.exitCode()) );
    return false;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QStringList logTextList;

    getFile(logTextList);

    return a.exec();
}

QProcess never starts with "scp" or even "dir" (remember, it's windows 10 host)
But with "cmd" or "ping" command works.
Also tried to execute "cmd" and write to stdin "scp". But command prompt reports that "scp" is an unkknown command.

[EDIT] Just found that "dir" is not an external executable. So, need to be execute within "cmd.exe". And works.
But "scp" still doesn't.

Any clue?

Thanks in advance.

Body:
When you spawn process by name it is searched in all paths in PATH environment variable, if it's not there it wont work.

You can fix it by adding scp path to PATH temporary or permanently before starting your application.

Or you can spawn process using full path:

QString command = "scp";
#ifdef Q_OS_WIN
command = "C:\\Program Files\\Git\\usr\\bin\\scp.exe";
#endif
scp.start(command, {});

Or you can spawn scp through shell with modified environment:

QProcess scp;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QString PATH = env.value("PATH") + ";C:\\msys64\\usr\\bin;C:\\Program Files\\Git\\usr\\bin";
env.insert("PATH", PATH);
scp.setProcessEnvironment(env);
scp.start("cmd",{"/c","scp"});


问:
List for all disable triggers
I need to make a list of all triggers which aren't running.

```<code>declare @Trigger nvarchar(150)
select @Trigger = t1.name from  sys.triggers as t1 WHERE t1.is_disabled = 1
declare @disable int
select @disable =t1.is_disabled FROM sys.triggers t1 WHERE t1.is_disabled = 0
While @disable <= 1
BEGIN
    Print 'Trigger ' + @Trigger +  ' is disable!'
    set @disable = @disable + 1
END
</code>```

As a result I have only one trigger, but there are another 10 which are disabled.

Any ideas?

答:
```<code>select *
from sys.triggers trg
where is_disabled = 1
</code>```

Title: List for all disable triggers

Body:
I need to make a list of all triggers which aren't running.

declare @Trigger nvarchar(150)
select @Trigger = t1.name from  sys.triggers as t1 WHERE t1.is_disabled = 1
declare @disable int
select @disable =t1.is_disabled FROM sys.triggers t1 WHERE t1.is_disabled = 0
While @disable <= 1
BEGIN
    Print 'Trigger ' + @Trigger +  ' is disable!'
    set @disable = @disable + 1
END

As a result I have only one trigger, but there are another 10 which are disabled.

Any ideas?