问:
npm run build prod not working with UglifyJs
I am implementing a project with vue js.

When I perform build production with the npm run build command, the UglifyJs error appears as follows:

```<code>ERROR in app/0.4743e576731afa06aec6.chunk.js from UglifyJs
Unexpected token: keyword «const» [./node_modules/vue2-editor/dist/vue2-editor.esm.js:876,0][app/0.4743e576731afa06aec6.chunk.js:141928,0]
</code>```

As I found out on google, because UglifyJs cannot build with ES6. However, I still do not know how to fix it.

I get the answer is to use TerserWebpackPlugin. However, when I tried to run with TerserWebpackPlugin, the program did not seem to respond. I felt like it was running without a stop.

This is config webpack.prod

webpack.prod.js

```<code>'use strict';
const utils = require('./vue.utils');
const webpack = require('webpack');
const config = require('../config');
const merge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.common');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const jhiUtils = require('./utils.js');

const env = require('../config/prod.env');

const webpackConfig = merge(baseWebpackConfig, {
  mode: 'production',
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  entry: {
    global: './src/main/webapp/content/scss/global.scss',
    main: './src/main/webapp/app/main'
  },
  output: {
    path: jhiUtils.root('target/classes/static/'),
    filename: 'app/[name].[hash].bundle.js',
    chunkFilename: 'app/[id].[hash].chunk.js'
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
      chunkFilename: '[id].css'
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({}),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      template: './src/main/webapp/index.html',
      chunks: ['vendors', 'main', 'global'],
      chunksSortMode: 'manual',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin()
  ]
});

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin');

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp('\\.(' + config.build.productionGzipExtensions.join('|') + ')$'),
      threshold: 10240,
      minRatio: 0.8
    })
  );
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = webpackConfig;

</code>```

答: JHipster Vue.js blueprint has been updated 16 days ago to replace uglifyjs by terser so I suppose you generated your project with an older version, try upgrading blueprint to 1.8.1 or copy what they did in https://github.com/jhipster/jhipster-vuejs/commit/ef369bb66643cc193aeb2868fc60e557252f6669</p>

Body:
I am implementing a project with vue js.

When I perform build production with the npm run build command, the UglifyJs error appears as follows:

ERROR in app/0.4743e576731afa06aec6.chunk.js from UglifyJs
Unexpected token: keyword «const» [./node_modules/vue2-editor/dist/vue2-editor.esm.js:876,0][app/0.4743e576731afa06aec6.chunk.js:141928,0]

As I found out on google, because UglifyJs cannot build with ES6. However, I still do not know how to fix it.

I get the answer is to use TerserWebpackPlugin. However, when I tried to run with TerserWebpackPlugin, the program did not seem to respond. I felt like it was running without a stop.

This is config webpack.prod

webpack.prod.js

'use strict';
const utils = require('./vue.utils');
const webpack = require('webpack');
const config = require('../config');
const merge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.common');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const jhiUtils = require('./utils.js');

const env = require('../config/prod.env');

const webpackConfig = merge(baseWebpackConfig, {
  mode: 'production',
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  entry: {
    global: './src/main/webapp/content/scss/global.scss',
    main: './src/main/webapp/app/main'
  },
  output: {
    path: jhiUtils.root('target/classes/static/'),
    filename: 'app/[name].[hash].bundle.js',
    chunkFilename: 'app/[id].[hash].chunk.js'
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
      chunkFilename: '[id].css'
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({}),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      template: './src/main/webapp/index.html',
      chunks: ['vendors', 'main', 'global'],
      chunksSortMode: 'manual',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin()
  ]
});

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin');

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp('\\.(' + config.build.productionGzipExtensions.join('|') + ')$'),
      threshold: 10240,
      minRatio: 0.8
    })
  );
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = webpackConfig;


来源: stackexchange

问:
Question regarding multi-threaded environment of servlet
If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?

Do they have a local copy of the following variables?

1) private/protected/public final Semaphore permits = new Semaphore(50);

2) private/protected/public final static Semaphore permits = new Semaphore(50);

3) private/protected/public Semaphore permits = new Semaphore(50);

4) private/protected/public static Semaphore permits = new Semaphore(50);

How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.

答: Each servlet is executed in a new thread.. Technically, there is worker threads that waits for requests, when a http request comes to servlet container, this one instantiates a new servlet (depending to servlets defined in web.xml) and passes it to the worker thread. So logically each variable is not seen by other servlet instances. Now if you want to make your variable visible by all servlet instances you have to define it as static so it will be shared between all instances of the same class.</p>

ContentLicense: CC BY-SA 3.0


问:
So, Unity and Vs CODE are not working together, I have updated all everything, Downloaded every version and its not working
Ok, Im tryna make a 2D game in unity because im bored, and everything else is fine, Sprites, Physics, But when I try to make a new script it tells me too re download vs or smthing and this has been happening for WEEKS and I just really want to get this too work, And yes Ik i have asked this before but it didnt work.</p>

答:
You can easily change your IDE:

Go to Preferences -> external tools -> and change the default editor to visual studio code

There is an assets that you can download in the assets manager.

If this does not work, just open your scripts by opening the folder in VS Code.

ContentLicense: CC BY-SA 4.0


问:
Pandas rolling sum that includes previous and coming days
A beginner, basically, trying to find a rolling sum that includes today, last 4 days, and coming days, in this case 1 next day (tomorrow).

```<code>            Test
1995-07-01    1
1995-07-02    0
1995-07-03    0
1995-07-04    1
1995-07-05    0
1995-07-06    0
1995-07-07    0
1995-07-08    0
1995-07-09    0
1995-07-10    0
1995-07-11    1
</code>```

Got rolling sum of 'today' and past 4 days to work
df['test'].rolling(5).sum()

```<code>1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    2.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    1.0
1995-07-09    0.0
1995-07-10    0.0
1995-07-11    1.0
</code>```

But including the next day's value into this sum is difficult for me, what I want is the output 1995-07-10 to show 1 since it needs to include 'tomorrow' (since 1995-07-11 is a 1 in the Test data)

答:
Use

```<code>pd.Series(df.Test.iloc[0]).append(df.Test.shift(-1)) \
                          .rolling(6, min_periods=1).sum().iloc[1:].astype(int)
</code>```

resulting (the original series is here only for a comfortable quick check)

```<code>--- Result ---                -- (Original) --

           Test                           Test
1995-07-01    1               1995-07-01     1
1995-07-02    1               1995-07-02     0
1995-07-03    2               1995-07-03     0
1995-07-04    2               1995-07-04     1
1995-07-05    2               1995-07-05     0
1995-07-06    1               1995-07-06     0
1995-07-07    1               1995-07-07     0
1995-07-08    1               1995-07-08     0
1995-07-09    0               1995-07-09     0
1995-07-10    1               1995-07-10     0
1995-07-11    1               1995-07-11     1
</code>```

