问:
How to access the state of a component at a superior level without using useContext?
let me explain my question.
I would like to create expanding flex cards, here is the exemple on codepen : https://codepen.io/z-/pen/OBPJKK

and here is my code for each button :
basically I have a component which is called HomeButtons that generates every flex cards. Inside this component I have a smaller component called readMore. In this component I have a useState that allows me to toggle individually each button to add or retreive an active class. If the active class is present, that means that the selected button must expand and the other ones must shrink.

What I would like to do is to access the readMore state ouside of the readMore subcomponent. That way I could write a function to remove the active class from a card if the user clicks on another card like so :

```<code>function setToUnactive() {
if (readMore(true)) {
readMore(false)}
}

</code>```

My question is how can I get the state of readMore outside of the readMore subcomponent ? Do I need to use useContext ? Because that seems very simple to do but I tried a lot of things and nothing works. Can I pass the state readMore as a prop of the component ReadMore ? Thank you !

```<code>import React, { useState } from 'react';
import '../style/catalogue.scss';
import collectionsItems from '../Components/collectionsItemsData';
import { Link } from "react-router-dom";

const HomeButtons = ({}) => {

    function ReadMore() {
        const [readMore, setReadMore] = useState(false)
        function toggleSetReadMore() {
            setReadMore(!readMore)
        }
        return (
            <p className='showmore' onClick={toggleSetReadMore} className={readMore ? "collection-item active" : "collection-item"}>TOGGLE BUTTON</p>
        )
    }

    return <div>
        {collectionsItems.map((collectionItem) => {
            const { id, category, img } = collectionItem;
            return < article key={id} >
                <img className="item-img" src={img} alt=''/>
                <ReadMore />
                <Link to={`/${category}`} className="item-title">{category}</Link>
            </article>
        })}
    </div>
}

export default HomeButtons;
</code>```

