问:
TypeError: webpack.optimize.UglifyJsPlugin is not a constructor
I'm experiencing a TypeError and am unsure how to resolve it. I look forward to any help you can provide.  The following is the terminal output from yarn run build:

```<code>BUILD_DIR /Users/blakelucey/Desktop/fsd-next/build
SRC_DIR /Users/blakelucey/Desktop/fsd-next/src
[webpack-cli] TypeError: webpack.optimize.UglifyJsPlugin is not a constructor
    at module.exports (/Users/blakelucey/Desktop/fsd-next/webpack.config.js:118:7)
    at WebpackCLI.loadConfig (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1589:33)
    at async WebpackCLI.resolveConfig (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1677:38)
    at async WebpackCLI.createCompiler (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:2085:22)
    at async WebpackCLI.runWebpack (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:2213:20)
    at async Command.<anonymous> (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:850:25)
    at async Promise.all (index 1)
    at async Command.<anonymous> (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1516:13)
error Command failed with exit code 2.
</code>```

This is the webpack.config.js:

```<code>const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

const extractCSS = new ExtractTextPlugin('[name].fonts.css');
const extractSCSS = new ExtractTextPlugin('[name].styles.css');
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');

console.log('BUILD_DIR', BUILD_DIR);
console.log('SRC_DIR', SRC_DIR);

module.exports = (env = {}) => {
  return {
    entry: {
      index: [SRC_DIR + '/index.tsx']
    },
    output: {
      path: BUILD_DIR,
      filename: '[name].bundle.js'
    },
    node: {
      fs: "empty"
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.css', 'scss']
    },
    // watch: true,
    devtool: env.prod ? 'source-map' : 'cheap-module-eval-source-map',
    devServer: {
      contentBase: BUILD_DIR,
      //   port: 9001,
      compress: true,
      hot: true,
      open: true
    },
    // optimization: {
    //   minimizer: [
    //     new UglifyJsPlugin({sourceMap: true})
    //   ]
    // },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: [
            {
              loader: 'ts-loader'
            }
          ],
        },
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              presets: ['react', 'env']
            }
          }
        },
        {
          test: /\.html$/,
          loader: 'html-loader'
        },
        {
          test: /\.(scss)$/,
          use: ['css-hot-loader'].concat(extractSCSS.extract({
            fallback: 'style-loader',
            use: [
              {
                loader: 'css-loader',
                options: { alias: { '../img': '../public/img' } }
              },
              {
                loader: 'sass-loader'
              }
            ]
          }))
          // loader: MiniCssExtractPlugin.loader
        },
        {
          test: /\.css$/,
          use: extractCSS.extract({
            fallback: 'style-loader',
            use: 'css-loader'
          })
          // loader: MiniCssExtractPlugin.loader
        },
        {
          test: /\.(png|jpg|jpeg|gif|ico)$/,
          use: [
            {
              // loader: 'url-loader'
              loader: 'file-loader',
              options: {
                name: './img/[name].[hash].[ext]'
              }
            }
          ]
        },
        {
          test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
          loader: 'file-loader',
          options: {
            name: './fonts/[name].[hash].[ext]'
          }
        }]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
      new webpack.NamedModulesPlugin(),
      extractCSS,
      extractSCSS,
      // new MiniCssExtractPlugin({
      //   // Options similar to the same options in webpackOptions.output
      //   // both options are optional
      //   filename: "[name].css",
      //   chunkFilename: "[id].css"
      // }),
      new HtmlWebpackPlugin(
        {
          inject: true,
          template: './public/index.html'
        }
      ),
      new CopyWebpackPlugin([
        { from: './public/img', to: 'img' }
      ],
        { copyUnmodified: false }
      ),
      new CopyWebpackPlugin([
        { from: './public/robot.txt', to: 'robot.txt' }
      ],
        { copyUnmodified: false }
      )
    ]
  }
};
</code>```

I think I need to remove my comments here:

```<code>// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
</code>```

and here:

```<code>// optimization: {
    //   minimizer: [
    //     new UglifyJsPlugin({sourceMap: true})
    //   ]
    // },
</code>```

But I'm not sure.  I look forward to and appreciate any input you can contribute, thank you.

答:
I searched the internet and came across issues like the following but could not solve my project problem

[https://stackoverflow.com/questions/46389267/using-async-await-with-webpack-simple-configuration-throwing-error-regeneratorr][1]

Body:
I'm experiencing a TypeError and am unsure how to resolve it. I look forward to any help you can provide.  The following is the terminal output from yarn run build:

BUILD_DIR /Users/blakelucey/Desktop/fsd-next/build
SRC_DIR /Users/blakelucey/Desktop/fsd-next/src
[webpack-cli] TypeError: webpack.optimize.UglifyJsPlugin is not a constructor
    at module.exports (/Users/blakelucey/Desktop/fsd-next/webpack.config.js:118:7)
    at WebpackCLI.loadConfig (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1589:33)
    at async WebpackCLI.resolveConfig (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1677:38)
    at async WebpackCLI.createCompiler (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:2085:22)
    at async WebpackCLI.runWebpack (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:2213:20)
    at async Command.<anonymous> (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:850:25)
    at async Promise.all (index 1)
    at async Command.<anonymous> (/Users/blakelucey/Desktop/fsd-next/node_modules/webpack-cli/lib/webpack-cli.js:1516:13)
error Command failed with exit code 2.

This is the webpack.config.js:

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

const extractCSS = new ExtractTextPlugin('[name].fonts.css');
const extractSCSS = new ExtractTextPlugin('[name].styles.css');
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');

console.log('BUILD_DIR', BUILD_DIR);
console.log('SRC_DIR', SRC_DIR);

module.exports = (env = {}) => {
  return {
    entry: {
      index: [SRC_DIR + '/index.tsx']
    },
    output: {
      path: BUILD_DIR,
      filename: '[name].bundle.js'
    },
    node: {
      fs: "empty"
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.css', 'scss']
    },
    // watch: true,
    devtool: env.prod ? 'source-map' : 'cheap-module-eval-source-map',
    devServer: {
      contentBase: BUILD_DIR,
      //   port: 9001,
      compress: true,
      hot: true,
      open: true
    },
    // optimization: {
    //   minimizer: [
    //     new UglifyJsPlugin({sourceMap: true})
    //   ]
    // },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: [
            {
              loader: 'ts-loader'
            }
          ],
        },
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              presets: ['react', 'env']
            }
          }
        },
        {
          test: /\.html$/,
          loader: 'html-loader'
        },
        {
          test: /\.(scss)$/,
          use: ['css-hot-loader'].concat(extractSCSS.extract({
            fallback: 'style-loader',
            use: [
              {
                loader: 'css-loader',
                options: { alias: { '../img': '../public/img' } }
              },
              {
                loader: 'sass-loader'
              }
            ]
          }))
          // loader: MiniCssExtractPlugin.loader
        },
        {
          test: /\.css$/,
          use: extractCSS.extract({
            fallback: 'style-loader',
            use: 'css-loader'
          })
          // loader: MiniCssExtractPlugin.loader
        },
        {
          test: /\.(png|jpg|jpeg|gif|ico)$/,
          use: [
            {
              // loader: 'url-loader'
              loader: 'file-loader',
              options: {
                name: './img/[name].[hash].[ext]'
              }
            }
          ]
        },
        {
          test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
          loader: 'file-loader',
          options: {
            name: './fonts/[name].[hash].[ext]'
          }
        }]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
      new webpack.NamedModulesPlugin(),
      extractCSS,
      extractSCSS,
      // new MiniCssExtractPlugin({
      //   // Options similar to the same options in webpackOptions.output
      //   // both options are optional
      //   filename: "[name].css",
      //   chunkFilename: "[id].css"
      // }),
      new HtmlWebpackPlugin(
        {
          inject: true,
          template: './public/index.html'
        }
      ),
      new CopyWebpackPlugin([
        { from: './public/img', to: 'img' }
      ],
        { copyUnmodified: false }
      ),
      new CopyWebpackPlugin([
        { from: './public/robot.txt', to: 'robot.txt' }
      ],
        { copyUnmodified: false }
      )
    ]
  }
};

I think I need to remove my comments here:

// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

and here:

// optimization: {
    //   minimizer: [
    //     new UglifyJsPlugin({sourceMap: true})
    //   ]
    // },

But I'm not sure.  I look forward to and appreciate any input you can contribute, thank you.


来源: stackexchange

问:
Sell me on unit testing
I've been a .Net developer for a long time and am trying to wrap my head around real, practical unit testing.

Most specifically, I'm looking at unit testing ASP.Net MVC 3 projects.

I've read a decent amount about it, and believe I understand it at the academic level (i.e. basically ensures that changes you make aren't going to break other stuff).  However, all of the tests I've seen written in examples are trivially stupid things that would be a pretty obvious catch anyway (does this controller return a view with this name?).

So, maybe I'm missing something, or just haven't seen any really good test examples or something, but it really looks like a crap ton of extra work and complexity with mocking, ioc, etc and I'm just not seeing the counter-balancing gains.