The explanation:

We want to shift the df.Test series 1 position up to include the next day ("tomorrow") into a rolling window, but it has a bad consequence — the first member of the original series disappears.

So we save it (df.Test.iloc[0]) in the form of 1-element series (pd.Series(df.Test.iloc[0])).

Only then we perform the intended shift of the original series (df.Test.shift(-1)).

The resulting shifted series we append to previously saved 1-element series (pd.Series(df.Test.iloc[0]).append(df.Test.shift(-1))).

Now we are ready to create a rolling window with size of 6 (4 days ago + today + tomorrow) and with minimal period of 1 to prevent arising NaN values (.rolling(6, min_periods=1)).

The final steps are now obvious:

applying the .sum() method,

drop the first element (.iloc[1:]), which was prepended to the shifted series only for rolling window calculation,

possibly convert the data type of the resulting series back to the integer type (.astype(int))

Body:
A beginner, basically, trying to find a rolling sum that includes today, last 4 days, and coming days, in this case 1 next day (tomorrow).

            Test
1995-07-01    1
1995-07-02    0
1995-07-03    0
1995-07-04    1
1995-07-05    0
1995-07-06    0
1995-07-07    0
1995-07-08    0
1995-07-09    0
1995-07-10    0
1995-07-11    1

Got rolling sum of 'today' and past 4 days to work
df['test'].rolling(5).sum()

1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    2.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    1.0
1995-07-09    0.0
1995-07-10    0.0
1995-07-11    1.0

But including the next day's value into this sum is difficult for me, what I want is the output 1995-07-10 to show 1 since it needs to include 'tomorrow' (since 1995-07-11 is a 1 in the Test data)

Body:
Use

pd.Series(df.Test.iloc[0]).append(df.Test.shift(-1)) \
                          .rolling(6, min_periods=1).sum().iloc[1:].astype(int)

resulting (the original series is here only for a comfortable quick check)

--- Result ---                -- (Original) --

           Test                           Test
1995-07-01    1               1995-07-01     1
1995-07-02    1               1995-07-02     0
1995-07-03    2               1995-07-03     0
1995-07-04    2               1995-07-04     1
1995-07-05    2               1995-07-05     0
1995-07-06    1               1995-07-06     0
1995-07-07    1               1995-07-07     0
1995-07-08    1               1995-07-08     0
1995-07-09    0               1995-07-09     0
1995-07-10    1               1995-07-10     0
1995-07-11    1               1995-07-11     1

The explanation:

We want to shift the df.Test series 1 position up to include the next day ("tomorrow") into a rolling window, but it has a bad consequence — the first member of the original series disappears.

So we save it (df.Test.iloc[0]) in the form of 1-element series (pd.Series(df.Test.iloc[0])).

Only then we perform the intended shift of the original series (df.Test.shift(-1)).

The resulting shifted series we append to previously saved 1-element series (pd.Series(df.Test.iloc[0]).append(df.Test.shift(-1))).

Now we are ready to create a rolling window with size of 6 (4 days ago + today + tomorrow) and with minimal period of 1 to prevent arising NaN values (.rolling(6, min_periods=1)).

The final steps are now obvious:

applying the .sum() method,

drop the first element (.iloc[1:]), which was prepended to the shifted series only for rolling window calculation,

possibly convert the data type of the resulting series back to the integer type (.astype(int))


问:
How to make specific options to appear in select menu?
I have two select fields in a program. Both select fields contain options with values 1 to 10. the code is as below:

<select id="noc">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select>

<select id="po">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select>```

I want to achieve the following effect using JavaScript :

(Only for example) If the user has selected the option 8 in the first select field (id="noc"), the options below 8 (i.e. 9 and 10) should not be visible in the second select field (id="po").

答:
You can try this, when the selected option first select (noc) changes, loop over the options in the second select (po) and hide its options whose values are greater than the value of the option selected in the first select (noc).

const noc = document.getElementById('noc');
const po = document.getElementById('po');

noc.addEventListener('change', (e) => {
  [...po.children].forEach(child => {
    if (Number(child.getAttribute('value')) > e.target.value) {
      return child.style.display = 'none'
    }
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="noc">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select><br/>

<!--Some text---->

<select id="po">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select></code>```

Body:
I have two select fields in a program. Both select fields contain options with values 1 to 10. the code is as below:

<select id="noc">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select>

<select id="po">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select>

I want to achieve the following effect using JavaScript :

(Only for example) If the user has selected the option 8 in the first select field (id="noc"), the options below 8 (i.e. 9 and 10) should not be visible in the second select field (id="po").

Body:
You can try this, when the selected option first select (noc) changes, loop over the options in the second select (po) and hide its options whose values are greater than the value of the option selected in the first select (noc).

const noc = document.getElementById('noc');
const po = document.getElementById('po');

noc.addEventListener('change', (e) => {
  [...po.children].forEach(child => {
    if (Number(child.getAttribute('value')) > e.target.value) {
      return child.style.display = 'none'
    }
  })
});

<select id="noc">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select><br/>

<!--Some text---->

<select id="po">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
       <option value="9">9</option>
       <option value="10">10</option>
</select>


问:
Back button in navigation controller wont change to custom image
I have two VC, the first of which is embedded in a NC. My second VC is presented using a push segue from my first VC. In my second VC, I am trying to change the back button to a custom image I have, but it is still using the default image and text in the navigation bar.

viewDidLoad() in my second VC:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let back = UIImage(named: "back")
    self.navigationController!.navigationBar.backIndicatorImage = back
    self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = back
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)

    configureView()
}
</code>```

Why is the following not changing the back button in my second VC?

答:
You need to set it on the first view controller.

Calling the following code on your first view controller.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let back = UIImage(named: "back")
    self.navigationController!.navigationBar.backIndicatorImage = back
    self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = back
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)

    configureView()
}
</code>```

More details
https://sarunw.com/posts/how-to-change-back-button-image/
https://sarunw.com/posts/how-to-remove-text-from-uinavigationbar-back-button/

Body:
I have two VC, the first of which is embedded in a NC. My second VC is presented using a push segue from my first VC. In my second VC, I am trying to change the back button to a custom image I have, but it is still using the default image and text in the navigation bar.

viewDidLoad() in my second VC:

override func viewDidLoad() {
    super.viewDidLoad()

    let back = UIImage(named: "back")
    self.navigationController!.navigationBar.backIndicatorImage = back
    self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = back
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)

    configureView()
}

Why is the following not changing the back button in my second VC?

Body:
You need to set it on the first view controller.

Calling the following code on your first view controller.

override func viewDidLoad() {
    super.viewDidLoad()

    let back = UIImage(named: "back")
    self.navigationController!.navigationBar.backIndicatorImage = back
    self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = back
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)

    configureView()
}