答:
First of all you need extract ReadMore component from function outside!
And for your problem you can lift state up(https://reactjs.org/docs/lifting-state-up.html). And since at the same time only one item can be opened you can do something like this:</p>
```<code>function ReadMore({ isOpened, setOpened }) {
  return (
    <p
      onClick={setOpened}
      className={isOpened ? "collection-item active" : "collection-item"}
    >
      TOGGLE BUTTON
    </p>
  );
}

const HomeButtons = () => {
  const [openedItemId, setOpenedItemId] = useState(null);

  return (
    <div>
      {collectionsItems.map((collectionItem) => {
        const { id, category, img } = collectionItem;
        return (
          <article key={id}>
            <img className="item-img" src={img} alt="" />
            <ReadMore
              isOpened={openedItemId === id}
              setOpened={() => setOpenedItemId(id)}
            />
            <Link to={`/${category}`} className="item-title">
              {category}
            </Link>
          </article>
        );
      })}
    </div>
  );
};

</code>```

Body:
let me explain my question.
I would like to create expanding flex cards, here is the exemple on codepen : https://codepen.io/z-/pen/OBPJKK

and here is my code for each button :
basically I have a component which is called HomeButtons that generates every flex cards. Inside this component I have a smaller component called readMore. In this component I have a useState that allows me to toggle individually each button to add or retreive an active class. If the active class is present, that means that the selected button must expand and the other ones must shrink.

What I would like to do is to access the readMore state ouside of the readMore subcomponent. That way I could write a function to remove the active class from a card if the user clicks on another card like so :

function setToUnactive() {
if (readMore(true)) {
readMore(false)}
}

My question is how can I get the state of readMore outside of the readMore subcomponent ? Do I need to use useContext ? Because that seems very simple to do but I tried a lot of things and nothing works. Can I pass the state readMore as a prop of the component ReadMore ? Thank you !

import React, { useState } from 'react';
import '../style/catalogue.scss';
import collectionsItems from '../Components/collectionsItemsData';
import { Link } from "react-router-dom";

const HomeButtons = ({}) => {

    function ReadMore() {
        const [readMore, setReadMore] = useState(false)
        function toggleSetReadMore() {
            setReadMore(!readMore)
        }
        return (

TOGGLE BUTTON

        )
    }

    return

        {collectionsItems.map((collectionItem) => {
            const { id, category, img } = collectionItem;
            return

                <ReadMore />
                <Link to={`/${category}`} className="item-title">{category}</Link>

        })}

}

export default HomeButtons;

Body:
First of all you need extract ReadMore component from function outside!
And for your problem you can lift state up(https://reactjs.org/docs/lifting-state-up.html). And since at the same time only one item can be opened you can do something like this:

function ReadMore({ isOpened, setOpened }) {
  return (
    <p
      onClick={setOpened}
      className={isOpened ? "collection-item active" : "collection-item"}
    >
      TOGGLE BUTTON
    </p>
  );
}

const HomeButtons = () => {
  const [openedItemId, setOpenedItemId] = useState(null);

  return (
    <div>
      {collectionsItems.map((collectionItem) => {
        const { id, category, img } = collectionItem;
        return (
          <article key={id}>
            <img className="item-img" src={img} alt="" />
            <ReadMore
              isOpened={openedItemId === id}
              setOpened={() => setOpenedItemId(id)}
            />
            <Link to={`/${category}`} className="item-title">
              {category}
            </Link>
          </article>
        );
      })}
    </div>
  );
};


来源: stackexchange

问:
Remove strings begining with 'AUTO_INCREMENT=' in 2 files
I am trying to create a ruby script that loads 2 .sql files and removes all strings that begin with 'AUTO_INCREMENT='
There are multiple occurrences of this in my .sql files and all I want is them to be removed from both files.
Thanks for any help or input as I am new to ruby and decided to give it a try.</p>

答:
Given the right regexp (the one below might not be the most correct given the syntax), and the answer given there to a similar question, it is rather straightforward to put a script together:</p>

```<code>file_names = ['file1.sql', 'file2.sql']

file_names.each do |file_name|
  text = File.read(file_name)
  File.open(file_name, 'wb') do
    |file|
    file.write(text.gsub(/\s*AUTO_INCREMENT\s*(\=\s*[0-9]+)?/, ""))
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given the right regexp (the one below might not be the most correct given the syntax), and the answer given there to a similar question, it is rather straightforward to put a script together:

file_names = ['file1.sql', 'file2.sql']

file_names.each do |file_name|
  text = File.read(file_name)
  File.open(file_name, 'wb') do
    |file|
    file.write(text.gsub(/\s*AUTO_INCREMENT\s*(\=\s*[0-9]+)?/, ""))
  end
end


问:
Failed to install Vuex in Vue3
I want to install Vuex but I get an error.</p>
```<code>// error
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: vuejs-v-3@0.1.0
npm ERR! Found: vue@3.1.2
npm ERR! node_modules/vue
npm ERR!   vue@"^3.1.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer vue@"^2.0.0" from vuex@3.6.2
npm ERR! node_modules/vuex
npm ERR!   vuex@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/hap/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/hap/.npm/_logs/2021-06-24T06_46_36_463Z-debug.log
</code>```
```<code>// package.json

    {
  "name": "vuejs-v-3",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@apollo/client": "^3.3.20",
    "axios": "^0.21.1",
    "bootstrap": "^5.0.2",
    "core-js": "^3.6.5",
    "graphql": "^15.5.1",
    "vue": "^3.1.2",
    "vue-router": "^4.0.10"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

</code>```

答:
As @Seegy said,

Vue 3 uses Vuex 4

Vue 2 uses Vuex 3

As of Feb 2022,

If you are using Vue 2, use the following to install Vuex 3

npm install vuex@3.4.0 --save

If you are using Vue 3, use the following to install Vuex 4

npm install vuex --save or npm install vuex@next --save

ContentLicense: CC BY-SA 4.0

Title: Failed to install Vuex in Vue3

Body:
I want to install Vuex but I get an error.

// error
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: vuejs-v-3@0.1.0
npm ERR! Found: vue@3.1.2
npm ERR! node_modules/vue
npm ERR!   vue@"^3.1.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer vue@"^2.0.0" from vuex@3.6.2
npm ERR! node_modules/vuex
npm ERR!   vuex@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/hap/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/hap/.npm/_logs/2021-06-24T06_46_36_463Z-debug.log

// package.json

    {
  "name": "vuejs-v-3",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@apollo/client": "^3.3.20",
    "axios": "^0.21.1",
    "bootstrap": "^5.0.2",
    "core-js": "^3.6.5",
    "graphql": "^15.5.1",
    "vue": "^3.1.2",
    "vue-router": "^4.0.10"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}


问:
Plot Bar and Line Charts from Pivot Table
I'm trying to create a plot with bar and line charts together where each chart corresponds to a column from my pivot table.

I've seen several questions with the same problem as me but non of them helped me. I want my first column of the dataset as a bar chart and the second as a line chart, with a different scale.

Here's my code:

```<code>#creatin my pivot table
gb_treino3=treino.pivot_table(index="ANO_MES", columns="TARGET", values='ID_PVC', aggfunc='count', margins=True)
gb_treino3['1(%)'] = gb_treino3[1] / gb_treino3['All'] * 100
gb_treino3.drop([0,'All'], inplace=True, axis=1)
gb_treino3.drop('All', inplace=True, axis=0)

#plotting
fig,ax=plt.subplots(figsize=(15,10))
#plt.rcParams["figure.figsize"]=[7.50,3.50]
plt.rcParams["figure.autolayout"]= True

ax1=gb_treino3.iloc[:,0].plot(kind='bar', color='orange')
gb_treino3.iloc[:,1].plot(secondary_y=TRUE,xlim=ax1.get_xlim())
plt.show()
</code>```

Although the bar chart appears, the line chart doesn't. Can anyone help?

答:
Here is an example to demonstrate one way to do it:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(
    {
        "year": [2015, 2016, 2017, 2018, 2019, 2020, 2021],
        "col1": [20, 60, 10, 40, 20, 25, 10],
        "col2": [80, 30, 15, 30, 40, 50, 20],
    }
)

# plt.figure()

ax = df[['year', 'col1']].plot(x='year', linestyle='-', marker='o', use_index=False)
df[['year', 'col2']].plot(x='year', kind='bar', ax=ax, use_index=True)

plt.show()
```

Which outputs:

Body:
I'm trying to create a plot with bar and line charts together where each chart corresponds to a column from my pivot table.

I've seen several questions with the same problem as me but non of them helped me. I want my first column of the dataset as a bar chart and the second as a line chart, with a different scale.

Here's my code:

#creatin my pivot table
gb_treino3=treino.pivot_table(index="ANO_MES", columns="TARGET", values='ID_PVC', aggfunc='count', margins=True)
gb_treino3['1(%)'] = gb_treino3[1] / gb_treino3['All'] * 100
gb_treino3.drop([0,'All'], inplace=True, axis=1)
gb_treino3.drop('All', inplace=True, axis=0)

#plotting
fig,ax=plt.subplots(figsize=(15,10))
#plt.rcParams["figure.figsize"]=[7.50,3.50]
plt.rcParams["figure.autolayout"]= True

ax1=gb_treino3.iloc[:,0].plot(kind='bar', color='orange')
gb_treino3.iloc[:,1].plot(secondary_y=TRUE,xlim=ax1.get_xlim())
plt.show()

Although the bar chart appears, the line chart doesn't. Can anyone help?

Body:
Here is an example to demonstrate one way to do it:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(
    {
        "year": [2015, 2016, 2017, 2018, 2019, 2020, 2021],
        "col1": [20, 60, 10, 40, 20, 25, 10],
        "col2": [80, 30, 15, 30, 40, 50, 20],
    }
)

# plt.figure()

ax = df[['year', 'col1']].plot(x='year', linestyle='-', marker='o', use_index=False)
df[['year', 'col2']].plot(x='year', kind='bar', ax=ax, use_index=True)

plt.show()

Which outputs:


问:
How To Count Number of Documents in a Collection in Firebase Firestore With a WHERE query in react.js
I want to get the total number of users in my Firebase Firestore collection. I can get it easily by writing this code:

```<code>const [totalUsers, setTotalUsers] = useState(0);
  const [newUsers, setNewUsers] = useState(0);

  useEffect(() => {
    firebase.firestore().collection("Users").get().then((querySnapshot) => {
      const TotalUsers = querySnapshot.size
        setTotalUsers(TotalUsers)

    })
  }, []);
</code>```

But what i want is to get the total number of users with a condition such as the following:

```<code>   // this is not working, its not showing any results back.
  useEffect(() => {
    firebase.firestore().collection("Users").where("usersID","!=","101010").get().then((querySnapshot) => {

      querySnapshot.forEach((doc) => {
        const TotalUsers = doc.size
        setTotalUsers(TotalUsers)
      })

    })
  }, []);
</code>```

But the above code is not working and isn't returning any results.

How can I get the total number of documents in a collection in firebase firestore with a where query?

答:
You've moved the count operation into a loop, which is not needed.

Instead, just add the condition to your read operation and keep the rest the same:

```<code>useEffect(() => {
  firebase.firestore().collection("Users").where("usersID","!=","101010").get().then((querySnapshot) => {
    const TotalUsers = querySnapshot.size
    setTotalUsers(TotalUsers)
  })
}, []);
</code>```

Note that reading all user documents just to determine their count is an expensive way to do this, so I recommend reading the documentation on aggregation operators, and Dan's answer on counting documents in Cloud Firestore collection count

Body:
I want to get the total number of users in my Firebase Firestore collection. I can get it easily by writing this code:

const [totalUsers, setTotalUsers] = useState(0);
  const [newUsers, setNewUsers] = useState(0);

  useEffect(() => {
    firebase.firestore().collection("Users").get().then((querySnapshot) => {
      const TotalUsers = querySnapshot.size
        setTotalUsers(TotalUsers)

    })
  }, []);

But what i want is to get the total number of users with a condition such as the following:

   // this is not working, its not showing any results back.
  useEffect(() => {
    firebase.firestore().collection("Users").where("usersID","!=","101010").get().then((querySnapshot) => {

      querySnapshot.forEach((doc) => {
        const TotalUsers = doc.size
        setTotalUsers(TotalUsers)
      })

    })
  }, []);

But the above code is not working and isn't returning any results.

How can I get the total number of documents in a collection in firebase firestore with a where query?

Body:
You've moved the count operation into a loop, which is not needed.

Instead, just add the condition to your read operation and keep the rest the same:

useEffect(() => {
  firebase.firestore().collection("Users").where("usersID","!=","101010").get().then((querySnapshot) => {
    const TotalUsers = querySnapshot.size
    setTotalUsers(TotalUsers)
  })
}, []);

Note that reading all user documents just to determine their count is an expensive way to do this, so I recommend reading the documentation on aggregation operators, and Dan's answer on counting documents in Cloud Firestore collection count


问:
Linking to different areas on a page
This may seem like a stupid question, but:

So what i would like to do is set up a menu section so that when the user clicked on the title of the section it would send them to that particular spot on the page with out having to scoll down. I am not entirely sure how this would work or how complicated it is to achieve.

So bacially i would have

Menu

item one (be a link)

item two (be a link)

etc (be a link)

then further down the page

item one (when item one in menu is clicked page comes to here)

"details about it here"

item two (when item two in menu is clicked page comes to here)

"details here"

How exactly would i go about doing this?

Any help or suggestions are greatly appreciated. Thanks.

答:
You can use a hash ('#') in front of a link to specify that it points to an ID or anchor within the same page.

Example:

```<code><a href="#item1">Item 1</a>
</code>```

will redirect to the following element on the same page:

```<code><div id="item1">Item one details</div>
</code>```

It will also point to the following anchor, but it is usually preferable to point to an element with an ID to avoid unnecessary markup:

```<code><a name="item1">Item one details</a>
</code>```

EDIT
For the reasons described in HTML Anchors with 'name' or 'id'?, anchors should not be used in this manner in HTML5 because the name attribute no longer exists (according to the current specification draft).

Title: Linking to different areas on a page

Body:
You can use a hash ('#') in front of a link to specify that it points to an ID or anchor within the same page.

Example:

<a href="#item1">Item 1</a>

will redirect to the following element on the same page:

<div id="item1">Item one details</div>

It will also point to the following anchor, but it is usually preferable to point to an element with an ID to avoid unnecessary markup:

<a name="item1">Item one details</a>

EDIT
For the reasons described in HTML Anchors with 'name' or 'id'?, anchors should not be used in this manner in HTML5 because the name attribute no longer exists (according to the current specification draft).


问:
How does dotenv cli with "--" (double-dash) running commands?
Im my project i am trying to use dotenv-cli with pnpm. I am using PowerShell 7.2.1 on windows. I have monorepo with package api with script dev in package.json.
First what I tried was:

dotenv -e .\.env -- pnpm dev --filter api
```
<p>And it did not work:</p>
``` ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL  not found: dev
```
<p>But when I tried:</p>
<pre class="lang-sh prettyprint-override"><code>dotenv -e .\.env -- pnpm -- dev --filter api
</code>```

It worked well.

As I had read -- signifies the end of command options, after which only positional arguments are accepted. So why do I need to use it twice for my command to work? Why is it working like that?

答:
The problem is that when you call from PowerShell (unlike from cmd.exe), the command name dotenv  resolves to a PowerShell script, namely dotenv.ps1, as you report.

When PowerShell calls a PowerShell-native command - including .ps1 files -  its own parameter binder interprets the (first) -- argument and removes it; that is, the target command never sees it.
(The semantics of -- is analogous to that of Unix utilities: -- tells the parameter binder to treat subsequent arguments as positional ones, even if they look like parameter (option) names, such as -foo.)

Thus, unfortunately, you need to specify -- twice in order to pass a single -- instance through to the .ps1 script itself:

# The first '--' is removed by PowerShell's parameter binder.
# The second one is then received as an actual, positional argument by
# dotenv.ps1
dotenv -e .\.env -- -- pnpm dev --filter api
```
<p>Alternatively, assuming that <code>dotenv.cmd</code>, i.e. a <em>batch file</em> version of the CLI exists too (and is also in a directory listed in <code>$env:PATH</code>), you can bypass this problem by calling it explicitly, instead of the <code>.ps1</code>; <strong>when calling <em>external programs</em> (including scripts interpreted by other shells / scripting engines, such as <code>cmd.exe</code>), PowerShell does <em>not</em> remove <code>--</code></strong>:</p>
<pre class="lang-sh prettyprint-override"><code># Calling the batch-file form of the command doesn't require
# passing '--' twice.
dotenv.cmd -e .\.env -- pnpm dev --filter api
</code>```

Caveat: While it will typically not matter, the way a batch file parses its arguments differs from how PowerShell does it for its native commands.

Body:
Im my project i am trying to use dotenv-cli with pnpm. I am using PowerShell 7.2.1 on windows. I have monorepo with package api with script dev in package.json.
First what I tried was:

dotenv -e .\.env -- pnpm dev --filter api

And it did not work:

 ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL  not found: dev

But when I tried:

dotenv -e .\.env -- pnpm -- dev --filter api

It worked well.

As I had read -- signifies the end of command options, after which only positional arguments are accepted. So why do I need to use it twice for my command to work? Why is it working like that?

Body:
The problem is that when you call from PowerShell (unlike from cmd.exe), the command name dotenv  resolves to a PowerShell script, namely dotenv.ps1, as you report.

When PowerShell calls a PowerShell-native command - including .ps1 files -  its own parameter binder interprets the (first) -- argument and removes it; that is, the target command never sees it.
(The semantics of -- is analogous to that of Unix utilities: -- tells the parameter binder to treat subsequent arguments as positional ones, even if they look like parameter (option) names, such as -foo.)

Thus, unfortunately, you need to specify -- twice in order to pass a single -- instance through to the .ps1 script itself:

# The first '--' is removed by PowerShell's parameter binder.
# The second one is then received as an actual, positional argument by
# dotenv.ps1
dotenv -e .\.env -- -- pnpm dev --filter api

Alternatively, assuming that dotenv.cmd, i.e. a batch file version of the CLI exists too (and is also in a directory listed in $env:PATH), you can bypass this problem by calling it explicitly, instead of the .ps1; when calling external programs (including scripts interpreted by other shells / scripting engines, such as cmd.exe), PowerShell does not remove --:

# Calling the batch-file form of the command doesn't require
# passing '--' twice.
dotenv.cmd -e .\.env -- pnpm dev --filter api

Caveat: While it will typically not matter, the way a batch file parses its arguments differs from how PowerShell does it for its native commands.


问:
Caused by: java.lang.IllegalStateException: Provider ID must be specified for client registration 'instagram'
How to create Oauth2 registration for instagramm in spring. I try to do it, but I got error, I did oauth2 registration for Facebook and google, but instagram it is not working and I can't find any tutorials. This is my application.yaml:

```<code> security:
    oauth2:
      client:
        registration:
          instagram:
            client-id: 6833951273265217
            client-secret: 398ec124b13c38ea175ded5badb117a2
            redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
            scope:
              - email
              - public_profile
</code>```

When app start I get this error:

```<code>Caused by: java.lang.IllegalStateException: Provider ID must be specified for client registration 'instagram'
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getBuilder(OAuth2ClientPropertiesRegistrationAdapter.java:95) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getClientRegistration(OAuth2ClientPropertiesRegistrationAdapter.java:61) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.lambda$getClientRegistrations$0(OAuth2ClientPropertiesRegistrationAdapter.java:53) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at java.base/java.util.HashMap.forEach(HashMap.java:1336) ~[na:na]
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(OAuth2ClientPropertiesRegistrationAdapter.java:52) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientRegistrationRepositoryConfiguration.clientRegistrationRepository(OAuth2ClientRegistrationRepositoryConfiguration.java:49) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.5.jar:5.3.5]
    ... 124 common frames omitted
</code>```

答:
Instagram is not the common OAuth2 provider that is supported by spring-security out of the box (see this).So you have to configure its configuration by yourself :

 security:
    oauth2:
      client:
        registration:
          instagram:
            client-id: 6833951273265217
            client-secret: 398ec124b13c38ea175ded5badb117a2
            redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
            scope:
              - email
              - public_profile
        provider:
          instagram:
            authorization-uri: https://api.instagram.com/oauth/authorize
            token-uri: https://api.instagram.com/oauth/access_token
```

Body:
How to create Oauth2 registration for instagramm in spring. I try to do it, but I got error, I did oauth2 registration for Facebook and google, but instagram it is not working and I can't find any tutorials. This is my application.yaml:

 security:
    oauth2:
      client:
        registration:
          instagram:
            client-id: 6833951273265217
            client-secret: 398ec124b13c38ea175ded5badb117a2
            redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
            scope:
              - email
              - public_profile

When app start I get this error:

Caused by: java.lang.IllegalStateException: Provider ID must be specified for client registration 'instagram'
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getBuilder(OAuth2ClientPropertiesRegistrationAdapter.java:95) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getClientRegistration(OAuth2ClientPropertiesRegistrationAdapter.java:61) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.lambda$getClientRegistrations$0(OAuth2ClientPropertiesRegistrationAdapter.java:53) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at java.base/java.util.HashMap.forEach(HashMap.java:1336) ~[na:na]
    at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(OAuth2ClientPropertiesRegistrationAdapter.java:52) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientRegistrationRepositoryConfiguration.clientRegistrationRepository(OAuth2ClientRegistrationRepositoryConfiguration.java:49) ~[spring-boot-autoconfigure-2.4.4.jar:2.4.4]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.5.jar:5.3.5]
    ... 124 common frames omitted


问:
Error creating Docker container for a microservice app in Springboot in Ubuntu
I am trying to create a Docker container for a micro-service in SpringBoot Java in Ubuntu 21.10, but when I try to build the container I get this error, maybe it is a common error, but so far I can't solve it, I have checked some posts on Internet but had no luck finding a similar solution. Please I would really appreciate the help! Thank you in advance

This is my Dockerfile:

```<code>FROM ubuntu
RUN yum install -y java
VOLUME /tmp
ADD target/microservice-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENTRYPOINT ["java", "-Djava.security.egd-file:/dev/./urandom","-jar","/app.jar"]
</code>```

This is the error I get:

```<code> docker build -t spring_boot_docker .

 Sending build context to Docker daemon  17.72MB
 Step 1/6 : FROM ubuntu
 ---> 54c9d81cbb44
 Step 2/6 : RUN yum install -y java
 ---> Running in a2793e79925b
 /bin/sh: 1: yum: not found
 The command '/bin/sh -c yum install -y java' returned a non-zero code: 127
</code>```

答:
In ubuntu you can try installing with apt-get:</p>
```<code>RUN apt-get update && \
    apt-get install -y openjdk-8-jdk
</code>```

Body:
I am trying to create a Docker container for a micro-service in SpringBoot Java in Ubuntu 21.10, but when I try to build the container I get this error, maybe it is a common error, but so far I can't solve it, I have checked some posts on Internet but had no luck finding a similar solution. Please I would really appreciate the help! Thank you in advance

This is my Dockerfile:

FROM ubuntu
RUN yum install -y java
VOLUME /tmp
ADD target/microservice-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENTRYPOINT ["java", "-Djava.security.egd-file:/dev/./urandom","-jar","/app.jar"]

This is the error I get:

 docker build -t spring_boot_docker .

 Sending build context to Docker daemon  17.72MB
 Step 1/6 : FROM ubuntu
 ---> 54c9d81cbb44
 Step 2/6 : RUN yum install -y java
 ---> Running in a2793e79925b
 /bin/sh: 1: yum: not found
 The command '/bin/sh -c yum install -y java' returned a non-zero code: 127

Body:
In ubuntu you can try installing with apt-get:

RUN apt-get update && \
    apt-get install -y openjdk-8-jdk


问:
std::basic_string<T>::size_type causes compile error in C++20 mode
Here is a simple code that MSVC 2022 compiles in C++17 mode, but fails in C++20 mode:

```<code>template <typename T>
void foo()
{
    std::basic_string<T>::size_type bar_size; //This fails to compile in C++20
}
</code>```

The error being reported in C++20 mode does not help explain the reason: error C3878: syntax error: unexpected token 'identifier' following 'expression'

Interestingly, it only happens inside templated functions, this counterexample compiles fine in C++20 mode (as well as in C++17):

```<code>void baz()
{
    std::basic_string<char>::size_type bar_size;
}
</code>```

The only way I can fix the problem so far is to use auto instead of explicit data type, for example like so:

```<code>template <typename T>
void foo()
{
    std::basic_string<T> bar;
    auto bar_size = bar.size();
}
</code>```

But I really want to learn what has changed in C++20 compared to C++17 that causes this syntax to be invalid instead of just mindlessly applying a workaround patch.

答:
Use

```<code>typename std::basic_string<T>::size_type bar_size;
</code>```

The name size_type is a dependent name.

Body:
Here is a simple code that MSVC 2022 compiles in C++17 mode, but fails in C++20 mode:

template <typename T>
void foo()
{
    std::basic_string<T>::size_type bar_size; //This fails to compile in C++20
}

The error being reported in C++20 mode does not help explain the reason: error C3878: syntax error: unexpected token 'identifier' following 'expression'

Interestingly, it only happens inside templated functions, this counterexample compiles fine in C++20 mode (as well as in C++17):

void baz()
{
    std::basic_string<char>::size_type bar_size;
}

The only way I can fix the problem so far is to use auto instead of explicit data type, for example like so:

template <typename T>
void foo()
{
    std::basic_string<T> bar;
    auto bar_size = bar.size();
}

But I really want to learn what has changed in C++20 compared to C++17 that causes this syntax to be invalid instead of just mindlessly applying a workaround patch.

Body:
Use

typename std::basic_string<T>::size_type bar_size;

The name size_type is a dependent name.


问:
object data editting form
I'm making django app which allow me to study. It has multiple tests with multiple question each. Every question has one correct answer. I'm trying to make form which allow me to edit answer If I made mistake in passing correct answer during making question.

That's what I have already made:

```<code>models.py

class Question(models.Model):

    text = models.CharField(max_length=200, null=True)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add = True)

    def get_answer(self):
        return self.answer_set.all()

    def __str__(self):
        return self.text

class Answer(models.Model):
    text = models.CharField(max_length=200)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent')
    def __str__(self):
         return self.text
</code>```
```<code>forms.py

class AnswerEditForm(ModelForm):
    class Meta:
        model = Answer
        exclude = ('question',)

</code>```
```<code>views.py

def UpdateAnswerView(request, pk):
    form = AnswerEditForm()

    if request.method == 'POST':
        form = AnswerEditForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.question = Question.objects.get(id=pk)

            obj.save()
            return redirect('home')

    context = {'form':form}
    return render(request, 'exam/update_answer.html', context)
</code>```
```<code>urls.py
urlpatterns = [
    ~some other urls~
    path('answer/edit/<int:pk>/', views.UpdateAnswerView, name='update-answer'),

]
</code>```

while I'm trying to edit answer i'm getting Question matching query does not exist. error.
Where did i make mistake ?

答: You should confirm that pk is actually getting passed to UpdateAnswerView.  Also confirm that you're actually passing a Question ID and not an Answer ID.

Title: object data editting form

Body:
I'm making django app which allow me to study. It has multiple tests with multiple question each. Every question has one correct answer. I'm trying to make form which allow me to edit answer If I made mistake in passing correct answer during making question.

That's what I have already made:

models.py

class Question(models.Model):

    text = models.CharField(max_length=200, null=True)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add = True)

    def get_answer(self):
        return self.answer_set.all()

    def __str__(self):
        return self.text

class Answer(models.Model):
    text = models.CharField(max_length=200)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent')
    def __str__(self):
         return self.text

forms.py

class AnswerEditForm(ModelForm):
    class Meta:
        model = Answer
        exclude = ('question',)

views.py

def UpdateAnswerView(request, pk):
    form = AnswerEditForm()

    if request.method == 'POST':
        form = AnswerEditForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.question = Question.objects.get(id=pk)

            obj.save()
            return redirect('home')

    context = {'form':form}
    return render(request, 'exam/update_answer.html', context)

urls.py
urlpatterns = [
    ~some other urls~
    path('answer/edit/<int:pk>/', views.UpdateAnswerView, name='update-answer'),

]

while I'm trying to edit answer i'm getting Question matching query does not exist. error.
Where did i make mistake ?


问:
Why are anonymous types in .NET implemented as reference type?
Because an anonymous type is readonly anyway, is would be more efficient if they implemented them as structs so that linq queries doesn't need to create tons of temporary objects:

```<code>// This doesn't make any sense, it is just for demonstration
var result = thingies
.Select(x=> new {A = 1, B = 2, C = 3});
</code>```

Btw. I got this idea, when reading this

EDIT:

The greatest thing would be if the compiler would, depending on the size and usage of the variable (must if be passed to lots of methods), decide whether to make if a value type or reference type.

But could the following sentence which I found in the msdn cause problems then:

If two or more anonymous types in the same assembly have the same
  number and type of properties, in the same order, the compiler treats
  them as the same type.

Since an anonymous object (with its associated type) cannot leave the method which it is defined in we have no problems here, do we?

答:
If anonymous types were value types I'm sure I could make some benchmarks that showed how horrendous all the copying was and how they should be reference types so that they don't need to be copied everywhere.  There are benefits and tradeoffs to both approaches and the language designers chose to use reference types; I would suspect because reference types are more common, more easily understood, and work with more APIs than value types.

Utmost speed isn't the point of anonymous types though.  They are built for the 90% of developers doing reasonable sized LINQ queries who need an intermediate type for storing results.  For the 10% that require millions of objects I would suggest they create a concrete type and invest in some optimizing time.

Body:
Because an anonymous type is readonly anyway, is would be more efficient if they implemented them as structs so that linq queries doesn't need to create tons of temporary objects:

// This doesn't make any sense, it is just for demonstration
var result = thingies
.Select(x=> new {A = 1, B = 2, C = 3});

Btw. I got this idea, when reading this

EDIT:

The greatest thing would be if the compiler would, depending on the size and usage of the variable (must if be passed to lots of methods), decide whether to make if a value type or reference type.

But could the following sentence which I found in the msdn cause problems then:

If two or more anonymous types in the same assembly have the same
  number and type of properties, in the same order, the compiler treats
  them as the same type.

Since an anonymous object (with its associated type) cannot leave the method which it is defined in we have no problems here, do we?


问:
SPFX in Visual Studio
i am wondering if anyone is successfully using SPFX in Visual Studio?

SPFX as it is is a nice idea, compared to how SharePoint development took place in the pre-2016 and SPO time.
But it comes with this downside: Visual Studio Code.
I see that Microsoft maybe plans to appeal to the more "hacky" Javascript volks and tied the SPFX development to VS Code, but VS Code is far from where Visual Studio is. Let alone refactoring of class names and files. There is that https://github.com/SharePoint/sp-dev-fx-vs-extension Repo, but it seems to not get much time and love.

Is there any other way to develop SPFX in the grown-up Visual Studio?

答:
I tried creating a SPFx project once using VS2019 and community project template for SPFX. New Project hung VS forever.

VS Code is best for SPFx because it's lightweight, fast and has tons of extensions.

Title: SPFX in Visual Studio


问:
Why is String.prototype.substr() deprecated?
It is mentioned on the ECMAScript standard here that :

... These features are not considered part of the core ECMAScript
language. Programmers should not use or assume the existence of these
features and behaviours when writing new ECMAScript code. ECMAScript
implementations are discouraged from implementing these features
unless the implementation is part of a web browser or is required to
run the same legacy ECMAScript code that web browsers encounter.

There is also a red warning on MDN : String.prototype.substr() MDN doc

Does anyone know why (ECMAScript standard say that) programmers should not use or assume the existence of String.prototype.substr ?

答:
I've added this declaration as an ambient declaration in a top-level ambient.d.ts file:

```<code>interface String {
  /**
   * Gets a substring beginning at the specified location and having the specified length.
   * (deprecation removed)
   * @param from The starting position of the desired substring. The index of the first character in the string is zero.
   * @param length The number of characters to include in the returned substring.
   */
  substr(from: number, length?: number): string;
}
</code>```

I find substr very useful. It's often a lot more concise to specify how long you want a string to be rather than the end index of the string. If substr really ever is removed from browser or Node.js JavaScript support, I suspect many of us will simply monkey-patch substr back into existence anyway.

Body:
I've added this declaration as an ambient declaration in a top-level ambient.d.ts file:

interface String {
  /**
   * Gets a substring beginning at the specified location and having the specified length.
   * (deprecation removed)
   * @param from The starting position of the desired substring. The index of the first character in the string is zero.
   * @param length The number of characters to include in the returned substring.
   */
  substr(from: number, length?: number): string;
}

I find substr very useful. It's often a lot more concise to specify how long you want a string to be rather than the end index of the string. If substr really ever is removed from browser or Node.js JavaScript support, I suspect many of us will simply monkey-patch substr back into existence anyway.


问:
Aws Rekognition - Search faces by image return maximum one match
Im using Aws Rekognition searchImageByFace function, for searching for the face id that matches between input image and a specific collection.
Everything works great except of the fact that the response I got includes maximum of one face match even if the input image as multiple faces.

I have tried to set the following:
MaxFaces: 6,
FaceMatchThreshold: 70

But it didn't help.

I would appreciate any suggestions.
Thanks!

答:
It is working the way it was designed.

SearchImagebyFace only searches against the largest face in the input image, as per the documentation:

For a given input image, first detects the largest face in the image,
and then searches the specified collection for matching faces.

MaxFaces in this case refers to the number of results, not the number of faces in the input image:

Maximum number of faces to return. The operation returns the maximum
number of faces with the highest confidence in the match.

To do what you want to do, you would need to first call IndexFaces to index all the faces in the input image, and then call SearchFaces on each face ID:

https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-id-procedure.html


问:
Display Django time variable as full hours, minutes am/pm
I want to use a time variable instead of a CharField for a model, which displays multiple saved times. My issue is it displays as "9 am" instead of "9:00 am", and "noon" instead of "12:00 pm".
Can anyone help? Thanks in advance.

Relevant code below-

models.py

```<code>class Post(models.Model):
time=models.TimeField()
free=models.CharField(max_length=50, default="")
player1=models.CharField(max_length=50, default="Player 1")
player2=models.CharField(max_length=50, default="Player 2")
player3=models.CharField(max_length=50, default="Player 3")
player4=models.CharField(max_length=50, default="Player 4")

def __str__(self):
    return self.time
</code>```

HTML

```<code> <h7>{{post.time}}     <a href="{% url 'update0' post.id %}"  class="btn-sm btn-success" >Update</a></h7>
</code>```

答:
You can try using built in date template tag.

```<code>{{ post.time|date:'H:i A' }}
</code>```

Body:
I want to use a time variable instead of a CharField for a model, which displays multiple saved times. My issue is it displays as "9 am" instead of "9:00 am", and "noon" instead of "12:00 pm".
Can anyone help? Thanks in advance.

Relevant code below-

models.py

class Post(models.Model):
time=models.TimeField()
free=models.CharField(max_length=50, default="")
player1=models.CharField(max_length=50, default="Player 1")
player2=models.CharField(max_length=50, default="Player 2")
player3=models.CharField(max_length=50, default="Player 3")
player4=models.CharField(max_length=50, default="Player 4")

def __str__(self):
    return self.time

HTML

 <h7>{{post.time}}     Update</h7>

Body:
You can try using built in date template tag.

{{ post.time|date:'H:i A' }}


问:
Easy_install and Pip doesn't work
Easy_install and Pip doesn't work anymore on python 2.7, when I try to do:

```<code>sudo easy_install pip
</code>```

I get:

```<code>Traceback (most recent call last):
  File "/usr/bin/easy_install", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: distribute==0.6.15
</code>```

And when I try:

```<code>sudo pip install [package]
</code>```

I get:

```<code>Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: pip==0.8.2
</code>```

I've already install both of them (and yes, first deleted them), but no result...

Thanks!

(I tried already this post)

答:
Try

```<code>  sudo easy_install Distribute
</code>```

and if that exists, but is too old

```<code>  sudo easy_install -U Distribute
</code>```

Looks like either Distribute/setuptools (it's old name) is messed up or Python package settings. If either of these do not help, try removing the full Python 2.7 installation and reinstall everything from the scratch.

Possible reasons for the mess is that you have used both sudo easy_install / sudo pip and Linux distribution packages to mix and match system-wide installation packages. You should use virtualenv instead if you use pip/easy_install (no sudo needed)

http://pypi.python.org/pypi/virtualenv

Title: Easy_install and Pip doesn't work

Body:
Easy_install and Pip doesn't work anymore on python 2.7, when I try to do:

sudo easy_install pip

I get:

Traceback (most recent call last):
  File "/usr/bin/easy_install", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: distribute==0.6.15

And when I try:

sudo pip install [package]

I get:

Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: pip==0.8.2

I've already install both of them (and yes, first deleted them), but no result...

Thanks!

(I tried already this post)

Body:
Try

  sudo easy_install Distribute

and if that exists, but is too old

  sudo easy_install -U Distribute

Looks like either Distribute/setuptools (it's old name) is messed up or Python package settings. If either of these do not help, try removing the full Python 2.7 installation and reinstall everything from the scratch.

Possible reasons for the mess is that you have used both sudo easy_install / sudo pip and Linux distribution packages to mix and match system-wide installation packages. You should use virtualenv instead if you use pip/easy_install (no sudo needed)

http://pypi.python.org/pypi/virtualenv


问:
What to return when failing to update a resource via API request? The resource or an error?
Suppose I'm trying to update a user via an API request to change his status to "active":

```<code>PUT http://example.com/user/12/activate
</code>```

What should my request handler return if the user is already "active"? Should I return a 200 response with the unmodified user object as its content, or should I return a 500 response with an error description?

If I should return the user object, how can the client know that something went wrong? Should I use a status code other than 200?

答:
You can return 409 Conflict HTTP status code in such cases.

You can learn about various HTTP status code using the links below:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409

Body:
Suppose I'm trying to update a user via an API request to change his status to "active":

PUT http://example.com/user/12/activate

What should my request handler return if the user is already "active"? Should I return a 200 response with the unmodified user object as its content, or should I return a 500 response with an error description?

If I should return the user object, how can the client know that something went wrong? Should I use a status code other than 200?


问:
How to access static class member from instance?
What is the best way to access a static member on a class from an instance of that class?

I want to be able to have shared values across all instances of a class be static on the class, and be able to refer to them from the instance.

There seems to be many janky ways of doing this, but none of them elegant IMO.

For example:

```<code>class BagOfCoins {
    static MAX_COINS = 9999;
}

const bag = new BagOfCoins();

// Method 1
// Almost works, but errors with "Property 'MAX_COINS' does not exist on type 'Function'.", but it still has a value of 9999 when compiled.
console.log(bag.constructor.MAX_COINS);

// Method 2
// Works, but looks awful and only works because it just confuses TS.
console.log(bag.constructor.prototype.constructor.MAX_COINS);

// Method 3
// Basically the same thing, TS still has no idea what the properties of `constructor` are so doesn't provide member suggestions.
console.log(Object.getPrototypeOf(bag).constructor.MAX_COINS);
</code>```

Method 4

```<code>class BagOfCoins {
    // Add a reference to the class itself to each instance.
    Class = BagOfCoins;

    static MAX_COINS = 9999;
}

const bag = new BagOfCoins();

// Wastes more memory for an extra member that it already has access to by other means...
console.log(bag.Class.MAX_COINS);
</code>```

Method 5

```<code>type Writable<T> = {-readonly [K in keyof T]: T[K]};

class BagOfCoins {
    readonly MAX_COINS!: number;
}
// Emulate static membership by moving it to the class prototype.
(BagOfCoins.prototype as Writable<BagOfCoins>).MAX_COINS = 9999;

const bag = new BagOfCoins();

// Adds a lot of extra syntax for defining such members, and need to move the initialisation out of the class itself, which looks awful.
console.log(bag.MAX_COINS);
</code>```

Is there a more user-friendly way of doing this that doesn't require adding a lot of confusing bloat?

EDIT:

Some answers & comments seem to be getting distracted by the low-hanging fruit answer of BagOfCoins.MAX_COINS.

Consider the following example use for when you might not know the specific class that a instance is made from, but you do know that the class has the static property you want to access defined on it:

```<code>class Weapon {
    static DAMAGE = 1;
}

class Spear extends Weapon {
}

class Sword extends Weapon {
    static DAMAGE = 4;
}

const Weapons: {[key: string]: typeof Weapon} = {
    Spear,
    Sword,
    // etc. may be a dynamically generated list from data loaded from some config file.
};

class Loadout {
    weapon: Weapon;

    constructor(weapon: Weapon) {
        this.weapon = weapon;
    }
}

const loadout1 = new Loadout(new Weapons.Spear());
const loadout2 = new Loadout(new Weapons.Sword());
// and so on...

// Comment by jcalz adds another method, by using a parent class that has the desired static property, i.e. Weapon.
// Method 6
// Best one so far I guess, a bit better looking than the others IMO, but does allow proper property suggestions.
console.log((loadout1.weapon.constructor as typeof Weapon).DAMAGE); // 1
console.log((loadout2.weapon.constructor as typeof Weapon).DAMAGE); // 4
</code>```

答:
Practically, you can't access static members on an instance because they belong to the class and not accessible on the instance of the class:</p>
```<code>class Cow {
  static NUMBER_OF_HORNS = 2
}
// usage would go like this:
let horns = Cow.NUMBER_OF_HORNS // 2
const ankole = new Cow()
ankole.NUMBER_OF_HORNS // this will never work, NUMBER_OF_HORNS is a     static property
</code>```

Body:
What is the best way to access a static member on a class from an instance of that class?

I want to be able to have shared values across all instances of a class be static on the class, and be able to refer to them from the instance.

There seems to be many janky ways of doing this, but none of them elegant IMO.

For example:

class BagOfCoins {
    static MAX_COINS = 9999;
}

const bag = new BagOfCoins();

// Method 1
// Almost works, but errors with "Property 'MAX_COINS' does not exist on type 'Function'.", but it still has a value of 9999 when compiled.
console.log(bag.constructor.MAX_COINS);

// Method 2
// Works, but looks awful and only works because it just confuses TS.
console.log(bag.constructor.prototype.constructor.MAX_COINS);

// Method 3
// Basically the same thing, TS still has no idea what the properties of `constructor` are so doesn't provide member suggestions.
console.log(Object.getPrototypeOf(bag).constructor.MAX_COINS);

Method 4

class BagOfCoins {
    // Add a reference to the class itself to each instance.
    Class = BagOfCoins;

    static MAX_COINS = 9999;
}

const bag = new BagOfCoins();

// Wastes more memory for an extra member that it already has access to by other means...
console.log(bag.Class.MAX_COINS);

Method 5

type Writable<T> = {-readonly [K in keyof T]: T[K]};

class BagOfCoins {
    readonly MAX_COINS!: number;
}
// Emulate static membership by moving it to the class prototype.
(BagOfCoins.prototype as Writable<BagOfCoins>).MAX_COINS = 9999;

const bag = new BagOfCoins();

// Adds a lot of extra syntax for defining such members, and need to move the initialisation out of the class itself, which looks awful.
console.log(bag.MAX_COINS);

Is there a more user-friendly way of doing this that doesn't require adding a lot of confusing bloat?

EDIT:

Some answers & comments seem to be getting distracted by the low-hanging fruit answer of BagOfCoins.MAX_COINS.

Consider the following example use for when you might not know the specific class that a instance is made from, but you do know that the class has the static property you want to access defined on it:

class Weapon {
    static DAMAGE = 1;
}

class Spear extends Weapon {
}

class Sword extends Weapon {
    static DAMAGE = 4;
}

const Weapons: {[key: string]: typeof Weapon} = {
    Spear,
    Sword,
    // etc. may be a dynamically generated list from data loaded from some config file.
};

class Loadout {
    weapon: Weapon;

    constructor(weapon: Weapon) {
        this.weapon = weapon;
    }
}

const loadout1 = new Loadout(new Weapons.Spear());
const loadout2 = new Loadout(new Weapons.Sword());
// and so on...

// Comment by jcalz adds another method, by using a parent class that has the desired static property, i.e. Weapon.
// Method 6
// Best one so far I guess, a bit better looking than the others IMO, but does allow proper property suggestions.
console.log((loadout1.weapon.constructor as typeof Weapon).DAMAGE); // 1
console.log((loadout2.weapon.constructor as typeof Weapon).DAMAGE); // 4

Body:
Practically, you can't access static members on an instance because they belong to the class and not accessible on the instance of the class:

class Cow {
  static NUMBER_OF_HORNS = 2
}
// usage would go like this:
let horns = Cow.NUMBER_OF_HORNS // 2
const ankole = new Cow()
ankole.NUMBER_OF_HORNS // this will never work, NUMBER_OF_HORNS is a     static property


问:
JDBC Pool Connection Validation
I experienced an outage with my application the other day and I need to understand how to avoid this in the future.

We have a Java based web application running on Tomcat 7. The application connected to several different data sources including an Oracle database.

Here are the details, the Oracle database server went down and had to be rebooted. My simple understanding tells me this would have severed the application's connections to the database, and in fact the users reported errors in the application.

The Oracle data source is setup in Tomcat's sever.xml as a GlobalNaming Resource:

```<code><Resource name="datasource"
        auth="Container"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        ....
        initialSize="4"
        minIdle="2"
        maxIdle="8"
        maxActive="8"
        maxAge="28800000"
        maxWait="30000"
        testOnBorrow="false"
        testOnReturn="false"
        testWhileIdle="false"
        validationQuery="SELECT 1 FROM dual"
        validationQueryTimeout="10"
        validationInterval="600000"
        timeBetweenEvictionRunsMillis="60000"
        minEvictableIdleTimeMillis="900000"
        removeAbandoned="true"
        removeAbandonedTimeout="60"
        logAbandoned="true"
        jmxEnabled="true" />
</code>```

So here is what I understand regarding connection validation.

Connections are not validated while idle (testWhileIdle = false), when borrowed (testOnBorrow = false), when returned (testOnReturn = false)

The PoolSweeper is enabled because timeBetweenEvictionRunsMillis > 0, removeAbandoned is true, and removeAbandonedTimeout > 0

What confuses me is the inclusion of the validation query and the validationInterval > 0. Since all of the tests are disabled, does the pool sweeper then use the validation query to check the connections? Or is the validation query irrelevant?

So when the database server went down, I believe the connection pool would not have tried to reestablish connections because there are no validation tests enabled. In my opinion, had testOnBorrow been enabled then when the database server came back up valid connections would have been established and the web application (meaning tomcat) would not have required a restart.

Do I have a correct understanding of how connection validation works?

答: you must lower the maxAge="28800000" parameter, in addition to this your instance crashes due to application errors and you should use jdbc interceptor</p>

Title: JDBC Pool Connection Validation

Body:
I experienced an outage with my application the other day and I need to understand how to avoid this in the future.

We have a Java based web application running on Tomcat 7. The application connected to several different data sources including an Oracle database.

Here are the details, the Oracle database server went down and had to be rebooted. My simple understanding tells me this would have severed the application's connections to the database, and in fact the users reported errors in the application.

The Oracle data source is setup in Tomcat's sever.xml as a GlobalNaming Resource:

<Resource name="datasource"
        auth="Container"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        ....
        initialSize="4"
        minIdle="2"
        maxIdle="8"
        maxActive="8"
        maxAge="28800000"
        maxWait="30000"
        testOnBorrow="false"
        testOnReturn="false"
        testWhileIdle="false"
        validationQuery="SELECT 1 FROM dual"
        validationQueryTimeout="10"
        validationInterval="600000"
        timeBetweenEvictionRunsMillis="60000"
        minEvictableIdleTimeMillis="900000"
        removeAbandoned="true"
        removeAbandonedTimeout="60"
        logAbandoned="true"
        jmxEnabled="true" />

So here is what I understand regarding connection validation.

Connections are not validated while idle (testWhileIdle = false), when borrowed (testOnBorrow = false), when returned (testOnReturn = false)

The PoolSweeper is enabled because timeBetweenEvictionRunsMillis > 0, removeAbandoned is true, and removeAbandonedTimeout > 0

What confuses me is the inclusion of the validation query and the validationInterval > 0. Since all of the tests are disabled, does the pool sweeper then use the validation query to check the connections? Or is the validation query irrelevant?

So when the database server went down, I believe the connection pool would not have tried to reestablish connections because there are no validation tests enabled. In my opinion, had testOnBorrow been enabled then when the database server came back up valid connections would have been established and the web application (meaning tomcat) would not have required a restart.

Do I have a correct understanding of how connection validation works?


问:
SolR : full sentence spellcheck
I'm trying to configure a spellchecker to autocomplete full sentences from my query.

I've already been able to get this results:

"american israel" :

-> "american something"

-> "israel something"

But i want :

"american israel" :

-> "american israel something"

This is my solrconfig.xml :

```<code><searchComponent name="suggest_full" class="solr.SpellCheckComponent">
 <str name="queryAnalyzerFieldType">suggestTextFull</str>
 <lst name="spellchecker">
  <str name="name">suggest_full</str>
  <str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
  <str name="lookupImpl">org.apache.solr.spelling.suggest.tst.TSTLookup</str>
  <str name="field">text_suggest_full</str>
  <str name="fieldType">suggestTextFull</str>
 </lst>
</searchComponent>

<requestHandler name="/suggest_full" class="org.apache.solr.handler.component.SearchHandler">
<lst name="defaults">
 <str name="echoParams">explicit</str>
 <str name="spellcheck">true</str>
 <str name="spellcheck.dictionary">suggest_full</str>
 <str name="spellcheck.count">10</str>
 <str name="spellcheck.onlyMorePopular">true</str>
</lst>
<arr name="last-components">
 <str>suggest_full</str>
</arr>
</requestHandler>
</code>```

And this is my schema.xml:

```<code><fieldType name="suggestTextFull" class="solr.TextField">
  <analyzer type="index">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

...

<field name="text_suggest_full" type="suggestTextFull" indexed="true" stored="false" multiValued="true"/>
</code>```

I've read somewhere that I have to use spellcheck.q because q use the WhitespaceAnalyzer, but when I use spellcheck.q i get a java.lang.NullPointerException

Any ideas ?

答:
If you spellcheck fields ( text_suggest_full ) contain american something and israel something so make sure, that there also exist an document/entry , with the value american israel something.

Solr will not  merge american something and israel something to one term and will not apply the result to your spellchecking for american israel.

Title: SolR : full sentence spellcheck

Body:
I'm trying to configure a spellchecker to autocomplete full sentences from my query.

I've already been able to get this results:

"american israel" :

-> "american something"

-> "israel something"

But i want :

"american israel" :

-> "american israel something"

This is my solrconfig.xml :

<searchComponent name="suggest_full" class="solr.SpellCheckComponent">
 <str name="queryAnalyzerFieldType">suggestTextFull</str>
 <lst name="spellchecker">
  <str name="name">suggest_full</str>
  <str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
  <str name="lookupImpl">org.apache.solr.spelling.suggest.tst.TSTLookup</str>
  <str name="field">text_suggest_full</str>
  <str name="fieldType">suggestTextFull</str>
 </lst>
</searchComponent>

<requestHandler name="/suggest_full" class="org.apache.solr.handler.component.SearchHandler">
<lst name="defaults">
 <str name="echoParams">explicit</str>
 <str name="spellcheck">true</str>
 <str name="spellcheck.dictionary">suggest_full</str>
 <str name="spellcheck.count">10</str>
 <str name="spellcheck.onlyMorePopular">true</str>
</lst>
<arr name="last-components">
 <str>suggest_full</str>
</arr>
</requestHandler>

And this is my schema.xml:

<fieldType name="suggestTextFull" class="solr.TextField">
  <analyzer type="index">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

...

<field name="text_suggest_full" type="suggestTextFull" indexed="true" stored="false" multiValued="true"/>

I've read somewhere that I have to use spellcheck.q because q use the WhitespaceAnalyzer, but when I use spellcheck.q i get a java.lang.NullPointerException

Any ideas ?


问:
NPM CLI returns command not found
I have created a simple CLI to bootstrap projects with inquirer and have successfully published it to NPM. However, when installing it with

```<code>npm i -g noobject
</code>```

it's successfully loading and installing.
When running

```<code>noobject
</code>```

in the cmd line, it does return "command not found" and when running

```<code>npx noobject its returning the following.
</code>```
```<code>npm ERR! could not determine executable to run

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Me\AppData\Local\npm-cache\_logs\2022-02-13T17_28_00_374Z-debug-0.log
</code>```

I have tried it both on windows 10 and linux ubuntu 20.4.
Here is my index.js: https://sourceb.in/ZGZMWKU8tb

#! /usr/bin/env node
const inquirer = require("inquirer");
const fs = require("fs");

// FULL SOURCE TREE: https://github.com/vKxni/noobject

const CURR_DIR = process.cwd();
const CHOICES = fs.readdirSync(`${__dirname}/templates`);

// Questions asked to the User
const QUESTIONS = [
  {
    name: "project-choice",
    type: "list",
    message: "What project would you like to generate?",
    choices: CHOICES,
  },
  {
    name: "project-name",
    type: "input",
    message: "Project name:",
    validate: (input) => {
      if (/^([A-Za-z\-\_\d])+$/.test(input)) return true;
      else
        return "Project name may only include letters, numbers, underscores and hashes.";
    },
  },
];

// Send a prompt to choose a template
inquirer.prompt(QUESTIONS).then((answers) => {
  const projectChoice = answers["project-choice"];
  const projectName = answers["project-name"];
  const templatePath = `${__dirname}/templates/${projectChoice}`;

  // Create the folder with the project name choosed by the user
  fs.mkdirSync(`${CURR_DIR}/${projectName}`);

  createDirectoryContents(templatePath, projectName);

  console.log(`✅ Successfully created ${projectName}`);
});

const createDirectoryContents = (templatePath, newProjectPath) => {
  const filesToCreate = fs.readdirSync(templatePath);

  filesToCreate.forEach((file) => {
    const origFilePath = `${templatePath}/${file}`;

    const stats = fs.statSync(origFilePath);

    if (stats.isFile()) {
      const contents = fs.readFileSync(origFilePath, "utf8");

      if (file === ".npmignore") file = ".gitignore";

      const writePath = `${CURR_DIR}/${newProjectPath}/${file}`;
      fs.writeFileSync(writePath, contents, "utf8");

      console.log(`⚠ Created ${writePath}`);

    } else if (stats.isDirectory()) {
      fs.mkdirSync(`${CURR_DIR}/${newProjectPath}/${file}`);

      createDirectoryContents(
        `${templatePath}/${file}`,
        `${newProjectPath}/${file}`
      );
    }
  });
};
```
<p>Here is my package.json:</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "noobject",
  "version": "1.2.8",
  "description": "Project generator written in NodeJS",
  "main": "index.js",
  "scripts": {
    "noobject": "node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/vKxni/noobject.git",
  "keywords": [
    "node",
    "generator",
    "project",
    "noobject"
  ],
  "author": "vKxni",
  "license": "ISC",
  "dependencies": {
    "inquirer": "^8.2.0"
  },
  "bin": {
    "noobject": "index.js"
  }
  }
}
</code>```

(As a pastebin: https://sourceb.in/CF4ydtNccG).
I hope anyone can help me so I can bootstrap projects and config files easier and faster.

答:
Your problem is that you're missing a } for repository, so bin is actually inside repository. You can see there's a doubled } in the second to last line.

{
  "name": "noobject",
  "version": "1.2.8",
  "description": "Project generator written in NodeJS",
  "main": "index.js",
  "scripts": {
    "noobject": "node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/vKxni/noobject.git",
  /* <----- should be here */
  "keywords": [
    "node",
    "generator",
    "project",
    "noobject"
  ],
  "author": "vKxni",
  "license": "ISC",
  "dependencies": {
    "inquirer": "^8.2.0"
  },
  "bin": {
    "noobject": "index.js"
  }
  } /* <----- wrong place! */
}
```
<p>If you fix that, it works:</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "noobject",
  "version": "1.2.8",
  "description": "Project generator written in NodeJS",
  "main": "index.js",
  "scripts": {
    "noobject": "node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/vKxni/noobject.git",
  },
  "keywords": [
    "node",
    "generator",
    "project",
    "noobject"
  ],
  "author": "vKxni",
  "license": "ISC",
  "dependencies": {
    "inquirer": "^8.2.0"
  },
  "bin": {
    "noobject": "index.js"
  }
}
</code>```

Title: NPM CLI returns command not found

Body:
I have created a simple CLI to bootstrap projects with inquirer and have successfully published it to NPM. However, when installing it with

npm i -g noobject

it's successfully loading and installing.
When running

noobject

in the cmd line, it does return "command not found" and when running

npx noobject its returning the following.

npm ERR! could not determine executable to run

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Me\AppData\Local\npm-cache\_logs\2022-02-13T17_28_00_374Z-debug-0.log

I have tried it both on windows 10 and linux ubuntu 20.4.
Here is my index.js: https://sourceb.in/ZGZMWKU8tb

#! /usr/bin/env node
const inquirer = require("inquirer");
const fs = require("fs");

// FULL SOURCE TREE: https://github.com/vKxni/noobject

const CURR_DIR = process.cwd();
const CHOICES = fs.readdirSync(`${__dirname}/templates`);

// Questions asked to the User
const QUESTIONS = [
  {
    name: "project-choice",
    type: "list",
    message: "What project would you like to generate?",
    choices: CHOICES,
  },
  {
    name: "project-name",
    type: "input",
    message: "Project name:",
    validate: (input) => {
      if (/^([A-Za-z\-\_\d])+$/.test(input)) return true;
      else
        return "Project name may only include letters, numbers, underscores and hashes.";
    },
  },
];

// Send a prompt to choose a template
inquirer.prompt(QUESTIONS).then((answers) => {
  const projectChoice = answers["project-choice"];
  const projectName = answers["project-name"];
  const templatePath = `${__dirname}/templates/${projectChoice}`;

  // Create the folder with the project name choosed by the user
  fs.mkdirSync(`${CURR_DIR}/${projectName}`);

  createDirectoryContents(templatePath, projectName);

  console.log(`✅ Successfully created ${projectName}`);
});

const createDirectoryContents = (templatePath, newProjectPath) => {
  const filesToCreate = fs.readdirSync(templatePath);

  filesToCreate.forEach((file) => {
    const origFilePath = `${templatePath}/${file}`;

    const stats = fs.statSync(origFilePath);

    if (stats.isFile()) {
      const contents = fs.readFileSync(origFilePath, "utf8");

      if (file === ".npmignore") file = ".gitignore";

      const writePath = `${CURR_DIR}/${newProjectPath}/${file}`;
      fs.writeFileSync(writePath, contents, "utf8");

      console.log(`⚠ Created ${writePath}`);

    } else if (stats.isDirectory()) {
      fs.mkdirSync(`${CURR_DIR}/${newProjectPath}/${file}`);

      createDirectoryContents(
        `${templatePath}/${file}`,
        `${newProjectPath}/${file}`
      );
    }
  });
};

Here is my package.json:

{
  "name": "noobject",
  "version": "1.2.8",
  "description": "Project generator written in NodeJS",
  "main": "index.js",
  "scripts": {
    "noobject": "node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/vKxni/noobject.git",
  "keywords": [
    "node",
    "generator",
    "project",
    "noobject"
  ],
  "author": "vKxni",
  "license": "ISC",
  "dependencies": {
    "inquirer": "^8.2.0"
  },
  "bin": {
    "noobject": "index.js"
  }
  }
}

(As a pastebin: https://sourceb.in/CF4ydtNccG).
I hope anyone can help me so I can bootstrap projects and config files easier and faster.

Body:
Your problem is that you're missing a } for repository, so bin is actually inside repository. You can see there's a doubled } in the second to last line.

{
  "name": "noobject",
  "version": "1.2.8",
  "description": "Project generator written in NodeJS",
  "main": "index.js",
  "scripts": {
    "noobject": "node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/vKxni/noobject.git",
  /* <----- should be here */
  "keywords": [
    "node",
    "generator",
    "project",
    "noobject"
  ],
  "author": "vKxni",
  "license": "ISC",
  "dependencies": {
    "inquirer": "^8.2.0"
  },
  "bin": {
    "noobject": "index.js"
  }
  } /* <----- wrong place! */
}

If you fix that, it works:

{
  "name": "noobject",
  "version": "1.2.8",
  "description": "Project generator written in NodeJS",
  "main": "index.js",
  "scripts": {
    "noobject": "node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/vKxni/noobject.git",
  },
  "keywords": [
    "node",
    "generator",
    "project",
    "noobject"
  ],
  "author": "vKxni",
  "license": "ISC",
  "dependencies": {
    "inquirer": "^8.2.0"
  },
  "bin": {
    "noobject": "index.js"
  }
}


问:
How to add the same Layout to Layout via kv file?
There is a problem that it is impossible to add BoxLayout to BoxLayout via kv file.

GTN.py

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class GTNApp(App):
    def build(self):
        return Main()

class Main(BoxLayout):
    pass

if __name__ == "__main__":
    GTNApp().run()
</code>```