Teach me, please :)

答: Given proper unit testing, it's almost trivial to catch corner-cases that would have otherwise slipped passed you.  Let's say you have a method that returns a list of items and the list of items is retrieved from some table.  What happens if that table isn't populated correctly (e.g. if there's a null value in one of the columns or empty) or if they change the column type to something your ORM tool doesn't map like you thought it would?  Unit tests would help catch these cases before you're in production and someone deletes all of the data in your table. </p>

ContentLicense: CC BY-SA 3.0

Title: Sell me on unit testing


问:
In an object nesting key-value pairs, how to convert a single-value array into just the value itself?
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]
```
<p>Since all the arrays are single-values, I would like to convert this entire <code>albums</code> object to:</p>
<pre class="lang-js prettyprint-override"><code>// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]
</code>```

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...

答:
Keep it Simple! You can achieve this by just using Array.toString() method.

Working Demo :

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
];

albums.forEach((obj) => {
    Object.keys(obj).forEach((key) => {
    obj[key] = obj[key].length === 1 ? obj[key].toString() : obj[key]
  });
});

console.log(albums);```

ContentLicense: CC BY-SA 4.0

Body:
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]

Since all the arrays are single-values, I would like to convert this entire albums object to:

// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...


问:
how to use template string to add or remove class of a button on click of the same button react
I am working on a quiz app using React and I want to change the border color of a button from grey to green if answer is correct and to red if incorrect. I am using template literals and I want to apply a different className only onClick but I am not sure where to place this line of code. Currently, It shows the correct and wrong answers before being answered.</p>
```<code>import {useState, useEffect} from 'react';
import "../index.css"

const QuestionSection = () => {
    const [questions, setQuestions] = useState([]);
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [showScore, setShowScore] = useState(false);
    const [score, setScore] = useState(0);
    const defaultBorder = "3px solid grey";
    const correctBorder = "3px solid green";
    const wrongBorder = "3px solid red";
    const [border, setBorder] = useState(defaultBorder);

    useEffect(() => {
        const getQuestions = async () => {
            const questionsFromServer = await fetchQuestions()
            setQuestions(questionsFromServer)
        }

        getQuestions()
    }, [])
    //Fetch questions
    const fetchQuestions = async () => {
        const res = await fetch ('http://localhost:5000/questions');
        const data = await res.json();

        return data
    }

    const handleAnswerOptionClick = (correct) => {
        if (correct) {
            setScore(score + 1);
            setBorder(correctBorder);

        } else {
            setBorder(wrongBorder);
        }

        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.length) {
            setCurrentQuestion(nextQuestion);
        } else {
            setShowScore(true);
        }
    };
  return (
    <questionSection>
    <div className='questionSection'>
            {showScore ? (
                <div className='score-section'>
                    You scored {score} out of {questions.length}
                </div>
            ) : (
                <>
                    <div className='question-section'>
                        <div className='question-count'>
                            <span>Question {currentQuestion + 1}</span>/{questions.length}
                        </div>
                        <div className='question-text'>{questions[currentQuestion]?.questionText}</div>
                    </div>
                    <div className='answer-section'>
                        {questions[currentQuestion]?.answerOptions.map((answerOption) => (
                            <button
                            //style = {`button ${answerOption.correct ? {correctBorder} : {wrongBorder}}`}
                            key = {answerOption.id}
                            onClick={() => {
                            handleAnswerOptionClick(answerOption.correct, border);

                            }}>
                            {answerOption.id} {answerOption.answerText}
                            </button>
                        ))}
                    </div>
                </>
            )}
        </div>
    </questionSection>
  )
}

export default QuestionSection
</code>```

答:
I think I spot a few problems here.

For one, you're setting border as a className, when it is defined as an object. Class names should be strings, and unless you have a CSS file not shown here it will have no effect. To apply objects as styles you need to use the style prop. It's here in the React docs.

The border property in CSS also takes 3 arguments, the width, style, and color. See this link. You're currently only passing one.

The state of your border is also confusing. It's instantiated as a string, grey, and then you are trying to update it to objects. It's unclear how you intend it to be read.

On that note, when you call setBorder in your button's onClick, you don't actually pass it a value to set to. This article explains setState.

Without a better look at the data you're fetching I'm not sure I can tell you exactly what else to implement to get it working, but here is a demo that I think should help illustrate a version of what you're trying to accomplish.

https://codesandbox.io/s/ecstatic-firefly-m7vcj?file=/src/App.js

Body:
I am working on a quiz app using React and I want to change the border color of a button from grey to green if answer is correct and to red if incorrect. I am using template literals and I want to apply a different className only onClick but I am not sure where to place this line of code. Currently, It shows the correct and wrong answers before being answered.

import {useState, useEffect} from 'react';
import "../index.css"

const QuestionSection = () => {
    const [questions, setQuestions] = useState([]);
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [showScore, setShowScore] = useState(false);
    const [score, setScore] = useState(0);
    const defaultBorder = "3px solid grey";
    const correctBorder = "3px solid green";
    const wrongBorder = "3px solid red";
    const [border, setBorder] = useState(defaultBorder);

    useEffect(() => {
        const getQuestions = async () => {
            const questionsFromServer = await fetchQuestions()
            setQuestions(questionsFromServer)
        }

        getQuestions()
    }, [])
    //Fetch questions
    const fetchQuestions = async () => {
        const res = await fetch ('http://localhost:5000/questions');
        const data = await res.json();

        return data
    }

    const handleAnswerOptionClick = (correct) => {
        if (correct) {
            setScore(score + 1);
            setBorder(correctBorder);

        } else {
            setBorder(wrongBorder);
        }

        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.length) {
            setCurrentQuestion(nextQuestion);
        } else {
            setShowScore(true);
        }
    };
  return (
    <questionSection>

            {showScore ? (

                    You scored {score} out of {questions.length}

            ) : (
                <>

                            Question {currentQuestion + 1}/{questions.length}

{questions[currentQuestion]?.questionText}

                        {questions[currentQuestion]?.answerOptions.map((answerOption) => (
                            <button
                            //style = {`button ${answerOption.correct ? {correctBorder} : {wrongBorder}}`}
                            key = {answerOption.id}
                            onClick={() => {
                            handleAnswerOptionClick(answerOption.correct, border);

                            }}>
                            {answerOption.id} {answerOption.answerText}
                            </button>
                        ))}

                </>
            )}

    </questionSection>
  )
}

export default QuestionSection


问:
How to replace all occurrences using sed
I couldn't make it work the way I want.

```<code>echo 'https://aaa/xx_one/bbb/xx_two/ccc' | sed 's|^\(https://.*\)xx_|\1OK_|g'
https://aaa/xx_one/bbb/OK_two/ccc
</code>```

The output I wanted is: https://aaa/OK_one/bbb/OK_two/ccc

That is, I just want to replace every occurrences of xx_ with OK_ and with that specific constraint.

Need some help. I want it in sed. Thanks.

答:
If the line should start with https://, which you originally didn't say, you can use an "address" in sed:

```<code>sed '\=^https://= s/xx_/OK_/g'
</code>```

Original answer: (will replace xx_ by OK_ after https://, but the line doesn't have to start with it).

Perl to the rescue:

```<code>perl -pe '1 while s=https://.*\Kxx_=OK_=g'
</code>```

-p reads the input line by line, prints each line after processing;

\K in a regular expression forgets what's been matched so far. In this case, it will only replace the xx_ by OK_, but it still has to match https://.* before it;

The substitution runs in a while loop until there's nothing to replace.

Body:
I couldn't make it work the way I want.

echo 'https://aaa/xx_one/bbb/xx_two/ccc' | sed 's|^\(https://.*\)xx_|\1OK_|g'
https://aaa/xx_one/bbb/OK_two/ccc

The output I wanted is: https://aaa/OK_one/bbb/OK_two/ccc

That is, I just want to replace every occurrences of xx_ with OK_ and with that specific constraint.

Need some help. I want it in sed. Thanks.

Body:
If the line should start with https://, which you originally didn't say, you can use an "address" in sed:

sed '\=^https://= s/xx_/OK_/g'

Original answer: (will replace xx_ by OK_ after https://, but the line doesn't have to start with it).

Perl to the rescue:

perl -pe '1 while s=https://.*\Kxx_=OK_=g'

-p reads the input line by line, prints each line after processing;

\K in a regular expression forgets what's been matched so far. In this case, it will only replace the xx_ by OK_, but it still has to match https://.* before it;

The substitution runs in a while loop until there's nothing to replace.


问:
Dealing with ambiguity in BNF grammar
I'm trying to build a parser for a DSL I'm building using Irony in .NET and found a problem I can't find a way around. Since it handles BNF I think that any BNF solution will be of help.

I have the following input:

```
$10 yesterday at drug store
```

With the following grammar:

```<code><expr> :== unit | expr + unit
<unit> :==  money | date | location