More details
https://sarunw.com/posts/how-to-change-back-button-image/
https://sarunw.com/posts/how-to-remove-text-from-uinavigationbar-back-button/


问:
Filling in missing data in SQL table with overlapping groups
I have some analytics data where a single activity stream for visitor our a website, where for part of the trace there is an id and later on the identifier is a different value. How can I using SQL pad the data so that it is complete.

```<code> id1 | id2 |   timestamp
-----+-----+---------------------
null |   3 |  123450
null |   3 |  123451
null |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |null |  123455
   5 |null |  123456
   5 |null |  123457
...
null |   8 |  123450
null |   8 |  123451
null |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |null |  123455
   9 |null |  123456
   9 |null |  123457
...
</code>```

The two sections above are part of the same group, and I know that because they essentially  some point stops recording the id2.

I want a query or sql and intermediate tables that would enabled me to populate the null values above so that I have:

```<code> id1 | id2 |   timestamp
-----+-----+---------------------
   5 |   3 |  123450
   5 |   3 |  123451
   5 |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |   3 |  123455
   5 |   3 |  123456
   5 |   3 |  123457
...
   9 |   8 |  123450
   9 |   8 |  123451
   9 |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |   8 |  123455
   9 |   8 |  123456
   9 |   8 |  123457
...
</code>```

答:
If we assume that id1 and id2 occur in unique pairs and each id is never with any other values, then you can simply use window functions:

```<code>select coalesce(id1, max(id1) over (partition by id2)) as id1,
       coalesce(id2, max(id2) over (partition by id1)) as id2,
       timestamp
from t;
</code>```

Without this assumption, the question is not well formed and does not have a specific answer.

Here is a db<>fiddle

Body:
I have some analytics data where a single activity stream for visitor our a website, where for part of the trace there is an id and later on the identifier is a different value. How can I using SQL pad the data so that it is complete.

 id1 | id2 |   timestamp
-----+-----+---------------------
null |   3 |  123450
null |   3 |  123451
null |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |null |  123455
   5 |null |  123456
   5 |null |  123457
...
null |   8 |  123450
null |   8 |  123451
null |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |null |  123455
   9 |null |  123456
   9 |null |  123457
...

The two sections above are part of the same group, and I know that because they essentially  some point stops recording the id2.

I want a query or sql and intermediate tables that would enabled me to populate the null values above so that I have:

 id1 | id2 |   timestamp
-----+-----+---------------------
   5 |   3 |  123450
   5 |   3 |  123451
   5 |   3 |  123452
   5 |   3 |  123453
   5 |   3 |  123454
   5 |   3 |  123455
   5 |   3 |  123456
   5 |   3 |  123457
...
   9 |   8 |  123450
   9 |   8 |  123451
   9 |   8 |  123452
   9 |   8 |  123453
   9 |   8 |  123454
   9 |   8 |  123455
   9 |   8 |  123456
   9 |   8 |  123457
...

Body:
If we assume that id1 and id2 occur in unique pairs and each id is never with any other values, then you can simply use window functions:

select coalesce(id1, max(id1) over (partition by id2)) as id1,
       coalesce(id2, max(id2) over (partition by id1)) as id2,
       timestamp
from t;

Without this assumption, the question is not well formed and does not have a specific answer.

Here is a db<>fiddle


Title: Pandas rolling sum that includes previous and coming days

Body:
df['Tomorrow'] = df.shift(-1)
df['Previous'] = df['Test'].rolling(4).sum()
df.sum(axis=1)

Output

1995-07-01    1.0
1995-07-02    0.0
1995-07-03    1.0
1995-07-04    3.0
1995-07-05    1.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    0.0
1995-07-09    0.0
1995-07-10    1.0
1995-07-11    2.0

Or if you like the first 3 rows to have a value for previous 4 even if there were fewer than 4 days:

df['Previous'] = df['Test'].rolling(4, min_periods=1).sum()


答:
const max = 10;

var items = [...Array(max).keys()]

var noc = document.getElementById("noc");
var po = document.getElementById("po");

items.forEach(n => {
  var opt = document.createElement("select");
  opt.value = n;
  noc.appendChild(opt);
  po.appendChild(opt);
});

