问:
Numpy: apply function to every (or subset of) diagonal
I'd like to apply a function (namely np.var, but a general method would be great) to every diagonal of an array.  My arrays are square.
I can do this with:

```<code>offset_list = np.arange(-1 * len(arr) + 1, len(arr))
diag_var_list = [np.var(np.diagonal(arr, k)) for k in offset_list]
</code>```

If I want a subset of the diagonals I can change offset_list.

But using list comprehension seems inefficient since I'll be doing this on many large arrays.
Is there a better way?

答:
Sparse matrices used in linear algebra often have a diagonal structure (not all diagonals though).  The scipy.sparse  has two ways of specifying diagonals - as a list of arrays, each different in length, and as a 2d padded array.

https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.diags.html

https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.spdiags.html#scipy.sparse.spdiags

For numpy (dense) arrays, diagonals aren't that special.  All the functions just handle one diagonal at a time (it can be offset).  np.diag*

Body:
I'd like to apply a function (namely np.var, but a general method would be great) to every diagonal of an array.  My arrays are square.
I can do this with:

offset_list = np.arange(-1 * len(arr) + 1, len(arr))
diag_var_list = [np.var(np.diagonal(arr, k)) for k in offset_list]

If I want a subset of the diagonals I can change offset_list.

But using list comprehension seems inefficient since I'll be doing this on many large arrays.
Is there a better way?


来源: stackexchange

问:
How do I set minimum output size when converting video files in Swift?
This is the function I use to compress video files in Swift:

```<code>private func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
    let urlAsset = AVURLAsset(url: inputURL, options: nil)
    guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetLowQuality) else {
        handler(nil)
        return
    }
    exportSession.outputURL = outputURL
    exportSession.outputFileType = AVFileType.mp4
    exportSession.shouldOptimizeForNetworkUse = true
    exportSession.exportAsynchronously { () -> Void in
        handler(exportSession)
    }
}
</code>```

But the result is not as I expect;) For example, when I have 17MB size before compression, then as output I get 0.6MB. Is it possible to set somewhere type of compression or something like this to get a result with better quality? I will have satisfied when I get ~2MB file size in output.

答:
You can use AVAssetExportPresetMediumQuality for better quality than AVAssetExportPresetLowQuality.

Or you can use AVAssetWriter for more cutomization

ContentLicense: CC BY-SA 4.0

Body:
This is the function I use to compress video files in Swift:

private func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
    let urlAsset = AVURLAsset(url: inputURL, options: nil)
    guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetLowQuality) else {
        handler(nil)
        return
    }
    exportSession.outputURL = outputURL
    exportSession.outputFileType = AVFileType.mp4
    exportSession.shouldOptimizeForNetworkUse = true
    exportSession.exportAsynchronously { () -> Void in
        handler(exportSession)
    }
}

But the result is not as I expect;) For example, when I have 17MB size before compression, then as output I get 0.6MB. Is it possible to set somewhere type of compression or something like this to get a result with better quality? I will have satisfied when I get ~2MB file size in output.


问:
How to make scrollable overlay
I am trying to achieve something like the image below. The goal is to have an overlay with an editText that that can scroll and hide the content under it. I'm not sure how to do this with Java or XML. The image on the left is the desired initial screen and the second screen is when the scrollView overlays the content, and a header appears.

答:
You might achieve that with a Collapsing Toolbar</p>

```<code><com.google.android.material.appbar.CollapsingToolbarLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:contentScrim="?attr/colorPrimary"
    app:expandedTitleGravity="top"
    app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

  <ImageView
      android:id="@+id/backdrop"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:scaleType="centerCrop"
      app:layout_collapseMode="parallax"
      android:src="@drawable/appbar_image" />

  <androidx.appcompat.widget.Toolbar
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      app:layout_collapseMode="pin"/>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</code>```

Title: How to make scrollable overlay

Body:
You might achieve that with a Collapsing Toolbar

<com.google.android.material.appbar.CollapsingToolbarLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:contentScrim="?attr/colorPrimary"
    app:expandedTitleGravity="top"
    app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

  <ImageView
      android:id="@+id/backdrop"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:scaleType="centerCrop"
      app:layout_collapseMode="parallax"
      android:src="@drawable/appbar_image" />

  <androidx.appcompat.widget.Toolbar
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      app:layout_collapseMode="pin"/>
</com.google.android.material.appbar.CollapsingToolbarLayout>


问:
Self syntax in iPhone development
What is the difference between the following two approaches for the self syntax to access the object properties:-

Approach 1:-

```<code>    self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

Approach 2:-

```<code>    effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

effortView is defined as a property, and synthesized, to the Class addressed as self in Approach 1. Both of the approaches work.

I am using Xcode 4.0 iPhone SDK 4.3 on Mac 10.6.6.

Please enlighten me.

Thank you All

答:
The former uses the accessors methods generated by the synthesize statement.

The latter accesses the variable directly.

ContentLicense: CC BY-SA 3.0

Title: Self syntax in iPhone development

Body:
What is the difference between the following two approaches for the self syntax to access the object properties:-

Approach 1:-

    self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

Approach 2:-

    effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

effortView is defined as a property, and synthesized, to the Class addressed as self in Approach 1. Both of the approaches work.

I am using Xcode 4.0 iPhone SDK 4.3 on Mac 10.6.6.

Please enlighten me.

Thank you All


问:
disabled "label" and disabled "input" Selenium
I am testing with Selenium. Two (2) Page elements are disabled, one is "input" the other is "label".
I have attached pictures to show how they look like being disabled.

But Selenium driver cannot assert the "label" type as disabled, although it clearly is.

Is something wrong with FE developer code to define "label" and "input" as disabled elements?

My code to assert is:

```<code>Assert.assertFalse(driver.findElement(By.xpath("abc").isEnabled());
</code>```

Input element:

Label element:

答:
HTML <input> disabled Attribute

A disabled <input> element is unusable and unclickable. At times the disabled attribute is set to keep an user from using the <input> element until some other condition has been met (like selecting a dropdown, checkbox, etc.).

As per the first image:

The <input> with name attribute set as destinationCity is assigned the disabled attribute possibly to force the user to fill up the originCity first.

Similarly, as per the second image:

The  with for attribute set as settingsDangerousGoods  which controls the following <input> element with id attribute set as settingsDangerousGoods is assigned the disabled attribute possibly to force the user to fill up the previous mandatory fields.

However, a JavaScript could remove the disabled value, and make the <input> element usable.

Update

The attributes of the  is applied for the element with id attribute set as for='settingsDangerousGoods'which is the following <input> element. However, you won't interact with a  but you would most likely interact with an <input> element. See the docs:

```<code>isEnabled():

Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
</code>```

Body:
I am testing with Selenium. Two (2) Page elements are disabled, one is "input" the other is "label".
I have attached pictures to show how they look like being disabled.

But Selenium driver cannot assert the "label" type as disabled, although it clearly is.

Is something wrong with FE developer code to define "label" and "input" as disabled elements?

My code to assert is:

Assert.assertFalse(driver.findElement(By.xpath("abc").isEnabled());

Input element:

Label element:

Body:
HTML <input> disabled Attribute

A disabled <input> element is unusable and unclickable. At times the disabled attribute is set to keep an user from using the <input> element until some other condition has been met (like selecting a dropdown, checkbox, etc.).

As per the first image:

The <input> with name attribute set as destinationCity is assigned the disabled attribute possibly to force the user to fill up the originCity first.

Similarly, as per the second image:

The <label> with for attribute set as settingsDangerousGoods  which controls the following <input> element with id attribute set as settingsDangerousGoods is assigned the disabled attribute possibly to force the user to fill up the previous mandatory fields.

However, a JavaScript could remove the disabled value, and make the <input> element usable.

Update

The attributes of the <label> is applied for the element with id attribute set as for='settingsDangerousGoods'which is the following <input> element. However, you won't interact with a <label> but you would most likely interact with an <input> element. See the docs:

isEnabled():

Is the element currently enabled or not? This will generally return true for everything but disabled input elements.


问:
Large console output produced by mini-css-extract-plugin
Been trying to research this but it doesn't seem as if any else has this, or see this as an issue.

I am using mini-css-extract-plugin(MiniCssExtractPlugin) in my webpack.config.js.

However, when I run webpack the console is littered with hundreds of instances of something similar to this...

```<code>Child mini-css-extract-plugin ../../../node_modules/css-loader/index.js??ref--6-1!../../../node_modules/postcss-loader/src/index.js!../../../node_modules/sass-loader/lib/loader.js!ui/radiolist-toggler/RadioListToggler.scss:
    Entrypoint mini-css-extract-plugin = *
    [../../../node_modules/css-loader/index.js?!../../../node_modules/postcss-loader/src/index.js!../../../node_modules/sass-loader/lib/loader.js!./ui/radiolist-toggler/RadioListToggler.scss] /Users/~~~/git/user-section/node_modules/css-loader??ref--6-1!/Users/~~~/git/user-section/node_modules/postcss-loader/src!/Users/~~/git/user-section/node_modules/sass-loader/lib/loader.js!./ui/radiolist-toggler/RadioListToggler.scss 5.33 KiB {mini-css-extract-plugin} [built]
        + 1 hidden module
</code>```

I need to scroll up for a good few seconds to be able to see all my assets etc.

I am pretty new to webpack, so not exactly sure how to prevent this from being output to the console?

Below is my webpack.config.js

```<code>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const modernizr = require("modernizr");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  context: path.resolve(__dirname, 'src/main/client'),
  entry: './index',
  devtool: 'cheap-module-source-map',
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        uglifyOptions: {
          mangle: true,
          compress: true,
          ecma: 6
        },
        sourceMap: true
      }),
      new OptimizeCssAssetsPlugin({}),
    ],
    splitChunks: {
      chunks: 'all'
    }
  },
  plugins: [
    new CompressionPlugin({
      test: /\.js$|\.css$|\.html$|\.(png|svg|jpg|gif)$/,
      cache: true,
      filename: '[path].gz[query]',
      algorithm: 'gzip',
      threshold: 10240
    }),
    new CleanWebpackPlugin([
      './target/webapp'
    ]),
    new HtmlWebpackPlugin({
      template: './index.html',
      filename: '../index.html',
      xhtml: true
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
    }),
    new CopyWebpackPlugin([{
      from: '../webapp/**/*',
      to: '../'
    }]),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"'
    }),
  ],
  output: {
    publicPath: '/app/',
    filename: '[name].bundle.js',
    chunkFilename: '[id].js',
    path: path.resolve(__dirname, 'target/webapp/app/')
  },
  module: {
    rules: [{
        loader: "webpack-modernizr-loader",
        test: /\.modernizrrc\.js$/
      },
      {
        test: /\.html$/,
        exclude: /node_modules/,
        use: {
          loader: 'html-loader'
        }
      },
      {
        test: /\.s?css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          {
            loader: 'postcss-loader'
          },
          {
            loader: 'sass-loader'
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader'
        ]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: './assets/fonts/'
          }
        }]
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          presets: ["@babel/env"]
        }
      }
    ],
  },
  resolve: {
    alias: {
      // You can add comment "Please do not delete this file" in this file
      modernizr$: path.resolve(__dirname, "./.modernizrrc.js")
    }
  }
}
</code>```

答:
@mcclosa mentioned this as a comment but in case anyone should look at this question, see no answer and click away, the solution is to add the stats option to your webpack.config.js file as follows:

```<code>module.exports = {
   stats: { children: false },
}
</code>```

The above option uses the children: false option suggested by @mcclosa, which does successfully remove the junk output by mini-css-extract-plugin, but I find using the preset stats: "minimal" produces a much nicer overall output. Using:

```<code>module.exports = {
   stats: "minimal",
}
</code>```

..gives me the following tiny output whenever my build has no errors:

```<code>i ｢wdm｣: Compiling...
i ｢wdm｣:    69 modules
i ｢wdm｣: Compiled successfully.
</code>```

..as opposed to dozens of lines of useless build data, but it will continue to give give error information when errors are present.

Body:
Been trying to research this but it doesn't seem as if any else has this, or see this as an issue.

I am using mini-css-extract-plugin(MiniCssExtractPlugin) in my webpack.config.js.

However, when I run webpack the console is littered with hundreds of instances of something similar to this...

Child mini-css-extract-plugin ../../../node_modules/css-loader/index.js??ref--6-1!../../../node_modules/postcss-loader/src/index.js!../../../node_modules/sass-loader/lib/loader.js!ui/radiolist-toggler/RadioListToggler.scss:
    Entrypoint mini-css-extract-plugin = *
    [../../../node_modules/css-loader/index.js?!../../../node_modules/postcss-loader/src/index.js!../../../node_modules/sass-loader/lib/loader.js!./ui/radiolist-toggler/RadioListToggler.scss] /Users/~~~/git/user-section/node_modules/css-loader??ref--6-1!/Users/~~~/git/user-section/node_modules/postcss-loader/src!/Users/~~/git/user-section/node_modules/sass-loader/lib/loader.js!./ui/radiolist-toggler/RadioListToggler.scss 5.33 KiB {mini-css-extract-plugin} [built]
        + 1 hidden module

I need to scroll up for a good few seconds to be able to see all my assets etc.

I am pretty new to webpack, so not exactly sure how to prevent this from being output to the console?

Below is my webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const modernizr = require("modernizr");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  context: path.resolve(__dirname, 'src/main/client'),
  entry: './index',
  devtool: 'cheap-module-source-map',
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        uglifyOptions: {
          mangle: true,
          compress: true,
          ecma: 6
        },
        sourceMap: true
      }),
      new OptimizeCssAssetsPlugin({}),
    ],
    splitChunks: {
      chunks: 'all'
    }
  },
  plugins: [
    new CompressionPlugin({
      test: /\.js$|\.css$|\.html$|\.(png|svg|jpg|gif)$/,
      cache: true,
      filename: '[path].gz[query]',
      algorithm: 'gzip',
      threshold: 10240
    }),
    new CleanWebpackPlugin([
      './target/webapp'
    ]),
    new HtmlWebpackPlugin({
      template: './index.html',
      filename: '../index.html',
      xhtml: true
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
    }),
    new CopyWebpackPlugin([{
      from: '../webapp/**/*',
      to: '../'
    }]),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"'
    }),
  ],
  output: {
    publicPath: '/app/',
    filename: '[name].bundle.js',
    chunkFilename: '[id].js',
    path: path.resolve(__dirname, 'target/webapp/app/')
  },
  module: {
    rules: [{
        loader: "webpack-modernizr-loader",
        test: /\.modernizrrc\.js$/
      },
      {
        test: /\.html$/,
        exclude: /node_modules/,
        use: {
          loader: 'html-loader'
        }
      },
      {
        test: /\.s?css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          {
            loader: 'postcss-loader'
          },
          {
            loader: 'sass-loader'
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader'
        ]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: './assets/fonts/'
          }
        }]
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          presets: ["@babel/env"]
        }
      }
    ],
  },
  resolve: {
    alias: {
      // You can add comment "Please do not delete this file" in this file
      modernizr$: path.resolve(__dirname, "./.modernizrrc.js")
    }
  }
}

Body:
@mcclosa mentioned this as a comment but in case anyone should look at this question, see no answer and click away, the solution is to add the stats option to your webpack.config.js file as follows:

module.exports = {
   stats: { children: false },
}

The above option uses the children: false option suggested by @mcclosa, which does successfully remove the junk output by mini-css-extract-plugin, but I find using the preset stats: "minimal" produces a much nicer overall output. Using:

module.exports = {
   stats: "minimal",
}

..gives me the following tiny output whenever my build has no errors:

i ｢wdm｣: Compiling...
i ｢wdm｣:    69 modules
i ｢wdm｣: Compiled successfully.

..as opposed to dozens of lines of useless build data, but it will continue to give give error information when errors are present.


问:
adding and substracting time in Javascript
I'm trying to add five minutes to the current time using milliseconds and am baffled why adding and subtracting give such different results:

const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;
```

<p>Respectively give:</p>

```"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"

1590962508207
```

Why does subtraction work, but not addition? How can I add time?

Added clarification per stack overflow prompt: while the Q here overlapped with Add 10 seconds to a Date, it differed in seeking to understand why the add and subtract operators show different behaviours (as explained by RobG, for which, much thanks!)

答:
If you are working with minutes best solution is to use Date's getMinutes and setMinutes methods.

var dt = new Date();
console.log(dt)

dt.setMinutes( dt.getMinutes() + 100 );
console.log(dt)

dt.setMinutes( dt.getMinutes() - 100 );
console.log(dt)```

Body:
I'm trying to add five minutes to the current time using milliseconds and am baffled why adding and subtracting give such different results:

const now = new Date();
const gimmeFive = now + 300000;
const takeFive = now - 300000;

Respectively give:

"Sun May 31 2020 23:06:48 GMT+0100 (British Summer Time)300000"

1590962508207

Why does subtraction work, but not addition? How can I add time?

Added clarification per stack overflow prompt: while the Q here overlapped with Add 10 seconds to a Date, it differed in seeking to understand why the add and subtract operators show different behaviours (as explained by RobG, for which, much thanks!)


问:
reading/recognizing new line operator \n
Pretty Simple question today.

PROBLEM:
I cannot get my code to read the newline operator from a repr string.

Desired Output:
I have a message and dummy variables. I want to write the message over the Dummy variables such as:

```<code>dummy:
$$$$$$$$
$$$$  $$
$$$$$$$$

Message:
Hello!!

Returns:
Hello!!H
ello  He
llo!!Hel

What I'm currently getting:
Hello! Hello! Hello! Hello!
</code>```

Code:

```<code>def patternedMessage(msg, pattern):
    ##Set variables, create repr and long string
    newBuild = ""
    reprPtrn = repr(pattern)
    strRecycleInt = len(reprPtrn)//len(msg)
    longPattern = (msg *(strRecycleInt+1))
    #print(reprPtrn) ## to see what the computer sees
    ##Rudimenray switch build
    lineCounter = 0
    for i in range(len(reprPtrn)):
        if (reprPtrn[i] == "\n"):
            newBuild = newBuild + "\n"
            #lineCounter += 1 ## testing for entering the for
        if (reprPtrn[i] != " "):
            newBuild = newBuild + longPattern[i]
        if (reprPtrn[i] == " "):
            newBuild = newBuild + " "
        #print(lineCounter) ## Not entering the for statement
    return newBuild
</code>```