GTN.kv

```<code><BoxLayout>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: '1'
</code>```

После этого выдает ошибку: AssertionError

答:
Python File. GTN.py

```<code>    from kivy.app import App
    from kivy.lang import Builder

    class GTNApp(App):
        def build(self):
            self.screen = Builder.load_file('GTN.kv')
            return self.screen

    if __name__ == "__main__":
        GTNApp().run()
</code>```

Kv File . GTN.kv

```<code>   BoxLayout:
       orientation: 'vertical'
       BoxLayout:
           orientation: 'horizontal'
           Button:
               text: '1'

</code>```

Body:
There is a problem that it is impossible to add BoxLayout to BoxLayout via kv file.

GTN.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class GTNApp(App):
    def build(self):
        return Main()

class Main(BoxLayout):
    pass

if __name__ == "__main__":
    GTNApp().run()

GTN.kv

<BoxLayout>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: '1'

После этого выдает ошибку: AssertionError

Body:
Python File. GTN.py

    from kivy.app import App
    from kivy.lang import Builder

    class GTNApp(App):
        def build(self):
            self.screen = Builder.load_file('GTN.kv')
            return self.screen

    if __name__ == "__main__":
        GTNApp().run()

Kv File . GTN.kv

   BoxLayout:
       orientation: 'vertical'
       BoxLayout:
           orientation: 'horizontal'
           Button:
               text: '1'