<date> : == yesterday|today|tomorrow
<location> :== .* | <preposition> .*
<preposition> :== at
<money> :== ((\$)?\d*((\.*)\d*)*\,?\d{1,2})
</code>```

It works like a charm with this input. I get exactly the result I wanted which is:

```<code>Money Amount: 10
Date: Yesterday
Location: Drug Store
</code>```

However, if I change the order of the input as following

```<code>$10 at drug store yesterday
</code>```

because of reduce steps it fails to give me the same output. The output becomes:

```<code>Money amount: 10
Location: Drug Store Yesterday
</code>```

I was wondering if there is way to make sure that Location (which is a really broad regex match) is only evaluated when all the other tokens are captured and nothing else is left.

Any help is appreciated.

Thanks!

Edit: Updated title according to suggestion

答:
Besides the fact that this is not a general answer to BNF ambiguity I was able to solve my problem with Irony by creating a new Terminal.

So if anyone else encounters this problem, the code for the new Terminal (while not added to main Irony project) can be found in this link: http://irony.codeplex.com/discussions/269483

Thanks

Title: Dealing with ambiguity in BNF grammar

Body:
I'm trying to build a parser for a DSL I'm building using Irony in .NET and found a problem I can't find a way around. Since it handles BNF I think that any BNF solution will be of help.

I have the following input:

$10 yesterday at drug store

With the following grammar:

<expr> :== unit | expr + unit
<unit> :==  money | date | location

<date> : == yesterday|today|tomorrow
<location> :== .* | <preposition> .*
<preposition> :== at
<money> :== ((\$)?\d*((\.*)\d*)*\,?\d{1,2})

It works like a charm with this input. I get exactly the result I wanted which is:

Money Amount: 10
Date: Yesterday
Location: Drug Store

However, if I change the order of the input as following

$10 at drug store yesterday

because of reduce steps it fails to give me the same output. The output becomes:

Money amount: 10
Location: Drug Store Yesterday

I was wondering if there is way to make sure that Location (which is a really broad regex match) is only evaluated when all the other tokens are captured and nothing else is left.

Any help is appreciated.

Thanks!

Edit: Updated title according to suggestion


问:
Could not find a version that satisfies the requirement pkg-resources==0.0.0
My app is deployed on heroku.

When I push my code via git push heroku master. It gives me this error

```<code>Collecting pkg-resources==0.0.0 (from -r requirements.txt (line 14))
remote:          Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r requirements.txt (line 14)) (from versions: )
remote:        No matching distribution found for pkg-resources==0.0.0 (from -r requirements.txt (line 14))
remote:  !     Push rejected, failed to compile Python app.
</code>```

requirement.txt

```<code>amqp==2.1.1
billiard==3.5.0.2
boto==2.42.0
celery==4.0.0
dj-database-url==0.4.1
Django==1.10.2
django-appconf==1.0.2
django-model-utils==2.6
django-storages==1.5.1
djangorestframework==3.4.7
gunicorn==19.6.0
Jinja2==2.8
kombu==4.0.0
MarkupSafe==0.23
optional-django==0.1.0
pep8==1.7.0
pkg-resources==0.0.0
psycopg2==2.6.2
pyflakes==1.3.0
pytz==2016.7
rcssmin==1.0.6
requests==2.12.1
rjsmin==1.0.12
vine==1.1.3
whitenoise==3.2.2
</code>```

Note: Its working perfectly fine on my local server.

My Question is why is not working on heroku but working on local. ???

答:
Remove pkg-resources==0.0.0 from requirements.txt

if you wish to avoid the problem next time you do a freeze, use pip uninstall pkg-resources==0.0.0

Body:
My app is deployed on heroku.

When I push my code via git push heroku master. It gives me this error

Collecting pkg-resources==0.0.0 (from -r requirements.txt (line 14))
remote:          Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r requirements.txt (line 14)) (from versions: )
remote:        No matching distribution found for pkg-resources==0.0.0 (from -r requirements.txt (line 14))
remote:  !     Push rejected, failed to compile Python app.

requirement.txt

amqp==2.1.1
billiard==3.5.0.2
boto==2.42.0
celery==4.0.0
dj-database-url==0.4.1
Django==1.10.2
django-appconf==1.0.2
django-model-utils==2.6
django-storages==1.5.1
djangorestframework==3.4.7
gunicorn==19.6.0
Jinja2==2.8
kombu==4.0.0
MarkupSafe==0.23
optional-django==0.1.0
pep8==1.7.0
pkg-resources==0.0.0
psycopg2==2.6.2
pyflakes==1.3.0
pytz==2016.7
rcssmin==1.0.6
requests==2.12.1
rjsmin==1.0.12
vine==1.1.3
whitenoise==3.2.2

Note: Its working perfectly fine on my local server.

My Question is why is not working on heroku but working on local. ???


问:
Javascript: How to remove empty string values from an array?
I have this array of objects:

const data = [{
    "_id": "plastic",
    "countries": ['Egypt','','Iran','',''],
    "likelihood": [1,2,3,4,5],
    "relevance": [1,2,3,4,5],
    "intensity": [1,2,3,4,5]
},
{
    "_id": "peak oil",
    "countries": ['USA','Russia',''],
    "likelihood": [1,2,3],
    "relevance": [1,2,3],
    "intensity": [1,2,3]
 }]```
</div>
</div>
</p>
<p>I want to remove empty strings in the countries array. Now here's the catch, I want to remove the same index in likelihood,relevance and intensity as well.</p>
<p>I tried this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// replacement for splice, array.remove(index)
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })</code>```

Example output on the above data:

[{
        "_id": "plastic",
        "countries": ['Egypt','Iran'],
        "likelihood": [1,3],
        "relevance": [1,3],
        "intensity": [1,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia'],
        "likelihood": [1,2],
        "relevance": [1,2],
        "intensity": [1,2]
 }]```

As you can see the index which was empty in the countries array was removed along with likelihood,relevance,intensity.

How can I achieve this ?

UPDATE

I want multiple strings to be removed.

答:
Complete algorithm:

for(let i=0; i<array.length; i++) {
    const trackindices = []
    const countries = data[i].countries.filter(Boolean)
    for(let k=0; k<data[i].countries.length; k++) {
        if(data[i].countries[k] == '') {
            trackindices.push(k)
        }
    }
    data[i].countries = countries

    const likelihood = data[i].likelihood
    const relevance = data[i].relevance
    const intensity = data[i].intensity

   trackindices.forEach(index => {
        delete likelihood[index]
        delete relevance[index]
        delete intensity[index]
   })
   data[i].likelihood = likelihood.filter(element => element !== undefined)
   data[i].relevance = relevance.filter(element => element !== undefined)
   data[i].intensity = intensity.filter(element => element !== undefined)
}```

Body:
I have this array of objects:

const data = [{
    "_id": "plastic",
    "countries": ['Egypt','','Iran','',''],
    "likelihood": [1,2,3,4,5],
    "relevance": [1,2,3,4,5],
    "intensity": [1,2,3,4,5]
},
{
    "_id": "peak oil",
    "countries": ['USA','Russia',''],
    "likelihood": [1,2,3],
    "relevance": [1,2,3],
    "intensity": [1,2,3]
 }]

I want to remove empty strings in the countries array. Now here's the catch, I want to remove the same index in likelihood,relevance and intensity as well.

I tried this:

// replacement for splice, array.remove(index)
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })

Example output on the above data:

[{
        "_id": "plastic",
        "countries": ['Egypt','Iran'],
        "likelihood": [1,3],
        "relevance": [1,3],
        "intensity": [1,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia'],
        "likelihood": [1,2],
        "relevance": [1,2],
        "intensity": [1,2]
 }]

As you can see the index which was empty in the countries array was removed along with likelihood,relevance,intensity.

How can I achieve this ?

UPDATE

I want multiple strings to be removed.


问:
Localhost accessed req.session.userid but virtual host can't be reached
here is some problem that i have... i have been tried days to figure it out but nothing make it working.

i have Node.js Express session on backend and there are users, when i make login i set req.session.userId = "userid" and i have middleware that check if req.session.userId exist and then next() so on Localhost everything worked fine but when i hosted my website i can’t access the req.session.userId it's mean the Middleware don’t next()

Frondend hosted: Netlify

Backend hosted: Nodechef

Mysql hosted: Nodechef

i don’t know, maybe i missed something or that i have to made some
changes when hosting...

i hope you guys have solution for me

index.js

```<code>const express = require('express');
const cookieParser = require("cookie-parser");
const session = require('express-session');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors({
origin: '***********',
credentials: true
}));

app.all('/', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});

app.use(session({
    secret: "******",
    name: "*****",
    saveUninitialized: true,
    resave: true,
    cookie: {
        domain: '*******',
        secure: true,
        maxAge: 1000 * 60 * 60 * 24 * 365,
    }
}))
app.get('/', (req, res) => {
    res.send({ msg: "seccess" })
})
app.use('/users', require('./routes/users'))