I'm so close. I basically built a simple switch and everything works but the operator. I know I'm doing something wrong with trying to get my code to recognize the \n. (I commented out the dummy counter. I was using it to see if I was actually entering the if statement. ignore that.)

I searched for a bit but am jsut beating my head against a wall now. any help is welcome. Thanks everyone!

答:
If

```<code>pattern='
$$$$$$$s
$$$$  $$
$$$$$$$$
'
</code>```

then

```<code>reprPtrn='\'\\n$$$$$$$s\\n$$$$  $$\\n$$$$$$$$\\n\''
</code>```

reprPtrn[i] iterates through each character, and \\n is composed of three characters, so the condition is never met.
However

```<code>pattern[i] is "\n":
</code>```

will return true at the newline.

You should also use elif and a separate index to follow the message characters from the pattern.

Full code with requested output:

```<code>def patternedMessage(msg, pattern):
##Set variables, create repr and long string
newBuild = ""
strRecycleInt = len(pattern) // len(msg)
longPattern = (msg * (strRecycleInt + 1))
# print(reprPtrn) ## to see what the computer sees
##Rudimenray switch build
lineCounter = 0
k = 0
for i in range(len(pattern)):
    if (pattern[i] is "\n"):
        newBuild = newBuild + "\n"
        # lineCounter += 1 ## testing for entering the for
    elif (pattern[i] != " "):
        newBuild = newBuild + longPattern[k]
        k += 1
    elif (pattern[i] is " "):
        newBuild = newBuild + " "
    # print(lineCounter) ## Not entering the for statement
return newBuild
</code>```

Body:
Pretty Simple question today.

PROBLEM:
I cannot get my code to read the newline operator from a repr string.

Desired Output:
I have a message and dummy variables. I want to write the message over the Dummy variables such as:

dummy:
$$$$$$$$
$$$$  $$
$$$$$$$$

Message:
Hello!!

Returns:
Hello!!H
ello  He
llo!!Hel

What I'm currently getting:
Hello! Hello! Hello! Hello!

Code:

def patternedMessage(msg, pattern):
    ##Set variables, create repr and long string
    newBuild = ""
    reprPtrn = repr(pattern)
    strRecycleInt = len(reprPtrn)//len(msg)
    longPattern = (msg *(strRecycleInt+1))
    #print(reprPtrn) ## to see what the computer sees
    ##Rudimenray switch build
    lineCounter = 0
    for i in range(len(reprPtrn)):
        if (reprPtrn[i] == "\n"):
            newBuild = newBuild + "\n"
            #lineCounter += 1 ## testing for entering the for
        if (reprPtrn[i] != " "):
            newBuild = newBuild + longPattern[i]
        if (reprPtrn[i] == " "):
            newBuild = newBuild + " "
        #print(lineCounter) ## Not entering the for statement
    return newBuild

I'm so close. I basically built a simple switch and everything works but the operator. I know I'm doing something wrong with trying to get my code to recognize the \n. (I commented out the dummy counter. I was using it to see if I was actually entering the if statement. ignore that.)

I searched for a bit but am jsut beating my head against a wall now. any help is welcome. Thanks everyone!

Body:
If

pattern='
$$$$$$$s
$$$$  $$
$$$$$$$$
'

then

reprPtrn='\'\\n$$$$$$$s\\n$$$$  $$\\n$$$$$$$$\\n\''

reprPtrn[i] iterates through each character, and \\n is composed of three characters, so the condition is never met.
However

pattern[i] is "\n":

will return true at the newline.

You should also use elif and a separate index to follow the message characters from the pattern.

Full code with requested output:

def patternedMessage(msg, pattern):
##Set variables, create repr and long string
newBuild = ""
strRecycleInt = len(pattern) // len(msg)
longPattern = (msg * (strRecycleInt + 1))
# print(reprPtrn) ## to see what the computer sees
##Rudimenray switch build
lineCounter = 0
k = 0
for i in range(len(pattern)):
    if (pattern[i] is "\n"):
        newBuild = newBuild + "\n"
        # lineCounter += 1 ## testing for entering the for
    elif (pattern[i] != " "):
        newBuild = newBuild + longPattern[k]
        k += 1
    elif (pattern[i] is " "):
        newBuild = newBuild + " "
    # print(lineCounter) ## Not entering the for statement
return newBuild


问:
Python variable's value doesn't get changed outside the function
I'm working on a school project. I made a test version of my program, because I'm new to Python and I only have experience with C#, so I'm still learning te basics. My problem is the following:
Before the function "Fill_Array()" I declared a variable (" max_element_var") that is supposed to store the max number of elements that can be stored in the array ("content_array"). Later in the function I change it's value to the input of the console, which happens, and the function runs as it should, the only problem being is that outside the function the value of " max_element_var" stays "None". What should I do in order to fix this?</p>

```<code>#__Test__#
def Test():
    class Que:
        def __init__(self, content, max_element ,actual_elements):
            self.content = content
            self.max_element = max_element
            self.actual_elements = actual_elements

    max_element_var = None
    content_array = []
    def Fill_array():
        print("What should be the max number of elements that can be stored in the array? (Type in an integer!)")
        max_element_var = int(input())
        if(max_element_var>0):
             import random
             random_var = random.randrange(0,max_element_var)
             for x in range(max_element_var-random_var):
                 content_array.append(x)
        else:
            print("It has to be more than 0!")
            Fill_array()
    Fill_array()

    actual_elements_var = len(content_array)

    que = Que (content_array, max_element_var, actual_elements_var)

    print("Content: ", que.content)
    print("Max number of elements: ", que.max_element)
    print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
    print("Which version should be used? (Type in the number!)")
    print("1 - Test")
    print("2 - Full")
    answer = int(input())
    if(answer == 1):
        Test()
        Version_selector()
    elif(answer == 2):
        Full()
        Version_selector()
#__Version_selector__#
Version_selector()
</code>```

答:
Modified code to correct some issues.

Import normally done at top of module (not within functions)

Remove nested class definition inside function (obfuscates things in simple code)

Changed recursive calls to a while loop (a better way to repeat execution of a function from beginning in Python since no tail recursion).

Code Refactoring

```<code>import random

class Que:
  def __init__(self, content, max_element ,actual_elements):
      self.content = content
      self.max_element = max_element
      self.actual_elements = actual_elements

def Fill_array():
  " Returns requested size and array "
  while True:
    prompt = """"What should be the max number of elements that can be stored in the array?  Type in an integer!: """
    max_element_var = int(input(prompt))
    if max_element_var > 0:
      random_var = random.randrange(0,max_element_var)
      return max_element_var, [x for x in range(max_element_var-random_var)]
    else:
      print("It has to be more than 0!")

def Test():
  max_element_var, content_array = Fill_array()
  actual_elements_var = len(content_array)
  que = Que (content_array, max_element_var, actual_elements_var)

  print("Content: ", que.content)
  print("Max number of elements: ", que.max_element)
  print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
  while True:
    prompt = """Which version should be used? (Type in the number!)
    1 - Test
    2 - Full
    3 - Quit\n\t"""

    answer = int(input(prompt))
    if answer == 1:
      Test()
    elif answer == 2:
      Full()
    else:
      break

#__Version_selector__#
Version_selector()
</code>```

Body:
I'm working on a school project. I made a test version of my program, because I'm new to Python and I only have experience with C#, so I'm still learning te basics. My problem is the following:
Before the function "Fill_Array()" I declared a variable (" max_element_var") that is supposed to store the max number of elements that can be stored in the array ("content_array"). Later in the function I change it's value to the input of the console, which happens, and the function runs as it should, the only problem being is that outside the function the value of " max_element_var" stays "None". What should I do in order to fix this?

#__Test__#
def Test():
    class Que:
        def __init__(self, content, max_element ,actual_elements):
            self.content = content
            self.max_element = max_element
            self.actual_elements = actual_elements

    max_element_var = None
    content_array = []
    def Fill_array():
        print("What should be the max number of elements that can be stored in the array? (Type in an integer!)")
        max_element_var = int(input())
        if(max_element_var>0):
             import random
             random_var = random.randrange(0,max_element_var)
             for x in range(max_element_var-random_var):
                 content_array.append(x)
        else:
            print("It has to be more than 0!")
            Fill_array()
    Fill_array()

    actual_elements_var = len(content_array)

    que = Que (content_array, max_element_var, actual_elements_var)

    print("Content: ", que.content)
    print("Max number of elements: ", que.max_element)
    print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
    print("Which version should be used? (Type in the number!)")
    print("1 - Test")
    print("2 - Full")
    answer = int(input())
    if(answer == 1):
        Test()
        Version_selector()
    elif(answer == 2):
        Full()
        Version_selector()
#__Version_selector__#
Version_selector()

Body:
Modified code to correct some issues.

Import normally done at top of module (not within functions)

Remove nested class definition inside function (obfuscates things in simple code)

Changed recursive calls to a while loop (a better way to repeat execution of a function from beginning in Python since no tail recursion).

Code Refactoring

import random

class Que:
  def __init__(self, content, max_element ,actual_elements):
      self.content = content
      self.max_element = max_element
      self.actual_elements = actual_elements