问:
Built-in Constructors and their Prototype --
The activity was to Log Array.prototype and Object.prototype to the console using only the arr variable and the proto property.

So these are the original code:

```<code>const arr = [1, 2, 3];

console.log(); // log the Array.prototype
console.log(); // log the Object.prototype
</code>```

So What I did: I wrote on the first, console.log(arr.__proto__ === Array.prototype);
the second one is, console.log(arr.__proto__ === Object.prototype); but still not right.
It says that in the first log, the Array.prototype is the proto property of any array. the next one, the prototype property of Array.prototype refers to the object.prototype. I can't figure it out what does it meant. I tried also writing like this: console.log(arr.__proto__ === Object.prototype); still not right. What am I missing here?

答:
Here is a solution:

const arr = [1, 2, 3];
console.log(Array.prototype === arr.__proto__);
console.log(Object.prototype === arr.__proto__.__proto__);
```
<p>Explanation: since array in Javascript is also an Object, you can access <code>Object.prototype</code> using just <code>arr</code>.</p>
<p>Following will also log true:</p>
<pre class="lang-js prettyprint-override"><code>console.log(Array.prototype.__proto__ === Object.prototype);
console.log(Array.__proto__.__proto__ === Object.prototype);
</code>```

Body:
The activity was to Log Array.prototype and Object.prototype to the console using only the arr variable and the proto property.