const PORT = 3000
app.listen(process.env.PORT || PORT, () => {
    console.log(`Express server listening on port ${PORT} `);
});
</code>```

users/login

```<code> const router = require('express').Router()

 router.post('/login', (req, res) => {
    const { userEmail, userPassword } = req.body
    db.query(`SELECT * FROM users WHERE userEmail = ?`, userEmail,
        (err, result) => {
            if (err) {
                return res.send({ err: err })
            } else {
                if (!userEmail || !userPassword)
                req.session.userId = user.id
                res.send({ msg: "Login Succes", req: req.session, user: user.id })
            }
        })
});
</code>```

Middleware

```<code>module.exports.onlyLoggedUsers = (req, res, next) => {
    if (req.session.userId) {
        next()
    } else {
        res.status(200).send({err:"sensetive content for logged users only, plesae log in"})
    }
}
</code>```

答:
I just added app.enable('trust proxy')
and it is work temporarily, in safari this not work and also on smartphone, if I got to setting in safari and turn of Prevent Cross-Site Tracking it is working so my question is how I can run the application without turn of Prevent Cross-Site Tracking.

Body:
here is some problem that i have... i have been tried days to figure it out but nothing make it working.

i have Node.js Express session on backend and there are users, when i make login i set req.session.userId = "userid" and i have middleware that check if req.session.userId exist and then next() so on Localhost everything worked fine but when i hosted my website i can’t access the req.session.userId it's mean the Middleware don’t next()

Frondend hosted: Netlify

Backend hosted: Nodechef

Mysql hosted: Nodechef

i don’t know, maybe i missed something or that i have to made some
changes when hosting...

i hope you guys have solution for me

index.js

const express = require('express');
const cookieParser = require("cookie-parser");
const session = require('express-session');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors({
origin: '***********',
credentials: true
}));

app.all('/', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});

app.use(session({
    secret: "******",
    name: "*****",
    saveUninitialized: true,
    resave: true,
    cookie: {
        domain: '*******',
        secure: true,
        maxAge: 1000 * 60 * 60 * 24 * 365,
    }
}))
app.get('/', (req, res) => {
    res.send({ msg: "seccess" })
})
app.use('/users', require('./routes/users'))

const PORT = 3000
app.listen(process.env.PORT || PORT, () => {
    console.log(`Express server listening on port ${PORT} `);
});

users/login

 const router = require('express').Router()

 router.post('/login', (req, res) => {
    const { userEmail, userPassword } = req.body
    db.query(`SELECT * FROM users WHERE userEmail = ?`, userEmail,
        (err, result) => {
            if (err) {
                return res.send({ err: err })
            } else {
                if (!userEmail || !userPassword)
                req.session.userId = user.id
                res.send({ msg: "Login Succes", req: req.session, user: user.id })
            }
        })
});

Middleware

module.exports.onlyLoggedUsers = (req, res, next) => {
    if (req.session.userId) {
        next()
    } else {
        res.status(200).send({err:"sensetive content for logged users only, plesae log in"})
    }
}


问:
FBReactNativeSpec, PhaseScriptExecution failed with a nonzero exit code
I have been having issues trying to create an IOS build of a react native application. Originally I made this on windows with an android emulator. Then I tried to build the react native code on mac with xcode but I can't get past this error.

I have tried a couple things like reinstalling node and unsetting the PREFIX variable in the find-node script but I have not gotten any further

When inspecting the error it says:

FBReactNativeSpec - Uncategorized - PhaseScriptExecution failed with a nonzero exit code

int he details there is another error that says:

bash: mobile/node_modules/react-native/scripts/../Libraries: No such file or directory

答:
I had the same issue on my MacBook Pro with M1 chip.
I managed to get rid of the FBReactNativeSpec error by editing the Project settings.

Try the following:

In Xcode select your app's project and then select the target.

In Terminal enter the following command to find out the path of your node installation:

which node

This should give you a path. Something like:

/Users/thomashuber/.nvm/versions/node/v16.14.0/bin/node

Copy this path.

In Xcode with the target selected click on Build Phases and open Bundle React Native code and images

Replace NODE_BINARY=node. Instead of node enter the path that you have copied so that it is something like this NODE_BINARY=/Users/thomashuber/.nvm/versions/node/v16.14.0/bin/node


问:
Unable to render {message} object in the Chrome Console
I am using {message} from the props in a component in the ReactJS.

The code is given below

```<code>import React from "react";

const MyMessage = ({ message }) => {
  if (message?.attachments?.length > 0) {
    return (
      <img
        src={message.attachments[0].file}
        alt="message_attachment"
        className="message-image"
        style={{ float: "right" }}
      />
    );
  }

  const msg = JSON.stringify(message);
  console.log("fmsg = "+ msg.sender)
  console.log("mes = "+JSON.stringify(message))
  console.log("now = "+msg.first_name)
  return (
    <div
      className="message"
      style={{
        float: "right",
        marginRight: "18px",
        color: "white",
        backgroundColor: "#3B2A50",
      }}
    >
      {message?.text}

    </div>
  );
};

export default MyMessage;

</code>```

What I tried?

I used the following console stmts:

console.log(message); ->  [Object Object]

console.log(JSON.stringify(message));

```<code>{
  "id":455890,
  "sender":{
    "username":"GMmohit",
    "first_name":"Mohit",
    "last_name":"Maroliya",
    "avatar":"https://api-chat-engine-io.s3.amazonaws.com/avatars/potrait_rKDI2hb.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAZA5RH3EC2MM47GFP%2F20220213%2Fca-central-1%2Fs3%2Faws4_request&X-Amz-Date=20220213T141431Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=1d5e0ec2418701210532824ba90af5f6366d17b7fa1f9dfadb6783cd8efdbfd6",
    "custom_json":"{}",
    "is_online":true
  },
  "created":"2022-02-12 12:23:04.745937+00:00",
  "attachments":[],
  "sender_username":"undefined",
  "text":"----",
  "custom_json":"{}"
}
</code>```

const msg = JSON.stringify(message)
console.log("now = "+msg.first_name)  -> but it gives undefined

How can I access the values in {message} like username,first_name etc? However, I am able to access message?.text .

答:
It looks like your username and first name are coming off the sender object in your message. You'll need to consider the sender like:
 message.sender.username
to access the username that is in the sender object in the message.

Body:
I am using {message} from the props in a component in the ReactJS.

The code is given below

import React from "react";

const MyMessage = ({ message }) => {
  if (message?.attachments?.length > 0) {
    return (

    );
  }

  const msg = JSON.stringify(message);
  console.log("fmsg = "+ msg.sender)
  console.log("mes = "+JSON.stringify(message))
  console.log("now = "+msg.first_name)
  return (

      {message?.text}

  );
};

export default MyMessage;

What I tried?

I used the following console stmts:

console.log(message); ->  [Object Object]

console.log(JSON.stringify(message));

{
  "id":455890,
  "sender":{
    "username":"GMmohit",
    "first_name":"Mohit",
    "last_name":"Maroliya",
    "avatar":"https://api-chat-engine-io.s3.amazonaws.com/avatars/potrait_rKDI2hb.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAZA5RH3EC2MM47GFP%2F20220213%2Fca-central-1%2Fs3%2Faws4_request&X-Amz-Date=20220213T141431Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=1d5e0ec2418701210532824ba90af5f6366d17b7fa1f9dfadb6783cd8efdbfd6",
    "custom_json":"{}",
    "is_online":true
  },
  "created":"2022-02-12 12:23:04.745937+00:00",
  "attachments":[],
  "sender_username":"undefined",
  "text":"----",
  "custom_json":"{}"
}

const msg = JSON.stringify(message)
console.log("now = "+msg.first_name)  -> but it gives undefined

How can I access the values in {message} like username,first_name etc? However, I am able to access message?.text .


答:
Good question that I tried out with rand() function just to check. It is sort of intuitive, but at the same time an Action without some prior .cache() applied to some data, would lead one to believe, a new round --> a new set of results.

show() is an Action with some smarts. Here is is based on the same underlying rdd and logically one would expect a deterministic outcome - at least I think so.

However, F.current_timestamp() is evaluated once at serialization time. So, two successive show()'s will have 2 different times. The other answer states that and points to the docs. So that is an exception and thus  tried with rand(). See below.

Datetime.now() is held constant by Spark - see WholeStageCodeGen - just how it works as it concerns the same underlying DF; it assumes the first lit function still applies because the preceding creation of the DF (underlying RDD) still exists. I did a check with rand() and all successive show() Actions return the same sequence of random numbers - the same seed is used. This emulates deterministic behaviour which is what we would want with 2 successive show() 's

With a new DF with same name, then that is also re-evaluated, obviously.

You can try and see what happens if you use .cache().

It is a contrived example range(10) of course.

Title: PySpark - Timestamp behavior

Body:
I'm trying to understand behaviour differences between pyspark.sql.currenttimestamp() and datetime.now()

If I create a Spark dataframe in DataBricks using these 2 mechanisms to create a timestamp column, everything works nicely as expected....

curDate2 = spark.range(10)\
  .withColumn("current_date_lit",F.lit(date.today()))\
  .withColumn("current_timestamp_lit",F.lit(F.current_timestamp()))\
  .withColumn("current_timestamp",F.current_timestamp())\
  .withColumn("now",F.lit(datetime.now()))

+---+----------------+---------------------+--------------------+--------------------+
| id|current_date_lit|current_timestamp_lit|   current_timestamp|                 now|
+---+----------------+---------------------+--------------------+--------------------+
|  0|      2022-02-12| 2022-02-12 16:40:...|2022-02-12 16:40:...|2022-02-12 16:40:...|
|  1|      2022-02-12| 2022-02-12 16:40:...|2022-02-12 16:40:...|2022-02-12 16:40:...|
|  2|      2022-02-12| 2022-02-12 16:40:...|2022-02-12 16:40:...|2022-02-12 16:40:...|
+---+----------------+---------------------+--------------------+--------------------+

However, when I then call show() on the dataframe a couple of minutes later the columns based on currenttimestamp() show me the time NOW (16:44) whilst the datetime.now() column shows me the timestamp from the first creation of the dataframe (16:40)

Clearly one column holds a literal value & the other enumerates the function at runtime but I'm at a loss to understand why they behave differently

show() a few mins later...

+---+----------------+---------------------+--------------------+--------------------+
| id|current_date_lit|current_timestamp_lit|   current_timestamp|                 now|
+---+----------------+---------------------+--------------------+--------------------+
|  0|      2022-02-12| 2022-02-12 16:44:...|2022-02-12 16:44:...|2022-02-12 16:40:...|
|  1|      2022-02-12| 2022-02-12 16:44:...|2022-02-12 16:44:...|2022-02-12 16:40:...|
|  2|      2022-02-12| 2022-02-12 16:44:...|2022-02-12 16:44:...|2022-02-12 16:40:...|
+---+----------------+---------------------+--------------------+--------------------+

Thanks - I hope this makes sense!


问:
TemplateDoesNotExist at / base/index.html when deploying to heroku
I've been working on this issue for days and I would really love some real help here! :)

I'm brand new to Python, Django, and stackoverflow, so please let me know if more information or a different format would be helpful.

I'm trying to deploy my app on Heroku. It runs locally, but when I try to

heroku open

I get the following error:

TemplateDoesNotExist at /
  base/index.html

I've seen this happen to others, and I've tried the following fixes which haven't worked:

Changing the folder structure by putting index.html directly into templates instead of templates>base>index.html
(TemplateDoesNotExist when base template is in root folder) - This causes the app to stop running locally

Adding templates as an installed app (like I did for core) by adding

(r'', include('templates.urls')),

to my urls.py

and added

'templates'

to my settings.py. This caused the app to stop running locally, so I changed it back.

changed my views.py from:

```<code>from django.shortcuts import render from django.views.generic.base
import TemplateView
# Create your views here. class LandingView(TemplateView):
   template_name = "base/index.html"