def Fill_array():
  " Returns requested size and array "
  while True:
    prompt = """"What should be the max number of elements that can be stored in the array?  Type in an integer!: """
    max_element_var = int(input(prompt))
    if max_element_var > 0:
      random_var = random.randrange(0,max_element_var)
      return max_element_var, [x for x in range(max_element_var-random_var)]
    else:
      print("It has to be more than 0!")

def Test():
  max_element_var, content_array = Fill_array()
  actual_elements_var = len(content_array)
  que = Que (content_array, max_element_var, actual_elements_var)

  print("Content: ", que.content)
  print("Max number of elements: ", que.max_element)
  print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
  while True:
    prompt = """Which version should be used? (Type in the number!)
    1 - Test
    2 - Full
    3 - Quit\n\t"""

    answer = int(input(prompt))
    if answer == 1:
      Test()
    elif answer == 2:
      Full()
    else:
      break

#__Version_selector__#
Version_selector()


答:
self.effortView uses the accessor methods generated by @synthesize to get and set the property, while effortView accesses the instance variable directly. Inside the class where the property is defined, the difference is most important when considering the setter: it automatically takes care of memory management. So if you've done this:

```<code>@property (nonatomic, retain) EffortView *effortView;
</code>```

then the two approaches have different results. Approach 1 leaks in this case, as the setter retains the object and you +alloc it without a balanced -release.

Title: Self syntax in iPhone development

Body:
self.effortView uses the accessor methods generated by @synthesize to get and set the property, while effortView accesses the instance variable directly. Inside the class where the property is defined, the difference is most important when considering the setter: it automatically takes care of memory management. So if you've done this:

@property (nonatomic, retain) EffortView *effortView;

then the two approaches have different results. Approach 1 leaks in this case, as the setter retains the object and you +alloc it without a balanced -release.


问:
systemverilog union type in chisel
I rewritting some systermverilog code into chisel, and I cannot find a good way to express the systemverilog's packed union in chisel. For example,

```<code>typedef struct packed {
    logic [3:0]     version;
    logic [3:0]     ihl;
    logic [7:0]     tos;
    logic [15:0]    total_length;
    logic [15:0]    id;
    logic           reserved;
    logic           df;
    logic           mf;
    logic [12:0]    frag_offset;
    logic [7:0]     ttl;
    logic [7:0]     protocol;
    logic [15:0]    checksum;
    logic [31:0]    ip_sa;
    logic [31:0]    ip_da;
} ipv4_s;

typedef struct packed {
    logic [63:0] DW0;
    logic [63:0] DW1;
    logic [31:0] DW2;
} common_20b_s;

typedef union packed {
    ipv4_s  structured;
    common_20b_s array;
    logic [$bits(ipv4_s)-1:0] bits;
} ipv4_hdr_u;

module test (
    input clk,
    input [$bits(ipv4_s)-1:0] pkt_stream_in,
    input [3:0] mode,
    input [127:0] config_in,
    output reg [$bits(ipv4_s)-1:0] pkt_stream_out
);

    ipv4_hdr_u ipv4_hdr;
    always @* begin
        ipv4_hdr.bits = pkt_stream_in;

        case(mode)
            0: ipv4_hdr.structured.ip_sa = config_in[31:0];
            1: ipv4_hdr.array.DW0 = config_in[63:0];
        endcase
    end

    always @(posedge clk)
        pkt_stream_out <= ipv4_hdr.bits;

endmodule: test

</code>```

For those two data structure ipv4_s and common_2b_s, each field in the structure can be updated individually, but to chisel. Is it any way to express this kind of function?

答:
There's no built-in support for packed unions, but you can create custom classes (subtyping Bundle) and build something similar yourself. It leads to a little more boiler plate so I think some built-in support would be nice, but it gets the job done:

Runnable transliteration: https://scastie.scala-lang.org/5jOMpEYuRbu9VbzScvDffQ

Pasted below:

import chisel3._
import chisel3.util._
import chisel3.stage.ChiselStage

class IPV4_s extends Bundle {
  val version = UInt(4.W)
  val ihl = UInt(4.W)
  val tos = UInt(8.W)
  val total_length = UInt(16.W)
  val id = UInt(16.W)
  val reserved = Bool()
  val df = Bool()
  val mf = Bool()
  val frag_offset = UInt(13.W)
  val ttl = UInt(8.W)
  val protocol = UInt(8.W)
  val checksum = UInt(16.W)
  val ip_sa = UInt(32.W)
  val ip_da = UInt(32.W)
}
object IPV4_s {
  // Utility, I got sick of typing this righthand expression
  val width = (new IPV4_s).getWidth
}

class Common_20b_s extends Bundle {
  val DW0 = UInt(64.W)
  val DW1 = UInt(64.W)
  val DW2 = UInt(32.W)
}

class IPV4_hdr_u extends Bundle {
  val bits = UInt(IPV4_s.width.W)
  // These helpers aren't really necessary but can save some typing
  def asIPV4_s = this.asTypeOf(new IPV4_s)
  def asCommon_20b_s = this.asTypeOf(new Common_20b_s)
}

class Test extends MultiIOModule {
  // clock is inherited
  val pkt_stream_in = IO(Input(new IPV4_hdr_u))
  val mode = IO(Input(UInt(4.W)))
  val config_in = IO(Input(UInt(128.W)))
  val pkt_stream_out = IO(Output(new IPV4_hdr_u))

  // Default to using stream_in
  val ipv4_hdr = WireInit(pkt_stream_in)
  switch (mode) {
    is (0.U) {
      // Cast input and use temporary for subfield assignment
      val t = WireInit(pkt_stream_in.asIPV4_s)
      t.ip_sa := config_in(31, 0)
      ipv4_hdr := t.asTypeOf(new IPV4_hdr_u)
    }
    is (1.U) {
      val t = WireInit(pkt_stream_in.asCommon_20b_s)
      t.DW0 := config_in(63, 0)
      ipv4_hdr := t.asTypeOf(new IPV4_hdr_u)
    }
  }
  pkt_stream_out := ipv4_hdr
}
```

Title: systemverilog union type in chisel

Body:
I rewritting some systermverilog code into chisel, and I cannot find a good way to express the systemverilog's packed union in chisel. For example,

typedef struct packed {
    logic [3:0]     version;
    logic [3:0]     ihl;
    logic [7:0]     tos;
    logic [15:0]    total_length;
    logic [15:0]    id;
    logic           reserved;
    logic           df;
    logic           mf;
    logic [12:0]    frag_offset;
    logic [7:0]     ttl;
    logic [7:0]     protocol;
    logic [15:0]    checksum;
    logic [31:0]    ip_sa;
    logic [31:0]    ip_da;
} ipv4_s;

typedef struct packed {
    logic [63:0] DW0;
    logic [63:0] DW1;
    logic [31:0] DW2;
} common_20b_s;

typedef union packed {
    ipv4_s  structured;
    common_20b_s array;
    logic [$bits(ipv4_s)-1:0] bits;
} ipv4_hdr_u;

module test (
    input clk,
    input [$bits(ipv4_s)-1:0] pkt_stream_in,
    input [3:0] mode,
    input [127:0] config_in,
    output reg [$bits(ipv4_s)-1:0] pkt_stream_out
);

    ipv4_hdr_u ipv4_hdr;
    always @* begin
        ipv4_hdr.bits = pkt_stream_in;

        case(mode)
            0: ipv4_hdr.structured.ip_sa = config_in[31:0];
            1: ipv4_hdr.array.DW0 = config_in[63:0];
        endcase
    end

    always @(posedge clk)
        pkt_stream_out <= ipv4_hdr.bits;

endmodule: test

For those two data structure ipv4_s and common_2b_s, each field in the structure can be updated individually, but to chisel. Is it any way to express this kind of function?


问:
SpringBoot upgrade RestTemplateBuilder from 1.5.14 to 2.1.5
I have this piece of code working fine on a project that uses RestTemplateBuilder 1.5.14

```<code>this.restTemplate = restTemplateBuilder
                .setConnectTimeout(connectTimeout)
                .setReadTimeout(readTimeout)
                .requestFactory(new MyHttpComponentFactoryBuilder()
                        .build())
                .build();
</code>```

After updating to  RestTemplateBuilder 2.1.5 I have this piece of code:

```<code>this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(connectTimeout))
                .setReadTimeout(Duration.ofMillis(readTimeout))
                .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass())
                .build();
</code>```

but when running the code I have a  InvocationTargetException / NullPointerException that dissapears when deleting the line .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass()) , but debugging new MyHttpComponentFactoryBuilder().build().getClass() is not null

I also tried with the solution proposed:

```<code>...
.requestFactory(new MyRequestFactorySupplier())
...

class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

        @Override
        public ClientHttpRequestFactory get() {

            // Using Apache HTTP client.
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
            return requestFactory;
        }

    }
</code>```

but I have also a InvocationTargetException / NullPointerException

答:
You don't need a builder here anymore as the supplier builds the ClientHttpRequestFactory on demand. Define the RequestFactorySupplier and the RestTemplateBuilder as beans.

    @Bean
    Supplier<ClientHttpRequestFactory> myRequestFactorySupplier() {
        return () -> {
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setConnectTimeout(5000);
            requestFactory.setReadTimeout(5000);
            requestFactory.setBufferRequestBody(false);
            return requestFactory;
        };
    }

    @Bean
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder();
    }
```

<p>Use the factory in the controller like this. </p>

<pre class="lang-java prettyprint-override"><code>@RestController
public class TestController {