So these are the original code:

const arr = [1, 2, 3];

console.log(); // log the Array.prototype
console.log(); // log the Object.prototype

So What I did: I wrote on the first, console.log(arr.__proto__ === Array.prototype);
the second one is, console.log(arr.__proto__ === Object.prototype); but still not right.
It says that in the first log, the Array.prototype is the proto property of any array. the next one, the prototype property of Array.prototype refers to the object.prototype. I can't figure it out what does it meant. I tried also writing like this: console.log(arr.__proto__ === Object.prototype); still not right. What am I missing here?

Body:
Here is a solution:

const arr = [1, 2, 3];
console.log(Array.prototype === arr.__proto__);
console.log(Object.prototype === arr.__proto__.__proto__);

Explanation: since array in Javascript is also an Object, you can access Object.prototype using just arr.

Following will also log true:

console.log(Array.prototype.__proto__ === Object.prototype);
console.log(Array.__proto__.__proto__ === Object.prototype);


问:
Project Run Time does not start on Sagemaker Studio Lab
That is the case as of last night. Does not work for CPU or GPU "compute type"
Basically, after pressing the "Start runtime" button, it says "Preparing project runtime..." for about ten minutes and then stops. It shows the following error, "There was a problem when starting the project runtime. This should be resolved shortly. Please try again later."