</code>```

to

```<code>from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
    template_name = [os.path.join(MAIN_DIR, 'coffeedapp2/templates')],
</code>```

checked to make sure I have standard Django 1.8x template settings (TemplateDoesNotExist at / base/index.html)

tried changing my views.py from:

```<code>from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
  template_name = "base/index.html"
</code>```

to

```<code>from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
  template_name = "base/index.html"
</code>```

(TemplateDoesNotExist at / at templates/index.html)

I'm thinking that I may need to define a SITE_ROOT or something but whenever I try to do that it stops running locally.

ERROR:

TemplateDoesNotExist at / base/index.html Request Method: GET Request
  URL:  https://salty-journey-18003.herokuapp.com/ Django Version:  1.9.7
  Exception Type:   TemplateDoesNotExist Exception Value:    base/index.html
  Exception
  Location: /app/.heroku/python/lib/python2.7/site-packages/django/template/loader.py
  in select_template, line 74 Python
  Executable:   /app/.heroku/python/bin/python Python Version:  2.7.12
  Python Path:   ['/app',  '/app/.heroku/python/bin',
  '/app/.heroku/python/lib/python2.7/site-packages/setuptools-23.1.0-py2.7.egg',
  '/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg',
  '/app',  '/app/.heroku/python/lib/python27.zip',
  '/app/.heroku/python/lib/python2.7',
  '/app/.heroku/python/lib/python2.7/plat-linux2',
  '/app/.heroku/python/lib/python2.7/lib-tk',
  '/app/.heroku/python/lib/python2.7/lib-old',
  '/app/.heroku/python/lib/python2.7/lib-dynload',
  '/app/.heroku/python/lib/python2.7/site-packages'] Server time:   Mon, 1
  Aug 2016 20:50:53 +0000 Template-loader postmortem

Django tried loading these templates, in this order:

Using engine django: django.template.loaders.filesystem.Loader:
  /coffeedapp2/templates/base/index.html (Source does not exist)
  django.template.loaders.app_directories.Loader:
  /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/base/index.html
  (Source does not exist)
  django.template.loaders.app_directories.Loader:
  /app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/templates/base/index.html
  (Source does not exist)

settings.py

"""

```<code>Django settings for coffeedapp2 project.

Generated by 'django-admin startproject' using Django 1.9.7.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MAIN_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^h)ohz4qbhu&5po084_ob8qy+1c*h^tb#jtab!p965^8@&64q!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'coffeedapp2.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(MAIN_DIR, 'coffeedapp2/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'coffeedapp2.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Update database configuration with $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES['default'] = dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(MAIN_DIR, 'coffeedapp2', 'static'),
    )
</code>```

coffeedapp>urls.py

```<code>from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.conf.urls import patterns

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    (r'', include('core.urls')),
)
</code>```

core>urls.py

```<code>from django.conf.urls import patterns, include, url
import core.views as coreviews
from django.conf.urls import include

urlpatterns = patterns('',

    url(r'^$', coreviews.LandingView.as_view()),
 )
</code>```

core>views.py

```<code>from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
    template_name = "base/index.html"
</code>```

See image of file structure

```<code>Relevant file structure:

coffeedapp2
  coffeedapp2
    _init_.py
    settings.py
    settings.py
    urls.py
    wsgi.py
  core
    migrations
    _init_.py
    admin.py
    apps.py
    models.py
    tests.py
    urls.py
    views.py
  static
  templates
    base
        index.html