    private final RestTemplate restTemplate;

    public TestController(
            RestTemplateBuilder restTemplateBuilder,
            Supplier<ClientHttpRequestFactory> myRequestFactorySupplier
    ) {
            this.restTemplate = restTemplateBuilder
                .requestFactory(myRequestFactorySupplier)
                .build();
    }

</code>```

Of course you could also use a specialized class.

public class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

        @Override
        public ClientHttpRequestFactory get() {
            // Using Apache HTTP client.
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
            return requestFactory;
        }

}
```

<p>using it in the controller as you proposed:</p>

<pre class="lang-java prettyprint-override"><code> public TestController(
     RestTemplateBuilder restTemplateBuilder,
     Supplier<ClientHttpRequestFactory> myRequestFactorySupplier
 ) {
     this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(5000))
                .setReadTimeout(Duration.ofMillis(5000))
                .requestFactory(new MyRequestFactorySupplier())
                .build();
 }

</code>```

Body:
I have this piece of code working fine on a project that uses RestTemplateBuilder 1.5.14

this.restTemplate = restTemplateBuilder
                .setConnectTimeout(connectTimeout)
                .setReadTimeout(readTimeout)
                .requestFactory(new MyHttpComponentFactoryBuilder()
                        .build())
                .build();

After updating to  RestTemplateBuilder 2.1.5 I have this piece of code:

this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(connectTimeout))
                .setReadTimeout(Duration.ofMillis(readTimeout))
                .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass())
                .build();

but when running the code I have a  InvocationTargetException / NullPointerException that dissapears when deleting the line .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass()) , but debugging new MyHttpComponentFactoryBuilder().build().getClass() is not null

I also tried with the solution proposed:

...
.requestFactory(new MyRequestFactorySupplier())
...

class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

        @Override
        public ClientHttpRequestFactory get() {

            // Using Apache HTTP client.
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
            return requestFactory;
        }

    }

but I have also a InvocationTargetException / NullPointerException

Body:
You don't need a builder here anymore as the supplier builds the ClientHttpRequestFactory on demand. Define the RequestFactorySupplier and the RestTemplateBuilder as beans.

    @Bean
    Supplier<ClientHttpRequestFactory> myRequestFactorySupplier() {
        return () -> {
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setConnectTimeout(5000);
            requestFactory.setReadTimeout(5000);
            requestFactory.setBufferRequestBody(false);
            return requestFactory;
        };
    }

    @Bean
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder();
    }

Use the factory in the controller like this.

@RestController
public class TestController {

    private final RestTemplate restTemplate;

    public TestController(
            RestTemplateBuilder restTemplateBuilder,
            Supplier<ClientHttpRequestFactory> myRequestFactorySupplier
    ) {
            this.restTemplate = restTemplateBuilder
                .requestFactory(myRequestFactorySupplier)
                .build();
    }

Of course you could also use a specialized class.

public class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

        @Override
        public ClientHttpRequestFactory get() {
            // Using Apache HTTP client.
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
            return requestFactory;
        }

}

using it in the controller as you proposed:

 public TestController(
     RestTemplateBuilder restTemplateBuilder,
     Supplier<ClientHttpRequestFactory> myRequestFactorySupplier
 ) {
     this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(5000))
                .setReadTimeout(Duration.ofMillis(5000))
                .requestFactory(new MyRequestFactorySupplier())
                .build();
 }


答:
```<code>new Date(now.getTime() + 5 * 60000)
</code>```

<p>as new Date always return Object, </p>

```<code>new Date() - 1 // Return (new Date).getMilliseconds() similar to "1"-1 = 0
new Date() + 1 // Return string similar to "1"+1 = "11"
</code>```

Title: adding and substracting time in Javascript

Body:
new Date(now.getTime() + 5 * 60000)

as new Date always return Object,

new Date() - 1 // Return (new Date).getMilliseconds() similar to "1"-1 = 0
new Date() + 1 // Return string similar to "1"+1 = "11"


问:
Adding DISTINCT to a UNION query
How do I get distinct title.id's from this:

```<code> SELECT Title.id, Title.title FROM titles as Title HAVING points > 0
 UNION ALL
 SELECT Title.id, Title.title FROM titles as Title HAVING points > 1
</code>```

There is more to the query but this should be enough to go on.

答:
You could drop the ALL as others have suggested.

If the two queries use same tables and are different only in the WHERE clause or only in the HAVING clause, you can also use this:

```<code>SELECT Title.id, Title.title FROM titles as Title
WHERE (1st query conditions)
   OR (2nd query conditions)
</code>```

or

```<code>SELECT Title.id, Title.title FROM titles as Title
HAVING (1st query conditions)
    OR (2nd query conditions)
</code>```

Title: Adding DISTINCT to a UNION query

Body:
How do I get distinct title.id's from this:

 SELECT Title.id, Title.title FROM titles as Title HAVING points > 0
 UNION ALL
 SELECT Title.id, Title.title FROM titles as Title HAVING points > 1

There is more to the query but this should be enough to go on.

Body:
You could drop the ALL as others have suggested.

If the two queries use same tables and are different only in the WHERE clause or only in the HAVING clause, you can also use this:

SELECT Title.id, Title.title FROM titles as Title
WHERE (1st query conditions)
   OR (2nd query conditions)

or

SELECT Title.id, Title.title FROM titles as Title
HAVING (1st query conditions)
    OR (2nd query conditions)


问:
Difficulties creating a SSL web service on GKE
I am trying to create an API that serves HTTPS traffic publicly and is reachable by an IP address (not the domain), using a GKE cluster. Docker images have been tested locally. They were capable of serving HTTPS on their own, but as far as I've come to realize, this is not necessary for the setup that I am imagining.

So what I've come up with so far is to have a Kubernetes Service exposing it's 8443 port and having an Ingress load balancer mapping to that port and using self-signed certificates created using this tutorial - basic-ingress-secret referred in the template. The only thing I have skipped is the domain binding given I am not in the possession of a domain. I hoped it would bind the certificate to the external IP, but this is unfortunately not the case (have tried to attach an IP to a CN of the certificate, as some users have noted here).

This is my yaml for service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: some-node
spec:
  selector:
    app: some
  ports:
  - protocol: "TCP"
    port: 8443
    targetPort: 8443
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-node-deploy
spec:
  selector:
    matchLabels:
      app: some
  replicas: 3
  template:
    metadata:
      labels:
        app: some
    spec:
      containers:
      - name: some-container
        image: "gcr.io/some-27417/some:latest"
</code>```

This is my yaml for Ingress:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: some-node
          servicePort: 8443
</code>```

答:
I have found a final solution that suits my current needs.

The issue with the setup above was that I didn't had a nodePort: value setup and that the SSL certificate was not properly working so I have purchased a domain, secured a static IP for the Ingress load balancer using gcloud compute addresses create some-static-ip --globaland pointed that domain to the IP. I have then created a self-signed SSL certificate again following this tutorial and using my new domain.

The final yaml for the service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: some-node
spec:
  selector:
    app: some
  ports:
  - port: 80
    targetPort: 30041
    nodePort: 30041
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-node-deploy
spec:
  selector:
    matchLabels:
      app: some
  replicas: 3
  template:
    metadata:
      labels:
        app: some
    spec:
      containers:
      - name: some-container
        image: "gcr.io/some-project/some:v1"
</code>```