I have now tried it about five times over last night and this morning.

There is no way to even access the work that is saved there. The "project" will not boot up.

Basically it is a dud at this point.

Is anyone else experiencing similar issues? What does one do?

答:
The issues/questions and answers that I have learned since (because I was asked to clarify):

(1) The environment on Sagemaker Studio Lab is supposed to be persistent. I.e., any time one starts it, the environment, files uploaded, etc. are where it was left last. However, I was not able to start the environment any longer. Before it locked out, it would start fine. Consequently, I was not able to get to my saved work in any way shape or form. I was wondering if anyone has had this issue

Answer: Thus far not too many people are approved for Sagemaker Studio Lab. So, I may have been the first or one of the first to encounter this issue. As of this writing there does not exist a way to access ones data if one cannot spin up a virtual machine that would have access to the data using their "Start runtime" button.

(2) It is not clear where one is supposed to report issues with Sagemaker Studio Lab. On one's home page in Studio Lab, it has a link to StackOverflow under "Get answers and help others". That is how I ended up here. Though, I should have included the following hashtag (#amazon-sagemaker pointing to https://stackoverflow.com/questions/tagged/amazon-sagemaker).

Answer: I eventually found where people are submitting bug reports. And I reported the issue there (see issue 56). https://github.com/aws/studio-lab-examples/issues