</code>```

答: makes sure your template directory is named 'templates' not 'Templates'</p>

Body:
I've been working on this issue for days and I would really love some real help here! :)

I'm brand new to Python, Django, and stackoverflow, so please let me know if more information or a different format would be helpful.

I'm trying to deploy my app on Heroku. It runs locally, but when I try to

heroku open

I get the following error:

TemplateDoesNotExist at /
  base/index.html

I've seen this happen to others, and I've tried the following fixes which haven't worked:

Changing the folder structure by putting index.html directly into templates instead of templates>base>index.html
(TemplateDoesNotExist when base template is in root folder) - This causes the app to stop running locally

Adding templates as an installed app (like I did for core) by adding

(r'', include('templates.urls')),

to my urls.py

and added

'templates'

to my settings.py. This caused the app to stop running locally, so I changed it back.

changed my views.py from:

from django.shortcuts import render from django.views.generic.base
import TemplateView
# Create your views here. class LandingView(TemplateView):
   template_name = "base/index.html"

to

from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
    template_name = [os.path.join(MAIN_DIR, 'coffeedapp2/templates')],

checked to make sure I have standard Django 1.8x template settings (TemplateDoesNotExist at / base/index.html)

tried changing my views.py from:

from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
  template_name = "base/index.html"

to

from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
  template_name = "base/index.html"

(TemplateDoesNotExist at / at templates/index.html)

I'm thinking that I may need to define a SITE_ROOT or something but whenever I try to do that it stops running locally.

ERROR:

TemplateDoesNotExist at / base/index.html Request Method: GET Request
  URL:  https://salty-journey-18003.herokuapp.com/ Django Version:  1.9.7
  Exception Type:   TemplateDoesNotExist Exception Value:    base/index.html
  Exception
  Location: /app/.heroku/python/lib/python2.7/site-packages/django/template/loader.py
  in select_template, line 74 Python
  Executable:   /app/.heroku/python/bin/python Python Version:  2.7.12
  Python Path:   ['/app',  '/app/.heroku/python/bin',
  '/app/.heroku/python/lib/python2.7/site-packages/setuptools-23.1.0-py2.7.egg',
  '/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg',
  '/app',  '/app/.heroku/python/lib/python27.zip',
  '/app/.heroku/python/lib/python2.7',
  '/app/.heroku/python/lib/python2.7/plat-linux2',
  '/app/.heroku/python/lib/python2.7/lib-tk',
  '/app/.heroku/python/lib/python2.7/lib-old',
  '/app/.heroku/python/lib/python2.7/lib-dynload',
  '/app/.heroku/python/lib/python2.7/site-packages'] Server time:   Mon, 1
  Aug 2016 20:50:53 +0000 Template-loader postmortem

Django tried loading these templates, in this order:

Using engine django: django.template.loaders.filesystem.Loader:
  /coffeedapp2/templates/base/index.html (Source does not exist)
  django.template.loaders.app_directories.Loader:
  /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/base/index.html
  (Source does not exist)
  django.template.loaders.app_directories.Loader:
  /app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/templates/base/index.html
  (Source does not exist)

settings.py

"""

Django settings for coffeedapp2 project.

Generated by 'django-admin startproject' using Django 1.9.7.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MAIN_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^h)ohz4qbhu&5po084_ob8qy+1c*h^tb#jtab!p965^8@&64q!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'coffeedapp2.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(MAIN_DIR, 'coffeedapp2/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'coffeedapp2.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Update database configuration with $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES['default'] = dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(MAIN_DIR, 'coffeedapp2', 'static'),
    )

coffeedapp>urls.py

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.conf.urls import patterns

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    (r'', include('core.urls')),
)

core>urls.py

from django.conf.urls import patterns, include, url
import core.views as coreviews
from django.conf.urls import include

urlpatterns = patterns('',

    url(r'^$', coreviews.LandingView.as_view()),
 )

core>views.py

from django.shortcuts import render
from django.views.generic.base import TemplateView
# Create your views here.
class LandingView(TemplateView):
    template_name = "base/index.html"

See image of file structure

Relevant file structure:

coffeedapp2
  coffeedapp2
    _init_.py
    settings.py
    settings.py
    urls.py
    wsgi.py
  core
    migrations
    _init_.py
    admin.py
    apps.py
    models.py
    tests.py
    urls.py
    views.py
  static
  templates
    base
        index.html


问:
how to get slack notification on change of Kubernetes pod status?
How to get slack notification while any k8s pod status changed? can't use kube bots as it's not allowed in my organisation.</p>

答:
You can try to use kwatch, which sends Slack notifications on crashes -

https://github.com/abahmed/kwatch


问:
Sum between dates (lines)
I have the following situation, I want to sum how much I've sold from 30 days ago. For the date 01/07/2020, my sum (the amount I've sold) has to be between 01/06 to 30/06.

My table

ID
CREATED_AT
AMOUNT_CENTS

9000
13/02/2022
100

9000
01/11/2021
200

9000
29/01/2022
300

9000
30/12/2021
400

9000
25/12/2021
500

9000
03/02/2022
600

9000
08/02/2022
700

9000
04/02/2022
800

9000
07/02/2022
900

How can I do that in SQL (select) I use SQL Management.

答:
Here are a couple of examples to work with:

SELECT SUM([AMOUNT_CENTS]) AS [Total]

FROM [TableName]

WHERE [CREATED_AT] BETWEEN GETDATE()-30 AND GETDATE()-1
```
<pre class="lang-sql prettyprint-override"><code>SELECT SUM(CASE WHEN [CREATED_AT] BETWEEN GETDATE()-30 AND GETDATE()-1 THEN [AMOUNT_CENTS] ELSE 0 END) AS [Total]

FROM [TableName]
</code>```

Title: Sum between dates (lines)

Body:
Here are a couple of examples to work with:

SELECT SUM([AMOUNT_CENTS]) AS [Total]

FROM [TableName]

WHERE [CREATED_AT] BETWEEN GETDATE()-30 AND GETDATE()-1

SELECT SUM(CASE WHEN [CREATED_AT] BETWEEN GETDATE()-30 AND GETDATE()-1 THEN [AMOUNT_CENTS] ELSE 0 END) AS [Total]

FROM [TableName]


问:
React | Update State | using spread and array.push to update array
I have jsfiddle Link https://jsfiddle.net/ilikeflex/r2uws1ez/30/

I am trying to set new state by accessing the previous state. I have three different cases where i am trying to update the state but i am not sure why does Case2 and Case 3 does not work. Can you please help me ??

```<code>const useState = React.useState;