The final yaml for the LB:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.class: "gce"
    kubernetes.io/ingress.global-static-ip-name: "some-static-ip"
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
    - host: my.domain.com
      http:
        paths:
        - path: /some/*
          backend:
            serviceName: some-node
            servicePort: 80
</code>```

The service now serves HTTPS traffic (only 443 port) on my.domain.com/some/* (placeholder domain and path). It is a simple HTTPS service setup that would require only a purchase of CA issued SSL certificate and a proper scaling configuration to be fully productionalized, from the DevOps standpoint. Unless someone has found some serious drawbacks to this setup.

Body:
I am trying to create an API that serves HTTPS traffic publicly and is reachable by an IP address (not the domain), using a GKE cluster. Docker images have been tested locally. They were capable of serving HTTPS on their own, but as far as I've come to realize, this is not necessary for the setup that I am imagining.

So what I've come up with so far is to have a Kubernetes Service exposing it's 8443 port and having an Ingress load balancer mapping to that port and using self-signed certificates created using this tutorial - basic-ingress-secret referred in the template. The only thing I have skipped is the domain binding given I am not in the possession of a domain. I hoped it would bind the certificate to the external IP, but this is unfortunately not the case (have tried to attach an IP to a CN of the certificate, as some users have noted here).

This is my yaml for service:

apiVersion: v1
kind: Service
metadata:
  name: some-node
spec:
  selector:
    app: some
  ports:
  - protocol: "TCP"
    port: 8443
    targetPort: 8443
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-node-deploy
spec:
  selector:
    matchLabels:
      app: some
  replicas: 3
  template:
    metadata:
      labels:
        app: some
    spec:
      containers:
      - name: some-container
        image: "gcr.io/some-27417/some:latest"

This is my yaml for Ingress:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: some-node
          servicePort: 8443

Body:
I have found a final solution that suits my current needs.

The issue with the setup above was that I didn't had a nodePort: value setup and that the SSL certificate was not properly working so I have purchased a domain, secured a static IP for the Ingress load balancer using gcloud compute addresses create some-static-ip --globaland pointed that domain to the IP. I have then created a self-signed SSL certificate again following this tutorial and using my new domain.

The final yaml for the service:

apiVersion: v1
kind: Service
metadata:
  name: some-node
spec:
  selector:
    app: some
  ports:
  - port: 80
    targetPort: 30041
    nodePort: 30041
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-node-deploy
spec:
  selector:
    matchLabels:
      app: some
  replicas: 3
  template:
    metadata:
      labels:
        app: some
    spec:
      containers:
      - name: some-container
        image: "gcr.io/some-project/some:v1"

The final yaml for the LB:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.class: "gce"
    kubernetes.io/ingress.global-static-ip-name: "some-static-ip"
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
    - host: my.domain.com
      http:
        paths:
        - path: /some/*
          backend:
            serviceName: some-node
            servicePort: 80

The service now serves HTTPS traffic (only 443 port) on my.domain.com/some/* (placeholder domain and path). It is a simple HTTPS service setup that would require only a purchase of CA issued SSL certificate and a proper scaling configuration to be fully productionalized, from the DevOps standpoint. Unless someone has found some serious drawbacks to this setup.


问:
PineScript Variables Intermittent Vales during candle making
I have a question regarding variables value during pine script execution.

Below picture shows a scenario on a five minute chart. In the first candle 11.00 am, the close price is 9200. New candle starts at 11.05 am and this candle is in making. Initially the price is 9100 and then changes to 8900, 9150, 9500 and 9300.

Inside the pinescript script there is a boolean "var lessthan9K" which stores the latest value. This variable is set to true if value goes less than 9000. This value remains true till other condition is met - Greater than 10000. It becomes false when value goes above 10000.

When new candle is in making and when price goes to 8900 at 11.06 am, lessthan9k variable becomes true. My question is whether this value remains true end of the candle when final close price is 9300 @ 11.09 am or it resets to false?

Basically how does it work ? During the candle making, any intermittent values are stored or lost (from 1 to 5)?

Thanks

答: What you call intermittent values are lost because of the rollback process in the realtime bar. See the usrman's Calculation based on realtime bars section for an explanation.


问:
Change height of android button through code
I am trying to change the height and width of a button through code at runtime.

My layout xml

```<code>   <Button
    android:id="@+id/button1"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/button2"
    android:background="@drawable/button1_background"
    />
</code>```

Main activity code

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   //some other code
   int displaywidth= getResources().getDisplayMetrics().widthPixels;
    Button f_button = (Button) findViewById(R.id.button1);
    Log.d("F_button width before is",""+ f_button.getWidth());
    f_button.setWidth(displaywidth/2);
    Log.d("F_button width after is",""+ f_button.getWidth());
//some other code
}
</code>```

The Logcat shows both F_button after and before width as "0".

what am I doing wrong.

thanks!.

答:
Yes, I tried to solve the problem for a long time. Ajay's solution made me successful.
For Kotlin programmers it looks like this:</p>

```<code>btn.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 60)
</code>```

Body:
I am trying to change the height and width of a button through code at runtime.

My layout xml

   <Button
    android:id="@+id/button1"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/button2"
    android:background="@drawable/button1_background"
    />

Main activity code

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   //some other code
   int displaywidth= getResources().getDisplayMetrics().widthPixels;
    Button f_button = (Button) findViewById(R.id.button1);
    Log.d("F_button width before is",""+ f_button.getWidth());
    f_button.setWidth(displaywidth/2);
    Log.d("F_button width after is",""+ f_button.getWidth());
//some other code
}

The Logcat shows both F_button after and before width as "0".

what am I doing wrong.

thanks!.

Body:
Yes, I tried to solve the problem for a long time. Ajay's solution made me successful.
For Kotlin programmers it looks like this:

btn.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 60)


问:
Makefile specific to directory structure
I'm trying to compile my project using a makefile. I'm new to makefiles so forgive my ignorance. The problem I'm running into is that I would like the output command to build all of the .o files but If I run it as such it will not build the .o files and instead will try to compile all .o files in the /obj directory.

How would I compile all .o file rules in the output rule?

```<code>The directory structure for this project is:
recipe_book
|-GFX         (source directory)
|-PageManager (source directory)
|-Pages       (source directory)
|-main        (source directory)
|-obj         (.o files directory)
|-out         (application output)
</code>```

Here is my Makefile:

```<code>#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
COMPILER_FLAGS = -w -g

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lSDL2 -lSDL2_image

G++ = g++ -std=c++17 $(LINKER_FLAGS) $(COMPILER_FLAGS)

#Source Directories:
GFX := GFX
PAGE_MANAGER := PageManager
PAGES := Pages

#Object Directory:
OBJ := obj

# Complile the objects into the executable
output: main/main.cpp main/main.hpp $(OBJ)/*.o
    $(G++) main/main.cpp $(OBJ)/*.o -o out/recipe_book.out

#make all object files
#'.' turns them into macros?
#GFX
$(OBJ)/%.o: $(GFX)/%.cpp $(GFX)/%.hpp
    $(G++) -I$(GFX) -c $< -o $@

#PageManager
$(OBJ)/%.o: $(PAGE_MANAGER)/%.cpp $(PAGE_MANAGER)/%.hpp
    $(G++) -I$(PAGE_MANAGER) -c $< -o $@

#Pages
$(OBJ)/%.o: $(PAGES)/%.cpp $(PAGES)/%.hpp
    $(G++) -I$(PAGES) -c $< -o $@

clean:
    rm out/*.out obj/*.o
</code>```

答:
This line:

```<code>output: main/main.cpp main/main.hpp $(OBJ)/*.o
</code>```

cannot work correctly as written.  What does this do?  It tells make, the target output (which, by the way, you never actually create: this rule creates a totally different file out/recipe_book.out, but leave that aside for now) depends on the files main/main.cpp, main/main.hpp, and the expansion of the glob expression obj/*.o.  So, make looks up the files that match the glob expression obj/*.o, which is all the object files that already exist.

If all the object files already exist, then all of them will be linked.  If you haven't created any object files, then none of them will be found (just like if you run ls obj/*.o no files are found) and so none of them will be linked.

You have to list the explicit set of object files that you want t link here.  You can't use glob expressions to find them.

You can use glob expressions to find the source files, which always (presumably) exist, then convert those into the object files.  Maybe something like this:

```<code>SOURCES := $(wildcard $(GFX)/*.cpp $(PAGE_MANAGER)/*.cpp $(PAGES)/*.cpp)
OBJECTS := $(addprefix $(OBJ)/,$(patsubst %.cpp,%.o,$(notdir $(SOURCES))))

output: main/main.cpp main/main.hpp $(OBJECTS)
</code>```

(and by the way, you really should use the real file name for this target not output: in make, all non-phony targets should always have the name of the actual file they create).

Body:
I'm trying to compile my project using a makefile. I'm new to makefiles so forgive my ignorance. The problem I'm running into is that I would like the output command to build all of the .o files but If I run it as such it will not build the .o files and instead will try to compile all .o files in the /obj directory.

How would I compile all .o file rules in the output rule?

The directory structure for this project is:
recipe_book
|-GFX         (source directory)
|-PageManager (source directory)
|-Pages       (source directory)
|-main        (source directory)
|-obj         (.o files directory)
|-out         (application output)

Here is my Makefile:

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
COMPILER_FLAGS = -w -g

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lSDL2 -lSDL2_image

G++ = g++ -std=c++17 $(LINKER_FLAGS) $(COMPILER_FLAGS)

#Source Directories:
GFX := GFX
PAGE_MANAGER := PageManager
PAGES := Pages

#Object Directory:
OBJ := obj

# Complile the objects into the executable
output: main/main.cpp main/main.hpp $(OBJ)/*.o
    $(G++) main/main.cpp $(OBJ)/*.o -o out/recipe_book.out

#make all object files
#'.' turns them into macros?
#GFX
$(OBJ)/%.o: $(GFX)/%.cpp $(GFX)/%.hpp
    $(G++) -I$(GFX) -c $< -o $@

#PageManager
$(OBJ)/%.o: $(PAGE_MANAGER)/%.cpp $(PAGE_MANAGER)/%.hpp
    $(G++) -I$(PAGE_MANAGER) -c $< -o $@

#Pages
$(OBJ)/%.o: $(PAGES)/%.cpp $(PAGES)/%.hpp
    $(G++) -I$(PAGES) -c $< -o $@

clean:
    rm out/*.out obj/*.o

Body:
This line:

output: main/main.cpp main/main.hpp $(OBJ)/*.o

cannot work correctly as written.  What does this do?  It tells make, the target output (which, by the way, you never actually create: this rule creates a totally different file out/recipe_book.out, but leave that aside for now) depends on the files main/main.cpp, main/main.hpp, and the expansion of the glob expression obj/*.o.  So, make looks up the files that match the glob expression obj/*.o, which is all the object files that already exist.

If all the object files already exist, then all of them will be linked.  If you haven't created any object files, then none of them will be found (just like if you run ls obj/*.o no files are found) and so none of them will be linked.

You have to list the explicit set of object files that you want t link here.  You can't use glob expressions to find them.

You can use glob expressions to find the source files, which always (presumably) exist, then convert those into the object files.  Maybe something like this:

SOURCES := $(wildcard $(GFX)/*.cpp $(PAGE_MANAGER)/*.cpp $(PAGES)/*.cpp)
OBJECTS := $(addprefix $(OBJ)/,$(patsubst %.cpp,%.o,$(notdir $(SOURCES))))

output: main/main.cpp main/main.hpp $(OBJECTS)

(and by the way, you really should use the real file name for this target not output: in make, all non-phony targets should always have the name of the actual file they create).


问:
SQL query, three tables
So let's same I'm trying to find actors who are in two movies together (for the purpose of a degrees of separation page). I have databases as such (this is just some made up data):

actors

```<code>id     first_name     last_name    gender
17     brad           pitt         m
2      kevin          bacon        m
</code>```

movies

```<code>id     name               year
20     benjamin button    2008
</code>```

roles

```<code>a_id    m_id     role
17      20       Mr. Benjamin Button
</code>```

So I want to return the names of the movies which both actors are in. I have the first and last names of two actors.

I'm having a lot of trouble getting this to work. What I'm having trouble with, specifically, is the SELECT part

```<code>SELECT name FROM movies JOIN . . .
</code>```

I'm starting with first_name and last_name values for each

答:
declare @FirstActorID int,
    @SecondActorID int;

select m.[name]
from
movies m
inner join [roles] r1 on r1.m_id = m.id and r1.a_id = @FirstActorID
inner join [roles] r2 on r2.m_id = m.id and r2.a_id = @SecondActorID

Title: SQL query, three tables

Body:
So let's same I'm trying to find actors who are in two movies together (for the purpose of a degrees of separation page). I have databases as such (this is just some made up data):

actors

id     first_name     last_name    gender
17     brad           pitt         m
2      kevin          bacon        m

movies

id     name               year
20     benjamin button    2008

roles

a_id    m_id     role
17      20       Mr. Benjamin Button

So I want to return the names of the movies which both actors are in. I have the first and last names of two actors.

I'm having a lot of trouble getting this to work. What I'm having trouble with, specifically, is the SELECT part

SELECT name FROM movies JOIN . . .

I'm starting with first_name and last_name values for each


问:
Stuck with Javascript! - How do I use an If statement to update an element and an array?
I am trying to build a shopping cart function for a project.

This is what I am being asked to do:

Inside the if statement, update the orderTotal element to display Total: $ and the sum of all the prices inside the cartItems array.

1) Under the IF statement I am then entering: orderTotal.innerHTML = "Total: $"
2) At this point I get stuck as I do not know how to add the sum of all prices in the array?

Please help!

var cartItems = [];
var isTotalHidden = true;

var backpack = {
 name: "Backpack",
 price: 400
}

var camera = {
 name: "Camera",
 price: 300
}

function addToCart(item) {
 cartItems.push(item);
 document.getElementById("itemCounter").innerHTML = cartItems.length;
 showTotal();
}

function clickCart() {
 isTotalHidden = !isTotalHidden;
 showTotal();
}

function showTotal() {
 var orderTotal = document.getElementById("orderTotal");
 orderTotal.innerHTML = "";

 if (isTotalHidden === false) {

 }
}```

答:
Your cartItems array has objects that have price property. In your ShowTotal function you can loop over cartItems and save the price of each item. Let me show you</p>

```<code>function showTotal() {
  var orderTotal = document.getElementById("orderTotal");
  //initialize sum to zero
  let sum = 0;
  for (let i = 0; cartItems.length; i++) {
    //add price of each item to sum
    sum = sum + cartItems[i].price;
  }
 orderTotal.innerHTML = sum;
}
</code>```

Body:
Your cartItems array has objects that have price property. In your ShowTotal function you can loop over cartItems and save the price of each item. Let me show you

function showTotal() {
  var orderTotal = document.getElementById("orderTotal");
  //initialize sum to zero
  let sum = 0;
  for (let i = 0; cartItems.length; i++) {
    //add price of each item to sum
    sum = sum + cartItems[i].price;
  }
 orderTotal.innerHTML = sum;
}


问:
Regex for brackets matching
I a using the current regex /(?:^|[^\/\\])\[([\w\s-]*)($|\[)/ to match when user starts to enter chars and enter [some tex, to match this. When he closes it stops the match.

The problem is that i added condition in front, the ?: and if he enter \[ or /[, i am not going to match it.

Well but, if he has something like [text][bla - in this i will match the previous ] bracket and the string will be ][bla, but i don't want this. If he enters [test] [car - this will match the space in front and will be _[car - _ is space.

I want from both to match only from opening bracket to, not before it. Do you guys have some ideas. Thank you!

答:
I am not totally clear, but if I understand you correctly, you would like to detect pairs of [ and ] angle brackets, but skip over / and \ escaped angle brackets like \] and /], correct?

So [aaa] would be one pair, [bbb/[ccc/]ddd] another, and [eee\[fff\]ggg] another.

Here is how you can parse that with three regular expressions:

var str = 'Test [1st], and [2nd\\[with\\]escapes], and [3nd/[more/]escapes][4thNoSpace] text';
var re = /(\[[^\]]*\])/g;
var result = str
.replace(/([\\\/])\]/g, '$1\x01') // replace escapes with tokens
.replace(re, function(m, p1) {    // process bracket pairs
  return '' + p1 + '';
})
.replace(/(.)\x01/g, '$1\]');     // restore escapes from tokens

console.log('before: ' + str);
console.log('result: ' + result);
document.body.insertAdjacentHTML('beforeend', result);```

So, this input:

Test [1st], and [2nd\[with\]escapes], and [3nd/[more/]escapes][4thNoSpace] text

...produces this output:

Test [1st], and [2nd\[with\]escapes], and [3nd/[more/]escapes][4thNoSpace] text

Explanation:

the test input string has 4 angle brackets pairs, two of which have escaped brackets, one follows another without a space

the first regex replaces escaped angle brackets with with a temporary token, so that the second regex does not trip over escaped angle brackets

the second regex identifies proper angle bracket pairs

the third regex restored the tokens back to the escaped angle brackets

the resulting text adds bold tags around the angle bracket pairs to indicate proper parsing

In the future it would be helpful to specify example input strings, and expected output for each input.

Title: Regex for brackets matching

Body:
I am not totally clear, but if I understand you correctly, you would like to detect pairs of [ and ] angle brackets, but skip over / and \ escaped angle brackets like \] and /], correct?

So [aaa] would be one pair, [bbb/[ccc/]ddd] another, and [eee\[fff\]ggg] another.

Here is how you can parse that with three regular expressions:

var str = 'Test [1st], and [2nd\\[with\\]escapes], and [3nd/[more/]escapes][4thNoSpace] text';
var re = /(\[[^\]]*\])/g;
var result = str
.replace(/([\\\/])\]/g, '$1\x01') // replace escapes with tokens
.replace(re, function(m, p1) {    // process bracket pairs
  return '<b>' + p1 + '</b>';
})
.replace(/(.)\x01/g, '$1\]');     // restore escapes from tokens

console.log('before: ' + str);
console.log('result: ' + result);
document.body.insertAdjacentHTML('beforeend', result);

So, this input:

Test [1st], and [2nd\[with\]escapes], and [3nd/[more/]escapes][4thNoSpace] text

...produces this output:

Test <b>[1st]</b>, and <b>[2nd\[with\]escapes]</b>, and <b>[3nd/[more/]escapes]</b><b>[4thNoSpace]</b> text

Explanation:

the test input string has 4 angle brackets pairs, two of which have escaped brackets, one follows another without a space

the first regex replaces escaped angle brackets with with a temporary token, so that the second regex does not trip over escaped angle brackets

the second regex identifies proper angle bracket pairs

the third regex restored the tokens back to the escaped angle brackets

the resulting text adds bold tags around the angle bracket pairs to indicate proper parsing

In the future it would be helpful to specify example input strings, and expected output for each input.


问:
replace ObjectId field with custom string for ObjectIdColumn in TypeORM/MongoDB
I have a NestJs REST API and use TypeORM with MongoDB. I want to create a entity called project. I started with a basic entity and I just read that I should use ObjectIdColumn instead of PrimaryColumn for MongoDB.

```<code>@Entity()
export class Project extends BaseEntity {
  // The technical project name
  @ObjectIdColumn({ generated: false })
  public id: ObjectID;

  // The display name
  @Column({ unique: true })
  public name: string;

  // The project successor
  @Column({ nullable: true })
  public successorId: ObjectID;

  // Configuration stuff for that project
  @Column()
  public configuration: object;
}
</code>```

I would like to know if it's possible to replace that object id column with a primary column of type string. The id field is based on a special pattern, e.g. the name field

my awesome project

would result into

my-awesome-project

for the id field. Sure I made use of generated: false but I have to pass in a custom string instead of an ObjectID. Currently this is not possible because the docs say the ObjectID

Can be a 24 byte hex string, 12 byte binary string or a Number. http://mongodb.github.io/node-mongodb-native/2.1/api/ObjectID.html

So what needs to get done to use a custom string as an ID field? The only thing I can think of is creating a second field e.g. theRealId and treat it like the ID field and ignore the autogenerated ObjectId...

答:
From what I've learnt, here is what you can do

```<code>@Entity()
export class UserEntity
{
  @ObjectIdColumn()
  _id: string;

  @PrimaryColumn()
  id: string;

  // The display name
  @Column({ unique: true })
  public name: string;

  @Column({ nullable: true })
  public successorId: ObjectID;

  @Column()
  public configuration: object;
}
</code>```

MongoDB will use _id as an internal id, that you do not expose through your program (and api, then)

You will work with the id, "normally', and it will be your primary key, generating automatically and so on

Source : personal learning, and Udemy course : NestJS Zero to Hero - Modern TypeScript Back-end Development

Body:
I have a NestJs REST API and use TypeORM with MongoDB. I want to create a entity called project. I started with a basic entity and I just read that I should use ObjectIdColumn instead of PrimaryColumn for MongoDB.

@Entity()
export class Project extends BaseEntity {
  // The technical project name
  @ObjectIdColumn({ generated: false })
  public id: ObjectID;

  // The display name
  @Column({ unique: true })
  public name: string;

  // The project successor
  @Column({ nullable: true })
  public successorId: ObjectID;

  // Configuration stuff for that project
  @Column()
  public configuration: object;
}

I would like to know if it's possible to replace that object id column with a primary column of type string. The id field is based on a special pattern, e.g. the name field

my awesome project

would result into

my-awesome-project

for the id field. Sure I made use of generated: false but I have to pass in a custom string instead of an ObjectID. Currently this is not possible because the docs say the ObjectID

Can be a 24 byte hex string, 12 byte binary string or a Number. http://mongodb.github.io/node-mongodb-native/2.1/api/ObjectID.html

So what needs to get done to use a custom string as an ID field? The only thing I can think of is creating a second field e.g. theRealId and treat it like the ID field and ignore the autogenerated ObjectId...

Body:
From what I've learnt, here is what you can do

@Entity()
export class UserEntity
{
  @ObjectIdColumn()
  _id: string;

  @PrimaryColumn()
  id: string;

  // The display name
  @Column({ unique: true })
  public name: string;

  @Column({ nullable: true })
  public successorId: ObjectID;

  @Column()
  public configuration: object;
}

MongoDB will use _id as an internal id, that you do not expose through your program (and api, then)

You will work with the id, "normally', and it will be your primary key, generating automatically and so on

Source : personal learning, and Udemy course : NestJS Zero to Hero - Modern TypeScript Back-end Development


问:
!== ' ' not allowing the intake of 0 in Javascript calculator
I've knocked up a simple calculator in vanilla JS. However when the user enters a 0 the calculation does nothing. I'd expect it to take 0 for example x it by 10 and give the answer 10. As an example. I'm guessing this line is stopping 0. Any ideas?</p>

```<code>const isValid = field => (field && field !== '' && !isNaN(field));
</code>```

答:
try this out</p>

```<code>const isValid = field => (typeof field !== 'undefined' && field !== '' && !isNaN(field));
</code>```

Body:
I've knocked up a simple calculator in vanilla JS. However when the user enters a 0 the calculation does nothing. I'd expect it to take 0 for example x it by 10 and give the answer 10. As an example. I'm guessing this line is stopping 0. Any ideas?

const isValid = field => (field && field !== '' && !isNaN(field));

Body:
try this out

const isValid = field => (typeof field !== 'undefined' && field !== '' && !isNaN(field));


问:
Function to convert letter-number coordinates to 2D array indices
I'm trying to build a board game where my board is a 2D array of lists.

```<code>self._board = [["A", "B", "C"],
               ["D", "E", "F"],
               ["G", "H", "I"]]
</code>```

How can I write a function that can be used to access each piece by using letter-number coordinates.
So for example I can use the function to get "A" by using converter(A1) or "F" by using converter(B3). I would like to avoid importing any modules.

答:
Ok, so assuming your board is immutable in size pandas is probably the best choice - it provides the indexing for both columns and rows, so:

```<code>import pandas as pd

df=pd.DataFrame(index=list("ABC"), columns=[1,2,3])

# both to assign value and to pull value use .loc[]
df.loc["B", 3]="x"
</code>```

Outputs:

>>> df

     1    2    3
A  NaN  NaN  NaN
B  NaN  NaN    x
C  NaN  NaN  NaN
```

Body:
I'm trying to build a board game where my board is a 2D array of lists.

self._board = [["A", "B", "C"],
               ["D", "E", "F"],
               ["G", "H", "I"]]

How can I write a function that can be used to access each piece by using letter-number coordinates.
So for example I can use the function to get "A" by using converter(A1) or "F" by using converter(B3). I would like to avoid importing any modules.

Body:
Ok, so assuming your board is immutable in size pandas is probably the best choice - it provides the indexing for both columns and rows, so:

import pandas as pd

df=pd.DataFrame(index=list("ABC"), columns=[1,2,3])

# both to assign value and to pull value use .loc[]
df.loc["B", 3]="x"

Outputs:

>>> df

     1    2    3
A  NaN  NaN  NaN
B  NaN  NaN    x
C  NaN  NaN  NaN


问:
How to set PDF height dynamically using 'react-native-html-to-pdf' package?
I am creating a PDF document in react-native. My aim is to create single page,no more pages and while my page's content gets bigger, my single page's height also must get bigger automatically.

```<code>options = {
            width: 675,
            height: ????,
            html: `<div id="myDiv" style="width: 100%; min-height: 850px"> </div>`
            }
</code>```

In the above code, I set myDiv's min-height and when myDiv's height changes dynamically, I want to take this height value and set the option's height automatically. I tried javascript offsetHeight property but it does not work because HTML's inside is completely a string. I tried to use template literals, but i couldn't succeed.

Is there a way to handle this,using template literals or any other ways?

答:
I'm pretty sure it can't be done with react-native-html-to-pdf.

If you read the package code, you'll find it does not include any option like that.

At least on android, you could try to measure the component yourself  using the same tecnique they use to render html before printing it, but it won't be an easy task: you will need to create a webview, inject the code, and extract the height of the desired component.

Try opening an issue on the github project, maybe they will add this feature on a future release.

Body:
I am creating a PDF document in react-native. My aim is to create single page,no more pages and while my page's content gets bigger, my single page's height also must get bigger automatically.

options = {
            width: 675,
            height: ????,
            html: `<div id="myDiv" style="width: 100%; min-height: 850px"> </div>`
            }

In the above code, I set myDiv's min-height and when myDiv's height changes dynamically, I want to take this height value and set the option's height automatically. I tried javascript offsetHeight property but it does not work because HTML's inside is completely a string. I tried to use template literals, but i couldn't succeed.

Is there a way to handle this,using template literals or any other ways?


问:
How to run an apscheduler job which requires app_context
I have a flask app which needs to run some of the methods as background tasks. I have been trying to use apscheduler. Background tasks which do not require app_context run without issue, however, tasks which do require it always throw an error:

```<code>RuntimeError: Working outside of application context.
</code>```

I have tried various options.
1. I have passed app into the job, and altered all the jobs to accept app as a parameter.

I have tried to force the background task to start an app with the following:

```<code>class APScheduler(_BaseAPScheduler):
    def start(self):
        app = create_app()
        apply_config(app)
        with app.app_context():
            super().start()
</code>```

Both options do not appear to have managed to get app_context. Are there any other ways to force the background task to have app_context?

答:
You might have already figured it out, but here is my approach. I would like to you what was yours

In global context create the app

```<code>#Let BackgroundJobs be A module having all logics of batch jobs
from BackgroundJobs import BatchJobs
app = Flask(__name__)

def job1():
     with app.app_context():
          BatchJobs.job1()

def job2():
     with app.app_context():
          BatchJobs.job2()

scheduler = BackgroundScheduler()
scheduler.add_job(job1, 'interval', minutes=5)
scheduler.add_job(job2, 'interval', minutes=5)

scheduler.start()
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False)

</code>```

Inside BackgroundJobs.py, you will have to import proxy to app using below. To have app available, we should invoke the methods in module with app.app_conext()

```<code>from flask import current_app as app

def job1():
     app.logger.info('Job1')

def job2():
     app.logger.info('Job2')
</code>```

Body:
I have a flask app which needs to run some of the methods as background tasks. I have been trying to use apscheduler. Background tasks which do not require app_context run without issue, however, tasks which do require it always throw an error:

RuntimeError: Working outside of application context.

I have tried various options.
1. I have passed app into the job, and altered all the jobs to accept app as a parameter.

I have tried to force the background task to start an app with the following:

class APScheduler(_BaseAPScheduler):
    def start(self):
        app = create_app()
        apply_config(app)
        with app.app_context():
            super().start()

Both options do not appear to have managed to get app_context. Are there any other ways to force the background task to have app_context?

Body:
You might have already figured it out, but here is my approach. I would like to you what was yours

In global context create the app

#Let BackgroundJobs be A module having all logics of batch jobs
from BackgroundJobs import BatchJobs
app = Flask(__name__)

def job1():
     with app.app_context():
          BatchJobs.job1()

def job2():
     with app.app_context():
          BatchJobs.job2()

scheduler = BackgroundScheduler()
scheduler.add_job(job1, 'interval', minutes=5)
scheduler.add_job(job2, 'interval', minutes=5)

scheduler.start()
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False)

Inside BackgroundJobs.py, you will have to import proxy to app using below. To have app available, we should invoke the methods in module with app.app_conext()

from flask import current_app as app

def job1():
     app.logger.info('Job1')

def job2():
     app.logger.info('Job2')