noc.addEventListener("change", e => {
  var selected = e.target.value;
  po.querySelectorAll("option").forEach((el, index) => {
    if (selected < index) {
      el.style.display = "visible";
    } else {
      el.style.display = "none";
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invisible {
  display: none;
}</code>```

<select id="noc">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>

<select id="po">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>```

Title: How to make specific options to appear in select menu?

Body:
const max = 10;

var items = [...Array(max).keys()]

var noc = document.getElementById("noc");
var po = document.getElementById("po");

items.forEach(n => {
  var opt = document.createElement("select");
  opt.value = n;
  noc.appendChild(opt);
  po.appendChild(opt);
});

noc.addEventListener("change", e => {
  var selected = e.target.value;
  po.querySelectorAll("option").forEach((el, index) => {
    if (selected < index) {
      el.style.display = "visible";
    } else {
      el.style.display = "none";
    }
  });
});

.invisible {
  display: none;
}

<select id="noc">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select><br/>

<!--Some text---->

<select id="po">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>


问:
If filename matches pattern do something (for-loop, case-statement)
The local file tree:

```<code>/pdf/Insurance.January.2020.pdf
/pdf/Insurance.February.2020.pdf
/pdf/Provider1.March.2020.pdf
/pdf/Provider2.April.2020.pdf
</code>```

The remote file tree:

```<code>/invoice/Insurance/2019/January/Insurance.January.2019.pdf
/invoice/Insurance/2020/February/Insurance.February.2020.pdf
/invoice/Provider1/.....
</code>```

What I want:
I want to (r)sync my local PDF-files with the remote folders by matching patterns like Name, Year and maybe Month.

I thought I can solve this with a for-loop and case-statements:

```<code>for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME=${FILE##*/}          # cut only filename
    case "$FILENAME" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done
</code>```

But now I think this is not the fastest way because I've to write a lot of lines to find a match. And I also need to "re-match" Year and Month.

Has someone another idea? Thanks!

答:
You can split the file names using the read command.

```<code>for FILE in ../pdf/*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    IFS=. read kind month year ext <<< "${FILE#./pdf/}"

    case "$kind" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done
</code>```

"${FILE#./pdf/}" expands to the value of FILE, minus the leading ./pdf/

<<< feeds a string to the standard input of a command.

read takes a line of input, performs word-splitting based on the first character of the value of IFS (here, a .), and puts resulting word each variable whose name is passed as an argument.

So if FILE=./pdf/Insurance.January.2020.pdf, then

```<code>IFS=. read kind month year ext <<< "${FILE#./pdf/}"
</code>```

feeds the string Insurance.Januray.2020.pdf to read, which then performs the assignments

```<code>kind=Insurance
month=January
year=2020
ext=pdf
</code>```

Body:
The local file tree:

/pdf/Insurance.January.2020.pdf
/pdf/Insurance.February.2020.pdf
/pdf/Provider1.March.2020.pdf
/pdf/Provider2.April.2020.pdf

The remote file tree:

/invoice/Insurance/2019/January/Insurance.January.2019.pdf
/invoice/Insurance/2020/February/Insurance.February.2020.pdf
/invoice/Provider1/.....

What I want:
I want to (r)sync my local PDF-files with the remote folders by matching patterns like Name, Year and maybe Month.

I thought I can solve this with a for-loop and case-statements:

for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME=${FILE##*/}          # cut only filename
    case "$FILENAME" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done

But now I think this is not the fastest way because I've to write a lot of lines to find a match. And I also need to "re-match" Year and Month.

Has someone another idea? Thanks!

Body:
You can split the file names using the read command.

for FILE in ../pdf/*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    IFS=. read kind month year ext <<< "${FILE#./pdf/}"

    case "$kind" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done

"${FILE#./pdf/}" expands to the value of FILE, minus the leading ./pdf/

<<< feeds a string to the standard input of a command.

read takes a line of input, performs word-splitting based on the first character of the value of IFS (here, a .), and puts resulting word each variable whose name is passed as an argument.

So if FILE=./pdf/Insurance.January.2020.pdf, then

IFS=. read kind month year ext <<< "${FILE#./pdf/}"

feeds the string Insurance.Januray.2020.pdf to read, which then performs the assignments

kind=Insurance
month=January
year=2020
ext=pdf


问:
ASP.NET Core 3.1 HttpContext.Connection.ClientCertificate or HttpContext.Connection.GetClientCertificateAsync?
I am a bit confused about which I should be using. In Microsoft.AspNetCore.HttpAbstractions, I am seeing that ClientCertificate is a property of ConnectionInfo, while GetClientCertificateAsync is method of ConnectionInfo. Both are publicly accessible, and I don't see any guidance on which one I should actually be using. Is there one that is generally preferred over the other?

答:
There seems that there is no difference between the two. They both return X509Certificate2.

source code for ClientCertificate

source code for GetClientCertificateAsync

The only difference is that you can await the GetClientCertificateAsync because it returnes a Task<X509Certificate2>and that it accepts a cancellation token.(documentation)

```<code>var certificate = await HttpContext.Connection.GetClientCertificateAsync();
</code>```

or

```<code>var certificate = await HttpContext.Connection.GetClientCertificateAsync(cancellationToken);
</code>```

Body:
There seems that there is no difference between the two. They both return X509Certificate2.

source code for ClientCertificate

source code for GetClientCertificateAsync

The only difference is that you can await the GetClientCertificateAsync because it returnes a Task<X509Certificate2>and that it accepts a cancellation token.(documentation)

var certificate = await HttpContext.Connection.GetClientCertificateAsync();

or

var certificate = await HttpContext.Connection.GetClientCertificateAsync(cancellationToken);


问:
map over nested array in react
I want to display the values of the following data which is received when i make fetch request:

data: Array

```<code>0: Object
  title: "html"
  description: Array
  name: "xyz"
  class: "c"

1: Object
  title: "html1"
  description: Array
  name: "xyz1"
  class: "c1"
</code>```

I have tried following code:

```<code><div>
  {
    data.map((item, index) => {
      <h1 key={index}>{item.title}/</h1>
      { item.description.map((c, i) =>
        <div>
          <h3 key={i}>{c.name} {c.class}</h3>
        </div>
      )}
    })
  }
</div>
</code>```

The above code displays only the title value. It's not displaying name and class value. Please help me.

答:
You were not returning anything to your data.map

```<code>{data.map((item, index) => {
              return (
                <div>
                  <h1 key={index}>{item.title}/</h1>
                  {item.description.map((c, i) => (
                    <div>
                      <h3 key={i}>
                        {c.name} {c.class1}
                      </h3>
                    </div>
                  ))}
                </div>
              );
            })}
</code>```

Title: map over nested array in react

Body:
I want to display the values of the following data which is received when i make fetch request:

data: Array

0: Object
  title: "html"
  description: Array
  name: "xyz"
  class: "c"

1: Object
  title: "html1"
  description: Array
  name: "xyz1"
  class: "c1"

I have tried following code:

  {
    data.map((item, index) => {

{item.title}/

      { item.description.map((c, i) =>

{c.name} {c.class}

      )}
    })
  }

The above code displays only the title value. It's not displaying name and class value. Please help me.

Body:
You were not returning anything to your data.map

{data.map((item, index) => {
              return (
                <div>
                  <h1 key={index}>{item.title}/</h1>
                  {item.description.map((c, i) => (
                    <div>
                      <h3 key={i}>
                        {c.name} {c.class1}
                      </h3>
                    </div>
                  ))}
                </div>
              );
            })}


问:
Visual Designer for JSF
I am using Netbeans for JSF development and...is there any Visual Web Designer plugin for JSF in Netbeans 6.9.1?

I am a sloppy guy, so without a visual aid for web development, I pretty much messed up my web UI.

答:
There are so many jsf component libraries which is one of the reasons that there will never be a decent designer. All there is content assist available in all major IDEs and IMHO that is all you need. Generated code from designers isnt worth much most of the time anyway.

There is Rich faces plugin from JBoss in Eclipse

There is OEOPE from Oracle where is JSF designer for Eclipse

Netbeans doesnt have any now

IntelliJ Idea doesnt have WYSIWYG either as far as I know

Title: Visual Designer for JSF


问:
Chain API calls with React hook useEffect
I need a solution for the following sequence:

The browser checks user's Geolocation (assuming he allows that) -> Longitude and Latitude are kept in state and used for 2 API calls -> Google Reverse Geolocation API checks for city name AND at the same time DarkSky API checks for the weather -> third API waits for results from previous calls and uses it as the query for the third, Unsplash API

Here's my code:

```<code>const [position, setPosition] = useState({ latitude: '50.049683', longitude: '19.944544' });
const [info, setInfo] = useState({ city: null, weather: null });
const [photos, setPhotos] = useState([]);

useEffect(() => {
    const fetchInfo = async () => {
      try {
        const [cityInfo, weatherInfo] = await Promise.all([
          axios.get(
            `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&language=en&result_type=locality&key=${GEO_ACC_KEY}`,
          ),
          axios.get(
         `https://api.darksky.net/forecast/${WEATHER_ACC_KEY}/${position.latitude},${position.longitude}?exclude=hourly,daily,alerts,flags`,
          ),
        ]);
        setInfo({
          city: cityInfo.data.results[0].address_components[0].short_name,
          weather: weatherInfo.data.currently.summary.toLowerCase(),
        });

        console.log('Info', info); // Results in {city: null, weather: 'null'}

        const photosData = await axios.get(
          `https://api.unsplash.com/search/photos?query=${info.weather}+${info.city}&page=1&per_page=8&client_id=${UNSPLASH_ACC_KEY}`,
        );

        setPhotos(photosData.data.results);

        console.log('Photos data from API call:', photosData); //Object based on query: "null+null"
        console.log('Photos:', photos); // Empty array
      } catch (err) {
        // Handling errors
      }
    };
    fetchInfo();
  }, []);

  console.log('Info outside axios get', info); // Results in object with city name and current weather
  console.log('photos outside axios get', photos); // Proper result I am looking for
</code>```

Right now the proper data is available ONLY outside useEffect. It does not provide the data for the third API call (right now Unsplash API call uses "null+null" as a query).

So I headed over to useEffect documentation and it says that a second parameter (an array) takes dependencies and updates when any of the state dependencies change.

I tried using it as follows:

```<code>useEffect(() => {
    const fetchInfo = async () => {
      //rest of the code
},
fetchInfo();
}, [info]);
</code>```

It uses proper keywords for the API call (city and weather, instead of null null) BUT creates an infinite API calls.

How do I fix that?

答:
State updates are not immediate and will reflect in the next render cycle.

Please check this post for more details on this: useState set method not reflecting change immediately

Also you must note that you want to chain API call and not call the entire useEffect again on info change. Adding info as a dependency will definitely lead to an infinite loop since info is being set inside the useEffect.

To solve your problem, You can instead use the value you set to state while making the api call

```<code>    const newInfo = {
      city: cityInfo.data.results[0].address_components[0].short_name,
      weather: weatherInfo.data.currently.summary.toLowerCase(),
    }

     setInfo(newInfo);

    console.log('Info', info); // Results in {city: null, weather: 'null'}

    const photosData = await axios.get(
      `https://api.unsplash.com/search/photos?query=${newInfo.weather}+${newInfo.city}&page=1&per_page=8&client_id=${UNSPLASH_ACC_KEY}`,
    );
</code>```

Body:
I need a solution for the following sequence:

The browser checks user's Geolocation (assuming he allows that) -> Longitude and Latitude are kept in state and used for 2 API calls -> Google Reverse Geolocation API checks for city name AND at the same time DarkSky API checks for the weather -> third API waits for results from previous calls and uses it as the query for the third, Unsplash API

Here's my code:

const [position, setPosition] = useState({ latitude: '50.049683', longitude: '19.944544' });
const [info, setInfo] = useState({ city: null, weather: null });
const [photos, setPhotos] = useState([]);

useEffect(() => {
    const fetchInfo = async () => {
      try {
        const [cityInfo, weatherInfo] = await Promise.all([
          axios.get(
            `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&language=en&result_type=locality&key=${GEO_ACC_KEY}`,
          ),
          axios.get(
         `https://api.darksky.net/forecast/${WEATHER_ACC_KEY}/${position.latitude},${position.longitude}?exclude=hourly,daily,alerts,flags`,
          ),
        ]);
        setInfo({
          city: cityInfo.data.results[0].address_components[0].short_name,
          weather: weatherInfo.data.currently.summary.toLowerCase(),
        });

        console.log('Info', info); // Results in {city: null, weather: 'null'}

        const photosData = await axios.get(
          `https://api.unsplash.com/search/photos?query=${info.weather}+${info.city}&page=1&per_page=8&client_id=${UNSPLASH_ACC_KEY}`,
        );

        setPhotos(photosData.data.results);

        console.log('Photos data from API call:', photosData); //Object based on query: "null+null"
        console.log('Photos:', photos); // Empty array
      } catch (err) {
        // Handling errors
      }
    };
    fetchInfo();
  }, []);

  console.log('Info outside axios get', info); // Results in object with city name and current weather
  console.log('photos outside axios get', photos); // Proper result I am looking for

Right now the proper data is available ONLY outside useEffect. It does not provide the data for the third API call (right now Unsplash API call uses "null+null" as a query).

So I headed over to useEffect documentation and it says that a second parameter (an array) takes dependencies and updates when any of the state dependencies change.

I tried using it as follows:

useEffect(() => {
    const fetchInfo = async () => {
      //rest of the code
},
fetchInfo();
}, [info]);

It uses proper keywords for the API call (city and weather, instead of null null) BUT creates an infinite API calls.

How do I fix that?

Body:
State updates are not immediate and will reflect in the next render cycle.

Please check this post for more details on this: useState set method not reflecting change immediately

Also you must note that you want to chain API call and not call the entire useEffect again on info change. Adding info as a dependency will definitely lead to an infinite loop since info is being set inside the useEffect.

To solve your problem, You can instead use the value you set to state while making the api call

    const newInfo = {
      city: cityInfo.data.results[0].address_components[0].short_name,
      weather: weatherInfo.data.currently.summary.toLowerCase(),
    }

     setInfo(newInfo);

    console.log('Info', info); // Results in {city: null, weather: 'null'}

    const photosData = await axios.get(
      `https://api.unsplash.com/search/photos?query=${newInfo.weather}+${newInfo.city}&page=1&per_page=8&client_id=${UNSPLASH_ACC_KEY}`,
    );


问:
How to call a TYPO3 custom viewhelper from a typoscript (.ts) file and receive a response from viewhelper?
I tried to call a custom viewhelper in TYPO3 9.5.9 from a typoscript file. But it is not working.
An example for viewhelper is given below:

```<code><?php
namespace MyVendor\BlogExample\ViewHelpers;

use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GravatarViewHelper extends AbstractViewHelper
{
   use CompileWithRenderStatic;

   public static function renderStatic(
       array $arguments,
       \Closure $renderChildrenClosure,
       RenderingContextInterface $renderingContext
   ) {
       return 'World';
   }
}
</code>```

How can I call this custom viewhelper from a typoscript (.ts) file and get a response ?

答:
I would suggest you extract the function that "does what the ViewHelper does" to a separate method and make it possible to call this method as a public method, and make it receive the PHP function arguments it requires (user email address, for example) *wrapped in an array $parameters.

This method can then be called from the ViewHelper as well as from TypoScript. The TypoScript would be something like:

```<code>lib.myGravatarObject = USER
lib.myGravatarObject.userFunc = MyVendor\ExtensionName\GravatarRenderer
lib.myGravatarObject.userEmail = foo@bar.com
</code>```

If you name the properties of the array $parameters the same as your ViewHelper arguments you can simply pass $this->arguments or $arguments from within the ViewHelper (the former if you are implementing render(), the latter if you are implementing renderStatic()). It also makes it more transparent that you use the same property names in TS as you would use for ViewHelper arguments.

Body:
I tried to call a custom viewhelper in TYPO3 9.5.9 from a typoscript file. But it is not working.
An example for viewhelper is given below:

<?php
namespace MyVendor\BlogExample\ViewHelpers;

use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GravatarViewHelper extends AbstractViewHelper
{
   use CompileWithRenderStatic;

   public static function renderStatic(
       array $arguments,
       \Closure $renderChildrenClosure,
       RenderingContextInterface $renderingContext
   ) {
       return 'World';
   }
}

How can I call this custom viewhelper from a typoscript (.ts) file and get a response ?

Body:
I would suggest you extract the function that "does what the ViewHelper does" to a separate method and make it possible to call this method as a public method, and make it receive the PHP function arguments it requires (user email address, for example) *wrapped in an array $parameters.

This method can then be called from the ViewHelper as well as from TypoScript. The TypoScript would be something like:

lib.myGravatarObject = USER
lib.myGravatarObject.userFunc = MyVendor\ExtensionName\GravatarRenderer
lib.myGravatarObject.userEmail = foo@bar.com

If you name the properties of the array $parameters the same as your ViewHelper arguments you can simply pass $this->arguments or $arguments from within the ViewHelper (the former if you are implementing render(), the latter if you are implementing renderStatic()). It also makes it more transparent that you use the same property names in TS as you would use for ViewHelper arguments.


问:
Typescript: Property 'leave' does not exist on type 'Socket'
I want to leave a room in socket.io with socket.leave("roomname"). Typescript claims that

"Property 'leave' does not exist on type 'Socket'"

.

Here is my code:

import io from "socket.io-client";
// leave chat
export async function leaveChat(conversationId){
  const socket: SocketIOClient.Socket = io(process.env.SERVER_URL);
  socket.leave(`chat@${conversationId}`);
}```

How to fix this?

答:
leave is function of on callback :

import io from "socket.io-client";

export async function leaveChat(conversationId){
  const socket: SocketIOClient.Socket = io(process.env.SERVER_URL);
  socket.on('connection', s => {
    s.leave(`chat@${conversationId}`);
  });
}
```

You can check the documentation about it : https://socket.io/docs/server-api/#socket-leave-room-callback

Body:
I want to leave a room in socket.io with socket.leave("roomname"). Typescript claims that

"Property 'leave' does not exist on type 'Socket'"

.

Here is my code:

import io from "socket.io-client";
// leave chat
export async function leaveChat(conversationId){
  const socket: SocketIOClient.Socket = io(process.env.SERVER_URL);
  socket.leave(`chat@${conversationId}`);
}

How to fix this?

Body:
leave is function of on callback :

import io from "socket.io-client";

export async function leaveChat(conversationId){
  const socket: SocketIOClient.Socket = io(process.env.SERVER_URL);
  socket.on('connection', s => {
    s.leave(`chat@${conversationId}`);
  });
}

You can check the documentation about it : https://socket.io/docs/server-api/#socket-leave-room-callback


问:
Python rq error while putting a class method on an RQ queue
I need to put a class method to on an RQ queue. But it gives an error

Here is the worker.py

```<code>import os

import redis
from rq import Worker, Queue, Connection

listen = ['high', 'default', 'low']

redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')

conn = redis.from_url(redis_url)

if __name__ == '__main__':
    with Connection(conn):
        worker = Worker(map(Queue, listen))
        worker.work()
</code>```

Here is the class in seperate file

```<code>import requests
import re

class Robots():
    def __init__(self, url):
        self.url = url

    def get_url(self):
        if self.url.endswith('/'):
            return self.url + "robots.txt"
        else:
            return self.url + "/robots.txt"

    def get_status_code(self):
        return requests.get(self.get_url()).status_code
</code>```

Here is the app.py

```<code>import time
from rq import Queue
from worker import conn
from rob import Robots
url = 'http://heroku.com'
q = Queue(connection=conn)

task = q.enqueue(Robots(url).get_status_code())
print (task.result)
time.sleep(4)
print (task.result)
</code>```

When I run the code, it gives an error.

```<code>File "app.py", line 8, in <module>
    task = q.enqueue(Robots(url).get_status_code())
  File "/home/atom/Desktop/Python/Tests/herokurq/lib/python3.8/site-packages/rq/queue.py", line 381, in enqueue
    depends_on, job_id, at_front, meta, args, kwargs) = Queue.parse_args(f, *args, **kwargs)
  File "/home/atom/Desktop/Python/Tests/herokurq/lib/python3.8/site-packages/rq/queue.py", line 353, in parse_args
    if not isinstance(f, string_types) and f.__module__ == '__main__':
</code>```

When I put simple function instead of class method - everything works fine. But I need to put the method. And it gives an error.

答:
I've found the problem
I should use task = q.enqueue(Robots(url).get_status_code)
instead of task = q.enqueue(Robots(url).get_status_code())</p>

Body:
I need to put a class method to on an RQ queue. But it gives an error

Here is the worker.py

import os

import redis
from rq import Worker, Queue, Connection

listen = ['high', 'default', 'low']

redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')

conn = redis.from_url(redis_url)

if __name__ == '__main__':
    with Connection(conn):
        worker = Worker(map(Queue, listen))
        worker.work()

Here is the class in seperate file

import requests
import re

class Robots():
    def __init__(self, url):
        self.url = url

    def get_url(self):
        if self.url.endswith('/'):
            return self.url + "robots.txt"
        else:
            return self.url + "/robots.txt"

    def get_status_code(self):
        return requests.get(self.get_url()).status_code

Here is the app.py

import time
from rq import Queue
from worker import conn
from rob import Robots
url = 'http://heroku.com'
q = Queue(connection=conn)

task = q.enqueue(Robots(url).get_status_code())
print (task.result)
time.sleep(4)
print (task.result)

When I run the code, it gives an error.

File "app.py", line 8, in <module>
    task = q.enqueue(Robots(url).get_status_code())
  File "/home/atom/Desktop/Python/Tests/herokurq/lib/python3.8/site-packages/rq/queue.py", line 381, in enqueue
    depends_on, job_id, at_front, meta, args, kwargs) = Queue.parse_args(f, *args, **kwargs)
  File "/home/atom/Desktop/Python/Tests/herokurq/lib/python3.8/site-packages/rq/queue.py", line 353, in parse_args
    if not isinstance(f, string_types) and f.__module__ == '__main__':

When I put simple function instead of class method - everything works fine. But I need to put the method. And it gives an error.


问:
How String data is converted for SVM machine learning algorithm
I have a dataset i.e.

TEXT	TYPE

100% free cashback 	spam

hello how are you 	ham

click on this link to get free sms plan	spam

     ```

I want to know how the SVM machine learning algorithm convert this text column to plot on a graph so that it can infer a line which separates spam from ham.

I know that spam and ham can be converted to 0,1 respectively. But how to convert this text column to numeric values ??

Note: I want the procedure. I want to do it manually using pen and paper, not code using some python library.

答:
Just so that we are on the same page:
You are looking for a procedure on how to solve Spam Vs. Ham email classification using pen and paper.

To start with the basics, the text data cannot be sent directly to the model,
1. we need to do data cleaning so that we extract multiple traits/features to in a matrix form ( 1 row = 1 email, 1 column = 1 feature) a feature/trait can be a word on any deep embeddings(Doc2Vec) of the email.
2. In the same way, we also create a target data which is (1 row saying 1 if spam and 0 if Ham email)
Once you have both the data, you can solve the SVM algorithm by hand with the assumption that all the columns are different axis in the N-dimensional data plane.

Body:
I have a dataset i.e.

TEXT	TYPE

100% free cashback 	spam

hello how are you 	ham

click on this link to get free sms plan	spam

I want to know how the SVM machine learning algorithm convert this text column to plot on a graph so that it can infer a line which separates spam from ham.

I know that spam and ham can be converted to 0,1 respectively. But how to convert this text column to numeric values ??

Note: I want the procedure. I want to do it manually using pen and paper, not code using some python library.


问:
footer hides when moves on next page
I have html structure like this

```<code><div data-role="page" data-theme="b">

    <div data-role="header" data-theme="b">
        <h1>header</h1>
    </div><!-- /header -->

    <div data-role="content" data-theme="b">
        <a href="#p2" data-role="button" data-icon="arrow-r" data-theme="b" data-iconpos="right">next pagey</a>
    </div><!-- /content -->

    <div data-role="footer" data-theme="b" data-position="fixed">
        <h1>Footer</h1>
    </div><!-- /footer -->

</div><!-- /page -->

<div id="p2" data-role="page" data-theme="b">

    <div data-role="header" data-theme="b">
        <h1>header</h1>
    </div><!-- /header -->

    <div data-role="content" data-theme="b">
        <h1>Content</h1>
    </div><!-- /content -->

    <div data-role="footer" data-theme="b" data-position="fixed">
        <h1>Content</h1>
    </div><!-- /footer -->

</div><!-- /page -->
</code>```

But when i click on next page and next page comes in with auto-added back btn in header, when I click on back button previous page appears but footer dissappears..

in FF working ok, but not in ipad simulator

答:
Getting fixed footers to work is a pain for the JQM team. I think it's just another little bug that is caused by unforseen circumstances. Well, nevermind...

A bit of insight:
Those darn mobile browsers have no support of fixed CSS positioning, so this is done with javascript and absolute position (and a ton of hacks - I bet)

This should already give you a clue...

If the behaviour isn't specific just to the emulator (quite possible!) and the problem remains after you fill the page with contents (I mean - finish writing the application) then all you need to do is to kickstart the code that repositions the footer. I'd do it like that:

```<code>$('div').live('pageshow',function(){ $(window).trigger('orientationchange') });
</code>```

The orientationchange event should work. You can also try resize if orientationchange causes any new problems.

Title: footer hides when moves on next page

Body:
I have html structure like this

header

        next pagey

Footer

header

Content

Content

But when i click on next page and next page comes in with auto-added back btn in header, when I click on back button previous page appears but footer dissappears..

in FF working ok, but not in ipad simulator

Body:
Getting fixed footers to work is a pain for the JQM team. I think it's just another little bug that is caused by unforseen circumstances. Well, nevermind...

A bit of insight:
Those darn mobile browsers have no support of fixed CSS positioning, so this is done with javascript and absolute position (and a ton of hacks - I bet)

This should already give you a clue...

If the behaviour isn't specific just to the emulator (quite possible!) and the problem remains after you fill the page with contents (I mean - finish writing the application) then all you need to do is to kickstart the code that repositions the footer. I'd do it like that:

$('div').live('pageshow',function(){ $(window).trigger('orientationchange') });

The orientationchange event should work. You can also try resize if orientationchange causes any new problems.


问:
Django get URL from address bar
I am a begginer with django and I am stuck in getting this to work, practically what I want is that the user types in the address bar http://website.com/example and then in Django I want to make a dynamic view where it checks the address and then redirects user to the correct page otherwise gives an error.

this is what I was trying but it might not be working..

urlpatterns = [
path("", views.index, name="index"),
path("<str:name>", views.example, name="example") ]
```

<p>and then in the <code>views.py</code> I want the following: </p>

<pre class="lang-py prettyprint-override"><code>def example(request, name):
    return render(request, "website/<name> here i want for it to insert what the user typed in the address bar", {
        "name": util.get_entry(name)  <-- this is a function which checks if there is that name in the database otherwise will return an error.
    })
</code>```

Hope I was clear with the question and thank you for the help :)

答:
I'm not entirely sure what you want to do here but I think you are trying to pass in a string as a parameter. In which case, you would do something like:

```<code>def example(request, name):
    #perform some logic with the name parameter like querying the database
    # results = Post.objects.filter(body__contains=name)

    return render(request, "blog/post.html", {"results": results})
</code>```

You can then access 'results' in the specified template: 'blog/post.html'.
I hope this helps!

Title: Django get URL from address bar

Body:
I am a begginer with django and I am stuck in getting this to work, practically what I want is that the user types in the address bar http://website.com/example and then in Django I want to make a dynamic view where it checks the address and then redirects user to the correct page otherwise gives an error.

this is what I was trying but it might not be working..

urlpatterns = [
path("", views.index, name="index"),
path("<str:name>", views.example, name="example") ]

and then in the views.py I want the following:

def example(request, name):
    return render(request, "website/<name> here i want for it to insert what the user typed in the address bar", {
        "name": util.get_entry(name)  <-- this is a function which checks if there is that name in the database otherwise will return an error.
    })

Hope I was clear with the question and thank you for the help :)

Body:
I'm not entirely sure what you want to do here but I think you are trying to pass in a string as a parameter. In which case, you would do something like:

def example(request, name):
    #perform some logic with the name parameter like querying the database
    # results = Post.objects.filter(body__contains=name)

    return render(request, "blog/post.html", {"results": results})

You can then access 'results' in the specified template: 'blog/post.html'.
I hope this helps!


问:
How to replace white space in column? Pandas
What I tried?

```<code>//1    myDataFrame['Gender'] = myDataFrame['Gender'].replace('^\s*$', np.nan)
//2    myDataFrame['Gender'] = myDataFrame['Gender'].replace('', np.nan)
       myDataFrame.to_csv('new_Paymets_Loan.csv')
</code>```

The white space is still the csv file.
Link to test csv: https://docs.google.com/spreadsheets/d/1eeHGsx3s7nZaSVPCFvtl0Wwp4KJGK8hAlH97n_4DPbI/edit?usp=sharing

[![enter image description here][1]][1]

```<code>Gender
Male
Female
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female

Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Female
Male
Female
Female
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female

Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male

Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male

Female
Male
Male
Male
Male
Female
Male
Male
Female
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male

Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Female
Male
Male
Male
Female
Male
Female
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Female
Male
Male
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Female
Male
</code>```

答:
You want the string NaN in your text csv file. Just put it in the DataFrame:

```<code>myDataFrame['Gender'] = myDataFrame['Gender'].str.replace('^\s*$', 'NaN')
</code>```

Body:
What I tried?

//1    myDataFrame['Gender'] = myDataFrame['Gender'].replace('^\s*$', np.nan)
//2    myDataFrame['Gender'] = myDataFrame['Gender'].replace('', np.nan)
       myDataFrame.to_csv('new_Paymets_Loan.csv')

The white space is still the csv file.
Link to test csv: https://docs.google.com/spreadsheets/d/1eeHGsx3s7nZaSVPCFvtl0Wwp4KJGK8hAlH97n_4DPbI/edit?usp=sharing

[![enter image description here][1]][1]

Gender
Male
Female
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female

Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Female
Male
Female
Female
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female

Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male

Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male

Female
Male
Male
Male
Male
Female
Male
Male
Female
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male

Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Female
Male
Male
Male
Female
Male
Female
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Female
Male
Male
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Female
Male

Body:
You want the string NaN in your text csv file. Just put it in the DataFrame:

myDataFrame['Gender'] = myDataFrame['Gender'].str.replace('^\s*$', 'NaN')


问:
Can we use Admob reward ads without giving any rewards to user?
I wanted to ask is it legal to use the Google Admob reward ads without giving any reward to the user like coins, points or etc. And can we use these ads in non-gaming applications like maps applications or chatting applications and etc.</p>

答: The video type of interstitial ads rather than the rewarded video ads should suit your purpose. Try using the sample unit id for the interstitial video written in this page to see if it is really what you want. </p>


问:
Remove text from Back button keeping the icon
I want to remove the text from the back button, but I want to keep the icon. I have tried </p>

```<code>let backButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: navigationController, action: nil)
navigationItem.leftBarButtonItem = backButton
</code>```

<p>However, this removes completely the text and the icon. </p>

答:
The easiest way to do this programmatically is to set backBarButtonItem from the parent view controller (a controller that calls push).

```<code>class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        navigationItem.backBarButtonItem = backBarButtonItem
    }
}
</code>```

More detail here https://sarunw.com/posts/how-to-remove-text-from-uinavigationbar-back-button/

Body:
I want to remove the text from the back button, but I want to keep the icon. I have tried

let backButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: navigationController, action: nil)
navigationItem.leftBarButtonItem = backButton

However, this removes completely the text and the icon.

Body:
The easiest way to do this programmatically is to set backBarButtonItem from the parent view controller (a controller that calls push).

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        navigationItem.backBarButtonItem = backBarButtonItem
    }
}

More detail here https://sarunw.com/posts/how-to-remove-text-from-uinavigationbar-back-button/


问:
Create a response table with a Google sheet which saves responses in another sheet
I'm trying to create a response table with a Google sheet that lets people enter their responses. Then compile that information into another Google Sheet by specified columns at the bottom of the previous response.

I have tried numerous ways but I cannot seem to get the script to work.

Broken Down, I need the Script/Guide to be able to:

Allow multiple people to record their response individually by the given link of Google sheet Form

Give a dynamic Sum Total in the Total Row

Have an Add row Icon so as to let respondent add rows dynamically and make their own choice of inputs

Create a Submit Icon, which records the response to another google sheet

The intended sheet is below

https://docs.google.com/spreadsheets/d/1cQTBONtpLiMbRmtVgSyOT_mShzzwbrX7-w46zy9w9I4/copy?usp=sharing

This may be a simple question that I didn't sound any solution

答:
Please see if this works for you.
Modified enquiry form

1. Allow multiple people to record their response individually by the given link of Google sheet Form

You need to share a copy of your spreadsheet. Do not share the original. In the URL you have posted, replace 'edit' with 'copy'.

The modified enquiry form

2. Gives a dynamic Sum Total in the Total Row as your user records their inputs by using onEdit function.

3. Has an Add row and Delete row Icon so as to let respondent add and delete rows dynamically and make their own choice of inputs. To add a row, the active row number should be 4 or above

4. Creates a Place Order Image, which appends the response to another google sheet

To achieve point 4, you need to create a separate spreadsheet having 1 row only. This serves as the column heading and can be in a form as shown below. This spreadsheet contains the details of responses from all users.

Note: Updating a spreadsheet automatically when the user clicks the Submit button would require you to make the spreadsheet shareable via email addresses with editor access at a minimum. This is potentially an unsafe way of saving user responses.


问:
can any one suggest a good math function in javascript to round integer?
i have to round the value from 2.3456789 to 2.345 .

After . there must be three number only remaining should be removed

答:
Javascript 1.5+ introduced Number.toFixed(n) and Number.toPrecision(n) - pick one depending on what you need.

Number.toFixed() lets you specify the number of digits after the decimal point (padded if necessary).

```<code>(2.3456789).toFixed(3) = "2.346"
(3).toFixed(3) = "3.000"
</code>```

Number.toPrecision() lets you specify the number of significant figures.

```<code>(2.3456789).toPrecision(4) = "2.346"
</code>```

Body:
Javascript 1.5+ introduced Number.toFixed(n) and Number.toPrecision(n) - pick one depending on what you need.

Number.toFixed() lets you specify the number of digits after the decimal point (padded if necessary).

(2.3456789).toFixed(3) = "2.346"
(3).toFixed(3) = "3.000"

Number.toPrecision() lets you specify the number of significant figures.

(2.3456789).toPrecision(4) = "2.346"


问:
Typo3 9.5: Deactivate Slugs and use id=123 instead?
I updated from typo3 4.7 to 9.5 - with a fresh installation - and imported my old page tree.

Now the page-URLs and menu-links are "speaking urls" and not the original "index.php?id=123" URLs. But for many of my individual PHP Scripts i need the "old" link-style ...

Is it possible to de-activate the "Slug" URLs, so that all links are just index.php?id=123 , like in the older versions?

答: The only way to achieve this is to delete all "Site" configuration, which causes TYPO3 to fall back on "NullSite" mode, which behaves the way you want.</p>


问:
Javascript: go to error page when any variable is undefined or null
I want to redirect to error page in the application , when any of the variable in the whole app is undefined or null.

Instead of crashing app, I want to redirect to error page.

Any help would be great.

Thank You.

答:
wrap your code in Try catch statement

```<code>try{
    var a = undefined;
    var b = a.length;
} catch(ex) {
    console.log(ex);
    //redirect to your error page
}
</code>```

Body:
wrap your code in Try catch statement

try{
    var a = undefined;
    var b = a.length;
} catch(ex) {
    console.log(ex);
    //redirect to your error page
}