(3) It was not clear to me if I was to delete my account and request a new one if I would be put on a waitlist (which supposedly is presently long). I.e., this would be the manual factory reboot option where one still loses all of ones work, but, at least has an opportunity to start again with the environment.

Answer: Once one is approved, one does not go to the waitlist. Deleting my account, requesting a new one, and setting it up to the initial state took a couple of minutes for me. And yes, I lost all my work that was on there. So, back stuff up as it was your computer in the `80s. I.e., back up externally to that environment.


问:
How would you solve this tricky SQL problem?
Say you have a table layout like the following:

couses:

```<code>id (INT),
courseName (VARCHAR)
</code>```

instructors:

```<code>id (INT),
courseId(INT),
instructor(VARCHAR)
</code>```

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

```
    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee
```

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

答:
I think this will work, but I have not tested it yet. It is not very scalable if you decide that you want to start showing 3 instructors or 4 or more though.</p>

```<code>SELECT
    C.id AS course_id,
    CASE
        WHEN I3 IS NOT NULL THEN 'Committee'
        ELSE I1.instructor + COALESCE(', ' + I2.instructor, '')
    END AS instructors
FROM
    Courses C
LEFT OUTER JOIN Instructors I1 ON
    I1.course_id = C.id
LEFT OUTER JOIN Instructors I_CHK1 ON
    I_CHK1.course_id = C.id AND
    I_CHK1.instructor < I1.instructor