function Example() {

  const [todos, setTodos] = useState([
    {id:1,text:'Learn React'},
    {id:2,text:'Learn TypeScript'},
    {id:3,text:'Learn Java'}
    ]);

  const case1 = () => {
   const newItem = {id:3,text:'Learn C++'};

   setTodos((prevState) => {
    return prevState.concat(newItem);
   });

  }

  const case2 = () => {
   const newItem = {id:3,text:'Learn .Net'};

   setTodos((prevState) => {
    prevState.push(newItem);  // I am adding to previous state and returning it
    return prevState;
   });

  }

 const case3 = () => {
   const newItem = {id:3,text:'Learn C#'};

   setTodos((prevState) => {
    let result = { ...prevState, newItem }; // using spread operator
    return result;
   });

  }

  return (
    <div>

      <button onClick={case1}>Case 1</button>
      <button onClick={case2}>Case 2</button>
      <button onClick={case3}>Case 3</button>

      <ul>
            {todos.map((item) => (
            <li key={item.id}>{item.text}</li>
          ))}
      </ul>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'))
</code>```

答:
To make case 2 work, you need to make a variable out of the prevState first. Then you can push to it and return that new variable.

```<code>const case2 = () => {
   const newItem = {id:3,text:'Learn .Net'};

   setTodos((prevState) => {
   const newState = [...prevState]
    newState.push(newItem);
    return newState;
   });

  }
</code>```

For case 3, you made a little mistake by making result an object instead of an array. Change the {} to [] and it should work fine, like this.

```<code>const case3 = () => {
   const newItem = {id:3,text:'Learn C#'};

   setTodos((prevState) => {
    let result = [...prevState, newItem ] ;
    return result;
   });

  }
</code>```

Body:
I have jsfiddle Link https://jsfiddle.net/ilikeflex/r2uws1ez/30/

I am trying to set new state by accessing the previous state. I have three different cases where i am trying to update the state but i am not sure why does Case2 and Case 3 does not work. Can you please help me ??

const useState = React.useState;

function Example() {

  const [todos, setTodos] = useState([
    {id:1,text:'Learn React'},
    {id:2,text:'Learn TypeScript'},
    {id:3,text:'Learn Java'}
    ]);

  const case1 = () => {
   const newItem = {id:3,text:'Learn C++'};

   setTodos((prevState) => {
    return prevState.concat(newItem);
   });

  }

  const case2 = () => {
   const newItem = {id:3,text:'Learn .Net'};

   setTodos((prevState) => {
    prevState.push(newItem);  // I am adding to previous state and returning it
    return prevState;
   });

  }

 const case3 = () => {
   const newItem = {id:3,text:'Learn C#'};

   setTodos((prevState) => {
    let result = { ...prevState, newItem }; // using spread operator
    return result;
   });

  }

  return (

      <button onClick={case1}>Case 1</button>
      <button onClick={case2}>Case 2</button>
      <button onClick={case3}>Case 3</button>

            {todos.map((item) => (

{item.text}

          ))}

  );
}

ReactDOM.render(<Example />, document.getElementById('root'))

Body:
To make case 2 work, you need to make a variable out of the prevState first. Then you can push to it and return that new variable.

const case2 = () => {
   const newItem = {id:3,text:'Learn .Net'};

   setTodos((prevState) => {
   const newState = [...prevState]
    newState.push(newItem);
    return newState;
   });

  }

For case 3, you made a little mistake by making result an object instead of an array. Change the {} to [] and it should work fine, like this.

const case3 = () => {
   const newItem = {id:3,text:'Learn C#'};

   setTodos((prevState) => {
    let result = [...prevState, newItem ] ;
    return result;
   });

  }


问:
How do you set a value to null with org.json.JSONObject in java?
How do you set a value to null with org.json.JSONObject in java? I can certainly read if a value is null by using isNull - but it seems like when I put null, it just ignores me:</p>

```<code>JSONObject o = new JSONObject();
o.put("key",null);
o.isNull("key"); // returns true, buuuut...
o.has("key");    // returns false
o.isNull("somethingIHaventSetAtAll");    // also returns true, unfortunately
</code>```

答:
Create a Utility Class or if you already have an existing one just create this utility method in it.

```<code> class JsonObjectUtility{
           public static Object getJSONObjectValue(Object value)  {
              return value == null ? "null" : value;
           }
 }
</code>```

then pass all input through this utility before passing it to the JSONObject put method as below: (i will use the code sample in the question)

```<code>JSONObject o = new JSONObject();
o.put("key", JsonObjectUtility.getJSONObjectValue(null) );
</code>```

This shall print a json string as below

{ "key" : null }

Body:
How do you set a value to null with org.json.JSONObject in java? I can certainly read if a value is null by using isNull - but it seems like when I put null, it just ignores me:

JSONObject o = new JSONObject();
o.put("key",null);
o.isNull("key"); // returns true, buuuut...
o.has("key");    // returns false
o.isNull("somethingIHaventSetAtAll");    // also returns true, unfortunately

Body:
Create a Utility Class or if you already have an existing one just create this utility method in it.

 class JsonObjectUtility{
           public static Object getJSONObjectValue(Object value)  {
              return value == null ? "null" : value;
           }
 }

then pass all input through this utility before passing it to the JSONObject put method as below: (i will use the code sample in the question)

JSONObject o = new JSONObject();
o.put("key", JsonObjectUtility.getJSONObjectValue(null) );

This shall print a json string as below

{ "key" : null }


问:
React Native - FBReactNativeSpec Command PhaseScriptExecution failed with a nonzero exit code
I am using a MacBook Pro with

M1 chip

MacOS Big Sur

Xcode Version 13.2.1

node v14.17.5

I wanted to follow this tutorial to set up a new React Native project called AwesomeProject https://reactnative.dev/docs/environment-setup the section with React Native CLI Quickstart.

When I try to run the app in terminal by typing: npx react-native run-ios
my build fails with the following error:

PhaseScriptExecution [CP-User]\ Generate\ Specs /Users/thomashuber/Library/Developer/Xcode/DerivedData/AwesomeProject-aprperxvqrezbfeyvousbagyesvr/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBReactNativeSpec.build/Script-5F4C70EF7D90A5A5BDAEB404279F232A.sh (in target 'FBReactNativeSpec' from project 'Pods')
(1 failure)

When I try to run it in Xcode either on a simulator or on an iPhone device I get the following error in FBReactNativeSpec:

Command PhaseScriptExecution failed with a nonzero exit code

I run it with

```<code>/bin/sh -c /Users/thomashuber/Library/Developer/Xcode/DerivedData/AwesomeProject-aprperxvqrezbfeyvousbagyesvr/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBReactNativeSpec.build/Script-5F4C70EF7D90A5A5BDAEB404279F232A.sh
</code>```

I restarted my MacBook, I deleted the project and tried it again. I cleaned the project in Xcode but none of it helps. I suspect that it is due the M1 chip of my MacBook.

答:
I managed to get rid of the FBReactNativeSpec error by editing the Project settings.

Try the following:

In Xcode select your app's project and then select the target.

In Terminal enter the following command to find out the path of your node installation:

which node

This should give you a path. Something like:

/Users/thomashuber/.nvm/versions/node/v16.14.0/bin/node

Copy this path.

In Xcode with the target selected click on Build Phases and open Bundle React Native code and images

Replace NODE_BINARY=node. Instead of node enter the path that you have copied so that it is something like this NODE_BINARY=/Users/thomashuber/.nvm/versions/node/v16.14.0/bin/node

Body:
I am using a MacBook Pro with

M1 chip

MacOS Big Sur

Xcode Version 13.2.1

node v14.17.5

I wanted to follow this tutorial to set up a new React Native project called AwesomeProject https://reactnative.dev/docs/environment-setup the section with React Native CLI Quickstart.

When I try to run the app in terminal by typing: npx react-native run-ios
my build fails with the following error:

PhaseScriptExecution [CP-User]\ Generate\ Specs /Users/thomashuber/Library/Developer/Xcode/DerivedData/AwesomeProject-aprperxvqrezbfeyvousbagyesvr/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBReactNativeSpec.build/Script-5F4C70EF7D90A5A5BDAEB404279F232A.sh (in target 'FBReactNativeSpec' from project 'Pods')
(1 failure)

When I try to run it in Xcode either on a simulator or on an iPhone device I get the following error in FBReactNativeSpec:

Command PhaseScriptExecution failed with a nonzero exit code

I run it with

/bin/sh -c /Users/thomashuber/Library/Developer/Xcode/DerivedData/AwesomeProject-aprperxvqrezbfeyvousbagyesvr/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBReactNativeSpec.build/Script-5F4C70EF7D90A5A5BDAEB404279F232A.sh

I restarted my MacBook, I deleted the project and tried it again. I cleaned the project in Xcode but none of it helps. I suspect that it is due the M1 chip of my MacBook.


答: If you are stringifying your json, you will not be able to take data from it, because it will serve as a whole string not as an object.</p>

Title: Unable to render {message} object in the Chrome Console


问:
Is it possible to alter Math Equations in a loop?
Take this array of math expressions, which are NOT strings:

```<code>let eqs = [ 1+n, 2+n, 3+n]
</code>```

Is it possible to loop through these equations and modify them WITHOUT evaluating them in javascript somehow?

```<code>eqs.map(eq => eq + 1)
</code>```

...and return this:

```<code>// [ 1+n+1, 2+n+1, 3+n+1]
</code>```

Is something like that even possible at all? Doesn't have to be .map() just using that as an example. Doesn't have to be that syntax, i just can't imagine what the syntax for something like that might be is all...

Been googling around but I haven't found much yet...but I am getting the feeling that this might NOT be possible...is that the case?

Thank you for any assistance :-)

答:
You can use Template literals (Template strings)

Demo :

let eqs = ['1+n', '2+n', '3+n'];

let res = eqs.map(eq => `${eq}+1`);

console.log(res);```

Body:
Take this array of math expressions, which are NOT strings:

let eqs = [ 1+n, 2+n, 3+n]

Is it possible to loop through these equations and modify them WITHOUT evaluating them in javascript somehow?

eqs.map(eq => eq + 1)

...and return this:

// [ 1+n+1, 2+n+1, 3+n+1]

Is something like that even possible at all? Doesn't have to be .map() just using that as an example. Doesn't have to be that syntax, i just can't imagine what the syntax for something like that might be is all...

Been googling around but I haven't found much yet...but I am getting the feeling that this might NOT be possible...is that the case?

Thank you for any assistance :-)


问:
How to use C++20 concepts to do different things based on return type of a function?
I want to make a generic print(x) function, which behaves different for different types.

What I have so far works for all container types, including the one I wrote myself. However, either the "wrong" function is getting called or it won't compile due to ambiguity.

Here is my code:

#include <iostream>
#include <concepts>

class Container
{
    int x, y, z;
public:
    Container(int a, int b, int c) : x(a), y(b), z(c) {}
    Container() : x(0), y(0), z(0) {}
    std::size_t size() const { return 3; }
    const int& operator[] (std::size_t index) const { if(index == 0) return x; else if(index == 1) return y; else return z; }
    int& operator[] (std::size_t index) { if(index == 0) return x; else if(index == 1) return y; else return z; }
};

template<typename T>
concept printable_num = requires (T t, std::size_t s)
{
    { t.size() } -> std::convertible_to<std::size_t>;
    { t[s] } -> std::same_as<int&>;
};
template<printable_num T>
void print(const T& t) {
    std::size_t i = 0;
    for(;i < t.size() - 1; i++)
        std::cout << t[i] << ", ";
    std::cout << t[i] << std::endl;
}

template<typename T>
concept printable = requires (T t, std::size_t s)
{
    { t.size() } -> std::convertible_to<std::size_t>;
    { t[s] } -> std::convertible_to<char>;
};

template<printable T>
void print(const T& t) {
    std::size_t i = 0;
    for(;i < t.size() - 1; i++)
        std::cout << t[i];
    std::cout << t[i] << std::endl;
}

int main()
{
    Container c{1, 2, 3};
    print(c);
    Container empty;
    print(empty);
    std::string s{"this is some string"};
    print(s);
    return 0;
}
```

As you can see, I want to print a separator if the type returned from operator[] is int&. This does not compile due to ambiguity.

Is there a way to make this compile and to get me where I want (call the print function without the separator for std::string and the one with separator for my own Container type)?

答:
Given an integer (or lvalue to one), would you not agree that it is convertible to a char? The constraints check exactly what you have them check for the types in your question.

One way to tackle it would be by constraint subsumption. Meaning (in a very hand wavy fashion) that if your concepts are written as a conjugation (or disjunction) of the same basic constraints, a compiler can normalize the expression to choose the "more specialized one". Applying it to your example..

```<code>template<typename T>
concept printable = requires (T t, std::size_t s)
{
    { t.size() } -> std::convertible_to<std::size_t>;
    { t[s] } -> std::convertible_to<char>;
};

template<typename T>
concept printable_num = printable<T> && requires (T t, std::size_t s)
{
    { t[s] } -> std::same_as<int&>;
};
</code>```

Note how we used printable to define printable_num as the "more specific" concept. Running this example, we get the output you are after.

Body:
I want to make a generic print(x) function, which behaves different for different types.

What I have so far works for all container types, including the one I wrote myself. However, either the "wrong" function is getting called or it won't compile due to ambiguity.

Here is my code:

#include <iostream>
#include <concepts>

class Container
{
    int x, y, z;
public:
    Container(int a, int b, int c) : x(a), y(b), z(c) {}
    Container() : x(0), y(0), z(0) {}
    std::size_t size() const { return 3; }
    const int& operator[] (std::size_t index) const { if(index == 0) return x; else if(index == 1) return y; else return z; }
    int& operator[] (std::size_t index) { if(index == 0) return x; else if(index == 1) return y; else return z; }
};

template<typename T>
concept printable_num = requires (T t, std::size_t s)
{
    { t.size() } -> std::convertible_to<std::size_t>;
    { t[s] } -> std::same_as<int&>;
};
template<printable_num T>
void print(const T& t) {
    std::size_t i = 0;
    for(;i < t.size() - 1; i++)
        std::cout << t[i] << ", ";
    std::cout << t[i] << std::endl;
}

template<typename T>
concept printable = requires (T t, std::size_t s)
{
    { t.size() } -> std::convertible_to<std::size_t>;
    { t[s] } -> std::convertible_to<char>;
};

template<printable T>
void print(const T& t) {
    std::size_t i = 0;
    for(;i < t.size() - 1; i++)
        std::cout << t[i];
    std::cout << t[i] << std::endl;
}

int main()
{
    Container c{1, 2, 3};
    print(c);
    Container empty;
    print(empty);
    std::string s{"this is some string"};
    print(s);
    return 0;
}

As you can see, I want to print a separator if the type returned from operator[] is int&. This does not compile due to ambiguity.

Is there a way to make this compile and to get me where I want (call the print function without the separator for std::string and the one with separator for my own Container type)?

Body:
Given an integer (or lvalue to one), would you not agree that it is convertible to a char? The constraints check exactly what you have them check for the types in your question.

One way to tackle it would be by constraint subsumption. Meaning (in a very hand wavy fashion) that if your concepts are written as a conjugation (or disjunction) of the same basic constraints, a compiler can normalize the expression to choose the "more specialized one". Applying it to your example..

template<typename T>
concept printable = requires (T t, std::size_t s)
{
    { t.size() } -> std::convertible_to<std::size_t>;
    { t[s] } -> std::convertible_to<char>;
};

template<typename T>
concept printable_num = printable<T> && requires (T t, std::size_t s)
{
    { t[s] } -> std::same_as<int&>;
};

Note how we used printable to define printable_num as the "more specific" concept. Running this example, we get the output you are after.


问:
Get starlette request body in the middleware context
I have such middleware

```<code>class RequestContext(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
        request_id = request_ctx.set(str(uuid4()))  # generate uuid to request
        body = await request.body()
        if body:
            logger.info(...)  # log request with body
        else:
            logger.info(...)  # log request without body

        response = await call_next(request)
        response.headers['X-Request-ID'] = request_ctx.get()
        logger.info("%s" % (response.status_code))
        request_ctx.reset(request_id)

        return response
</code>```

So the line body = await request.body() freezes all requests that have body and I have 504 from all of them. How can I safely read the request body in this context? I just want to log request parameters.

答:
If you only want to read request parameters, best solution i found was to implement a "route_class" and add it as arg when creating the fastapi.APIRouter, this is because parsing the request within the middleware is considered problematic
The intention behind the route handler from what i understand is to attach exceptions handling logic to specific routers, but since it's being invoked before every route call, you can use it to access the Request arg

Fastapi documentation

You could do something as follows:

```<code>class MyRequestLoggingRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            body = await request.body()
            if body:
               logger.info(...)  # log request with body
            else:
               logger.info(...)  # log request without body
            try:

                return await original_route_handler(request)
            except RequestValidationError as exc:
               detail = {"errors": exc.errors(), "body": body.decode()}
               raise HTTPException(status_code=422, detail=detail)

        return custom_route_handler
</code>```

Body:
I have such middleware

class RequestContext(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
        request_id = request_ctx.set(str(uuid4()))  # generate uuid to request
        body = await request.body()
        if body:
            logger.info(...)  # log request with body
        else:
            logger.info(...)  # log request without body

        response = await call_next(request)
        response.headers['X-Request-ID'] = request_ctx.get()
        logger.info("%s" % (response.status_code))
        request_ctx.reset(request_id)

        return response

So the line body = await request.body() freezes all requests that have body and I have 504 from all of them. How can I safely read the request body in this context? I just want to log request parameters.

Body:
If you only want to read request parameters, best solution i found was to implement a "route_class" and add it as arg when creating the fastapi.APIRouter, this is because parsing the request within the middleware is considered problematic
The intention behind the route handler from what i understand is to attach exceptions handling logic to specific routers, but since it's being invoked before every route call, you can use it to access the Request arg

Fastapi documentation

You could do something as follows:

class MyRequestLoggingRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            body = await request.body()
            if body:
               logger.info(...)  # log request with body
            else:
               logger.info(...)  # log request without body
            try:

                return await original_route_handler(request)
            except RequestValidationError as exc:
               detail = {"errors": exc.errors(), "body": body.decode()}
               raise HTTPException(status_code=422, detail=detail)

        return custom_route_handler


问:
Customising ClassWizard in VS2010
With the advent of VS2010 SP1, I'm once again looking at moving off VS2008 to the newer version.  The main reason for this, is that as a long time VC6 user, I find ClassWizard to be a great productivity tool, and welcome its long awaited return.  However, while ClassWizard works ok, I can't find any equivalent of the .CLW file necessary for creating custom DDX routines.  So for example, when regularly dealing with inputting lengths in VC6, I would have the following lines in my CLW file

```<code>ExtraDDXCount=1
ExtraDDX1=E;;Length;double;0.0;Length;Atlas:Use to store lengths;;&Length;s
</code>```

which would let add length variables from ClassWizard.  Any idea if this is still supported in VS2010, or are we another year away from catching up with VC6?

答: I believe the answer is "Not with VS2010".  I would like to see the ClassWizard support virtual methods from custom classes, but apparently it has a undocumented database of classes it knows about, or can figure out.</p>

Title: Customising ClassWizard in VS2010

Body:
With the advent of VS2010 SP1, I'm once again looking at moving off VS2008 to the newer version.  The main reason for this, is that as a long time VC6 user, I find ClassWizard to be a great productivity tool, and welcome its long awaited return.  However, while ClassWizard works ok, I can't find any equivalent of the .CLW file necessary for creating custom DDX routines.  So for example, when regularly dealing with inputting lengths in VC6, I would have the following lines in my CLW file

ExtraDDXCount=1
ExtraDDX1=E;;Length;double;0.0;Length;Atlas:Use to store lengths;;&Length;s

which would let add length variables from ClassWizard.  Any idea if this is still supported in VS2010, or are we another year away from catching up with VC6?


问:
How can I configure the 'staticcheck' linter in Visual Studio Code?
I installed staticcheck, but it doesn't tell me any problems in my Visual Studio Code.

I configured my linter to use staticcheck and I looked everywhere on the Internet. It still doesn't work.

Here is a part of my settings.json file:

{
  "go.formatTool": "goimports",
  "go.useLanguageServer": true,
  "go.lintTool": "staticcheck",
  "go.lintFlags": [],
  "go.testFlags": ["-v"],
  "go.toolsManagement.autoUpdate": true,
  "editor.codeActionsOnSave": { "source.fixAll.eslint": true }
}
```

I already tried to add "-check=all" on the go.lintFlags. I reloaded my Visual Studio Code, but it still doesn't work.

When I checked the official website they talk about staticcheck.conf, but I don't get it since there are multiple files named staticcheck.conf on my system.

答:
You don't need "go.lintTool": "staticcheck", because, this is (staticcheck) default linting tool in vscode-go.

If you have language serve enabled, you need to turn staticcheck explicitly with

```<code>"gopls": { "ui.diagnostic.staticcheck": true }.
</code>```

As alternative, you can set up golangci-lint as your linter and turn staticcheck in it.

Body:
I installed staticcheck, but it doesn't tell me any problems in my Visual Studio Code.

I configured my linter to use staticcheck and I looked everywhere on the Internet. It still doesn't work.

Here is a part of my settings.json file:

{
  "go.formatTool": "goimports",
  "go.useLanguageServer": true,
  "go.lintTool": "staticcheck",
  "go.lintFlags": [],
  "go.testFlags": ["-v"],
  "go.toolsManagement.autoUpdate": true,
  "editor.codeActionsOnSave": { "source.fixAll.eslint": true }
}

I already tried to add "-check=all" on the go.lintFlags. I reloaded my Visual Studio Code, but it still doesn't work.

When I checked the official website they talk about staticcheck.conf, but I don't get it since there are multiple files named staticcheck.conf on my system.

Body:
You don't need "go.lintTool": "staticcheck", because, this is (staticcheck) default linting tool in vscode-go.

If you have language serve enabled, you need to turn staticcheck explicitly with

"gopls": { "ui.diagnostic.staticcheck": true }.

As alternative, you can set up golangci-lint as your linter and turn staticcheck in it.


问:
Change admin password in Gitea
I created an admin user with a password, that contains a special character. Installation of Gitea was successful, but I can't login. I can't get new password, because it says:

Sorry, Register Mail Confirmation has been disabled.

I tried command gitea admin change-password, but command is not recognized.

答:
For NixOS users, it's a bit more complicated:

```<code>su
su gitea
nix-shell -p gitea
gitea admin user change-password -c /var/lib/gitea/custom/conf/app.ini -u user-name -p new-pwd
</code>```

(tested on Gitea version 1.15.6)

Title: Change admin password in Gitea

Body:
For NixOS users, it's a bit more complicated:

su
su gitea
nix-shell -p gitea
gitea admin user change-password -c /var/lib/gitea/custom/conf/app.ini -u user-name -p new-pwd

(tested on Gitea version 1.15.6)