LEFT OUTER JOIN Instructors I2 ON
    I2.course_id = C.id AND
    I2.instructor > I1.instructor
LEFT OUTER JOIN Instructors I_CHK2 ON
    I_CHK2.course_id = C.id AND
    I_CHK2.instructor > I1.instructor AND
    I_CHK2.instructor < I2.instructor
LEFT OUTER JOIN Instructors I_CHK2 ON
    I3.course_id = C.id AND
    I3.instructor > I2.instructor AND
WHERE
    I_CHK1.id IS NULL AND
    I_CHK2.id IS NULL
</code>```

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Body:
Say you have a table layout like the following:

couses:

id (INT),
courseName (VARCHAR)

instructors:

id (INT),
courseId(INT),
instructor(VARCHAR)

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

Body:
I think this will work, but I have not tested it yet. It is not very scalable if you decide that you want to start showing 3 instructors or 4 or more though.

SELECT
    C.id AS course_id,
    CASE
        WHEN I3 IS NOT NULL THEN 'Committee'
        ELSE I1.instructor + COALESCE(', ' + I2.instructor, '')
    END AS instructors
FROM
    Courses C
LEFT OUTER JOIN Instructors I1 ON
    I1.course_id = C.id
LEFT OUTER JOIN Instructors I_CHK1 ON
    I_CHK1.course_id = C.id AND
    I_CHK1.instructor < I1.instructor
LEFT OUTER JOIN Instructors I2 ON
    I2.course_id = C.id AND
    I2.instructor > I1.instructor
LEFT OUTER JOIN Instructors I_CHK2 ON
    I_CHK2.course_id = C.id AND
    I_CHK2.instructor > I1.instructor AND
    I_CHK2.instructor < I2.instructor
LEFT OUTER JOIN Instructors I_CHK2 ON
    I3.course_id = C.id AND
    I3.instructor > I2.instructor AND
WHERE
    I_CHK1.id IS NULL AND
    I_CHK2.id IS NULL

OwnerDisplayName: Tom H.


问:
How to define Ordering[Array[Byte]]?
Is it necessary to provide the implementation from scratch? I could not find any matching implicit, not even in last-resort Implicits trait. seqDerivedOrdering obviously doesn't work, since Array is not a Seq.

答: You can implement a very simple Ordering which calls toSeq on comapred array and calls then the seqDerivedOrdering. The conversion to a Seq should be nearly free in term of performances.

Title: How to define Ordering[Array[Byte]]?


问:
Is it possible to schedule a tweet?
Is it possible to schedule a tweet using Tweepy?

I could not find any mention to the datetime, referring to the code I use to create a tweet in tweepy:

```<code>api.update_status(tw_post)
</code>```

If it is not possible, which workaround would you suggest to schedule tweets using python?
Thanks

答:
You can use datetime to check for the current time:

```<code>if (DateTime.Now.Hour == 18)
    api.update_status(tw_post)
</code>```

If the hour on your computer is 18, the code will run.

Title: Is it possible to schedule a tweet?

Body:
Is it possible to schedule a tweet using Tweepy?

I could not find any mention to the datetime, referring to the code I use to create a tweet in tweepy:

api.update_status(tw_post)

If it is not possible, which workaround would you suggest to schedule tweets using python?
Thanks

Body:
You can use datetime to check for the current time:

if (DateTime.Now.Hour == 18)
    api.update_status(tw_post)

If the hour on your computer is 18, the code will run.


问:
CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler (in target 'Pageboy' from project 'Pods')
I am getting the below error when I build my iOS project in Xcode 13.0 for Simulator 15 with Swift 5.5

答:
For Example:

```<code>The following build commands failed:
    CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler (in target 'ExpoModulesCore' from project 'Pods')
</code>```

The outdated pod here seems to be ExpoModulesCore

and if it does not work, like it did not for me lol:

follow this: https://stackoverflow.com/a/69384358/15421728

For anyone looking for an answer.

run

cd ios
pod update ExpoModulesCore
```

and repeat the previous step for every outdated pod, if there are more outdated.

Body:
For Example:

The following build commands failed:
    CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler (in target 'ExpoModulesCore' from project 'Pods')

The outdated pod here seems to be ExpoModulesCore

and if it does not work, like it did not for me lol:

follow this: https://stackoverflow.com/a/69384358/15421728

For anyone looking for an answer.

run

cd ios
pod update ExpoModulesCore

and repeat the previous step for every outdated pod, if there are more outdated.