问:
How to get cell name and row id when changing a table using mindmup / editable-table
There is a database. Need an opportunity to edit it. I want to implement this with https://github.com/mindmup/editable-table

When changing the table, a request is sent:

```<code>$('#myTable td').on('change', function(evt, newValue) {
    $.post( "script.php", { value: newValue })
        .done(function( data ) {
                alert( "Data Loaded: " + data );
        });
    ;
});
</code>```

In this regard, the question:

How to find out which cell was changed?

答:
The way I did this was to give the cells a data-row and data-col attribute, e.g.

                                        Category
                                        Dataset 1

                                        Category 1
                                        10

                                        Category 2
                                        8

```
</div>
</div>
</p>

<p>Then, you can get the cell and row by...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>   $(document).ready(function () {
   ////////////////////////////////////////////////
            //Make the data table editable
            // https://github.com/mindmup/editable-table
            ///////////////////////////////////////////////
            $('#data_table').editableTableWidget();

$('#data_table td').on('change', function(evt, newValue) {
// get the row
console.log($(evt.currentTarget).data('row'))
// get the col
console.log($(evt.currentTarget).data('col'))

});

});</code>```

                                        Category
                                        Dataset 1

                                        Category 1
                                        10

                                        Category 2
                                        8

```

Body:
There is a database. Need an opportunity to edit it. I want to implement this with https://github.com/mindmup/editable-table

When changing the table, a request is sent:

$('#myTable td').on('change', function(evt, newValue) {
    $.post( "script.php", { value: newValue })
        .done(function( data ) {
                alert( "Data Loaded: " + data );
        });
    ;
});

In this regard, the question:

How to find out which cell was changed?

Body:
The way I did this was to give the cells a data-row and data-col attribute, e.g.

<table id="chart_data_table" class="table table-bordered">
                                    <tbody>
                                    <tr>
                                        <td data-row="0" data-col="0">Category</td>
                                        <td data-row="0" data-col="1">Dataset 1</td>
                                    </tr>
                                    <tr>
                                        <td data-row="1" data-col="0">Category 1</td>
                                        <td data-row="1" data-col="1" data-type="number">10</td>

                                    </tr>
                                    <tr>
                                        <td data-row="2" data-col="0">Category 2</td>
                                        <td data-row="2" data-col="1" data-type="number">8</td>
                                    </tr>

                                    </tbody>
                                </table>

Then, you can get the cell and row by...

   $(document).ready(function () {
   ////////////////////////////////////////////////
            //Make the data table editable
            // https://github.com/mindmup/editable-table
            ///////////////////////////////////////////////
            $('#data_table').editableTableWidget();

$('#data_table td').on('change', function(evt, newValue) {
// get the row
console.log($(evt.currentTarget).data('row'))
// get the col
console.log($(evt.currentTarget).data('col'))

});

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<script src="https://raw.githubusercontent.com/mindmup/editable-table/master/mindmup-editabletable.js"></script>

<table id="data_table" class="table table-bordered">
                                    <tbody>
                                    <tr>
                                        <td  data-row="0" data-col="0">Category</td>
                                        <td data-row="0" data-col="1">Dataset 1</td>
                                    </tr>
                                    <tr>
                                        <td data-row="1" data-col="0">Category 1</td>
                                        <td data-row="1" data-col="1" >10</td>

                                    </tr>
                                    <tr>
                                        <td data-row="2" data-col="0">Category 2</td>
                                        <td data-row="2" data-col="1" >8</td>
                                    </tr>

                                    </tbody>
                                </table>


来源: stackexchange

问:
AWS EC2 instance not letting TCP connection
I have created an EC2 (Windows) instance on AWS. I want to run a TCP server on this EC2 on TCP port 7889
and want to connect to it from outside world.

I have edited the inbound traffic rule in security group and added TCP rule for 7889 from anywhere.

But unfortunately my TCP client socket can not reach the server through the public ip of the EC2 instance.

Please help.

Note: The same thing worked for me few years ago. My little search has shown me few things like , I need to create VPC, public and private subnets, internet gateway and route tables.Is it true? All these were not required earlier.Is it a new addition?

答:
Yes all you mentioned are absolutely needed. VPC, Subnet, Route table, Internet Gateway and EIP all are required.

The reason it worked for you previously because you might have used the default VPC with all other components already configured. Even now you will be having a default VPC in every AWS region which you can make use of it.

But it's really needed to have basic understanding of how things connect and work together because all these components are very basic and important. Refer AWS documents for more details.

If all the components are cofigured already, check the output of

netstat -nptl

command. The port 7999 should be available and it should be ready to accept any IP (i.e. point to 0.0.0.0)

ContentLicense: CC BY-SA 4.0


问:
Is it wise to manually synchronize database operations and avoiding the inbuilt database synchronization mechanism?
I am making this application which reads and writes from a database and is accessed by multiple users. To avoid concurrency issues I am using mutex. The database that I am using is postgresql. Its documentation says it is ACID compliant and provides various levels of synchronization such as read_committed etc. So I can avoid using mutex and put all my statements in a transaction block and the database will take care of it. But I am not fully confident of using this transaction based approach as I am having trust issues with the database automatic mechanism.

My current approach:

```<code>mutex.lock();
\\perform database operations
mutex.unlock();
</code>```

Alternative approach:

```<code>begin transaction
\\perform database operations
end transaction
</code>```

Is it wise to handle with mutex or should I rely on the database mechanism.
Each user is accessing the database in a separate thread. And database operations are simple. One read and one write. That is all.

答:
If the database is being accessed by multiple users simultaneously, an application level mutex does absolutely nothing to prevent them from stepping on each other on the database side1. You must use the locking constructs provided at the database level (transactions) to achieve what you are after.

A better use case for the application level mutex is to provide resource locking between threads running within the application (which may also be achievable with database transactions, but use the right tool for the job).

1: I have to be careful here: if an application handles multiple users in a single instance, or otherwise shares database objects outside of the database, then a mutex might be a good way to do locking. Even then, it won't protect things on the database (meaning it's not functionality that is built into the DBMS), and it's still probably better to let the database take care of it's own locks.

Body:
I am making this application which reads and writes from a database and is accessed by multiple users. To avoid concurrency issues I am using mutex. The database that I am using is postgresql. Its documentation says it is ACID compliant and provides various levels of synchronization such as read_committed etc. So I can avoid using mutex and put all my statements in a transaction block and the database will take care of it. But I am not fully confident of using this transaction based approach as I am having trust issues with the database automatic mechanism.

My current approach:

mutex.lock();
\\perform database operations
mutex.unlock();

Alternative approach:

begin transaction
\\perform database operations
end transaction

Is it wise to handle with mutex or should I rely on the database mechanism.
Each user is accessing the database in a separate thread. And database operations are simple. One read and one write. That is all.


问:
Android Studio 4.0 shortcuts changed
This week I updated to Android Studio 4.0, and one of the first things I noticed was that some of my favorite shortcuts like CMD+W has changed to CMD+F4 (which the touchbar wont actually show the F keys anymore), and also CMD+O changed to CMD+N.  Is there any way to get them back to what they were to set to in Android Studio 3?</p>

答:
To open the keymap settings, choose File > Settings (on Mac, Android Studio > Preferences) and navigate to the Keymap pane.

Select the short cut you want to modify then add/assign new keys to short cut.

See for more info

Title: Android Studio 4.0 shortcuts changed


问:
SQLite is not creating any table in Android studio
hi i am trying to make a raffle table but however i did created the database but no table is create, the run panel shows that i created it but the sqlite browser shows that there is nothing in it.
here is the code:
in the database java:

```<code>        public void onCreate(SQLiteDatabase db)
    {

        // Note the use of super, which calls the constructor of the SQLiteOpenHelper class,
        // which does the actual work of opening the database.
        Log.d(TAG, "DatabaseHelper onCreate");
        Log.d(TAG, RaffleTable.CREATE_STATEMENT);
        db.execSQL(RaffleTable.CREATE_STATEMENT);

    }
</code>```

in the raffletalbe.java:

```<code>public class RaffleTable {

public static final String TABLE_NAME = "Raffle";

public static final String KEY_ID = "raffle_id";
public static final String KEY_NAME = "raffle_name";
public static final String KEY_PRICE = "price";
public static final String KEY_START = "raffle_start";
public static final String KEY_END = "raffle_end";
public static final String KEY_DESCRIPTION = "raffle_description";
public static final String KEY_TYPE = "raffle_type";
public static final String KEY_PRIZE = "raffle_prize";
public static final String KEY_LIMIT = "raffle_limit";

public static final String CREATE_STATEMENT = "CREATE TABLE "
        + TABLE_NAME
        + " (" + KEY_ID + " integer primary key autoincrement, "
        + KEY_NAME + " string not null, "
        + KEY_DESCRIPTION + " string, "
        + KEY_START + " string not null, "
        + KEY_END + " string not null, "
        + KEY_TYPE +  " integer not null, "
        + KEY_LIMIT + " integer, "
        + KEY_PRIZE + " String, "
        + KEY_PRICE + " real);";
</code>```

what it shows in the run panel:

```<code>D/RaffleDatabase: DatabaseHelper onCreate
CREATE TABLE Raffle (raffle_id integer primary key autoincrement, raffle_name string not null, raffle_description string, raffle_start string not null, raffle_end string not null, raffle_type integer not null, raffle_limit integer, raffle_prize String, price real);
</code>```

here is the code i used to insert the table:

```<code>        Raffle Ruffle1 = new Raffle();
    Ruffle1.setRuffleDes("742 Evergreen Terrace");
    Ruffle1.setRuffleEnd("20190102");
    Ruffle1.setRuffleStart("20190101");
    Ruffle1.setRuffleLimit(5);
    Ruffle1.setRuffleName("testing");
    Ruffle1.setRufflePrize("cooper");
    Ruffle1.setRuffleType("Normal");
    Ruffle1.setRufflePrice(1000);

    Raffle Ruffle2 = new Raffle();
    Ruffle2.setRuffleDes("742 Evergreen Terrace");
    Ruffle2.setRuffleEnd("20190102");
    Ruffle2.setRuffleStart("20190101");
    Ruffle2.setRuffleLimit(5);
    Ruffle2.setRuffleName("testing");
    Ruffle2.setRufflePrize("cooper");
    Ruffle2.setRuffleType("Normal");
    Ruffle2.setRufflePrice(1000);

    RaffleTable.insert(db, Ruffle1);
    RaffleTable.insert(db, Ruffle2);
</code>```

答: There is nothing wrong with your code. You just need to put the updated file in your browser. May be your browser is reading the old file that's why you're not able to read the updated content.</p>

Body:
hi i am trying to make a raffle table but however i did created the database but no table is create, the run panel shows that i created it but the sqlite browser shows that there is nothing in it.
here is the code:
in the database java:

        public void onCreate(SQLiteDatabase db)
    {

        // Note the use of super, which calls the constructor of the SQLiteOpenHelper class,
        // which does the actual work of opening the database.
        Log.d(TAG, "DatabaseHelper onCreate");
        Log.d(TAG, RaffleTable.CREATE_STATEMENT);
        db.execSQL(RaffleTable.CREATE_STATEMENT);

    }

in the raffletalbe.java:

public class RaffleTable {

public static final String TABLE_NAME = "Raffle";

public static final String KEY_ID = "raffle_id";
public static final String KEY_NAME = "raffle_name";
public static final String KEY_PRICE = "price";
public static final String KEY_START = "raffle_start";
public static final String KEY_END = "raffle_end";
public static final String KEY_DESCRIPTION = "raffle_description";
public static final String KEY_TYPE = "raffle_type";
public static final String KEY_PRIZE = "raffle_prize";
public static final String KEY_LIMIT = "raffle_limit";

public static final String CREATE_STATEMENT = "CREATE TABLE "
        + TABLE_NAME
        + " (" + KEY_ID + " integer primary key autoincrement, "
        + KEY_NAME + " string not null, "
        + KEY_DESCRIPTION + " string, "
        + KEY_START + " string not null, "
        + KEY_END + " string not null, "
        + KEY_TYPE +  " integer not null, "
        + KEY_LIMIT + " integer, "
        + KEY_PRIZE + " String, "
        + KEY_PRICE + " real);";

what it shows in the run panel:

D/RaffleDatabase: DatabaseHelper onCreate
CREATE TABLE Raffle (raffle_id integer primary key autoincrement, raffle_name string not null, raffle_description string, raffle_start string not null, raffle_end string not null, raffle_type integer not null, raffle_limit integer, raffle_prize String, price real);

here is the code i used to insert the table:

        Raffle Ruffle1 = new Raffle();
    Ruffle1.setRuffleDes("742 Evergreen Terrace");
    Ruffle1.setRuffleEnd("20190102");
    Ruffle1.setRuffleStart("20190101");
    Ruffle1.setRuffleLimit(5);
    Ruffle1.setRuffleName("testing");
    Ruffle1.setRufflePrize("cooper");
    Ruffle1.setRuffleType("Normal");
    Ruffle1.setRufflePrice(1000);

    Raffle Ruffle2 = new Raffle();
    Ruffle2.setRuffleDes("742 Evergreen Terrace");
    Ruffle2.setRuffleEnd("20190102");
    Ruffle2.setRuffleStart("20190101");
    Ruffle2.setRuffleLimit(5);
    Ruffle2.setRuffleName("testing");
    Ruffle2.setRufflePrize("cooper");
    Ruffle2.setRuffleType("Normal");
    Ruffle2.setRufflePrice(1000);

    RaffleTable.insert(db, Ruffle1);
    RaffleTable.insert(db, Ruffle2);


问:
How to pass computed function into v-bind and v-on?
I know it's simple example, but I'm new to Vue.

I'm sure that error is  where I pointed. I'm trying to call function from computed method. There is no problem if write code straight to v:bind, but once I pass it throug func it gives me error. As well I know that from method functions call as func(), but I guess from computed they have another syntax.

```<code>  <body>
        <div class="container">
            <hr>
            <div class="sample">
            <input type="text" v-bind:value="name" v-on:input="name = $event.target.value">
            <hr>
            <h2>Hello, {{ name }}</h2>
            <input type="button" value="Click on it" v-on:click="addNumber()">
            <hr>
            <div v-for="num in numbers">
                {{ num }}
            </div>
            <input type="button" v-on:click="show" v-bind:title="btnText" > //I'M SURE ERROR IS HERE
            <h2 v-show="showH2">check hide</h2>
            </div>
        <div></div>
        <script>
            let sample = new Vue({
            el: '.sample',
            data:
            {
                showH2: true,
                name: '12344',
                numbers: []
            },
            methods:
            {
                addNumber()
                {
                    let num = Math.floor(Math.random() * 11) - 5;
                    this.numbers.push(num);
                }
            },
            computed:
            {
                btnText()
                {
                    return this.showH2 ? 'Hide' : 'Show';
                },
                sum()
                {
                    let sum = 0;
                    this.numbers.forEach((el) => sum += el);
                    return sum;
                },
                show()
                {
                    this.showH2 = !this.showH2;
                }
            }
            });
        </script>
    </body>
    </html>
</code>```

答: You are perfectly correct when you say- "There is no problem if write code straight to v:bind, but once I pass it through func it gives me error". This is because You don't call a computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Whereas a method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. So if you shift show in methods it will work. vue doc</p>

Body:
I know it's simple example, but I'm new to Vue.

I'm sure that error is  where I pointed. I'm trying to call function from computed method. There is no problem if write code straight to v:bind, but once I pass it throug func it gives me error. As well I know that from method functions call as func(), but I guess from computed they have another syntax.

            <input type="text" v-bind:value="name" v-on:input="name = $event.target.value">

Hello, {{ name }}

            <input type="button" value="Click on it" v-on:click="addNumber()">

                {{ num }}

            <input type="button" v-on:click="show" v-bind:title="btnText" > //I'M SURE ERROR IS HERE

check hide


问:
How to build (Webpack) the Node Js project using PUG Engine?
I am stuck to build the node js project using webpack and I am using pug engine for front end.

My Project Structure:

```<code>bin
controller
  - csv.controller.js
public
  - stylesheets
  - javascript
  - images
routes
  - csv.route.js
  - index.route.js
views
  - layouts
   -- layout.pug
  -index.pug
app.js
</code>```

Package.json File

```<code>{
  "name": "csv",
  "version": "0.0.0",
  "private": true,
  "scripts": {
          "build": "webpack --mode=production",
          "build:dev": "webpack --mode=development",
          "start":"nodemon ./app.js",
          "start:dev": "webpack-dev-server --mode=development"
             },
  "dependencies": {
          "body-parser": "^1.19.0",
          "compression": "^1.7.4",
          "cookie-parser": "~1.4.4",
          "csv-parser": "^2.3.1",
          "csv-writer": "^1.5.0",
          "debug": "~2.6.9",
          "express": "^4.17.1",
          "express-fileupload": "^1.1.6-alpha.5",
          "fast-csv": "^3.4.0",
          "http-errors": "~1.6.3",
          "morgan": "^1.9.1",
          "multer": "^1.4.2",
          "npm-check-updates": "^3.1.23",
          "request": "^2.88.0"
         },
        "devDependencies": {
              "@babel/core": "^7.6.2",
              "@babel/preset-env": "^7.6.2",
              "babel-loader": "^8.0.6",
              "clean-webpack-plugin": "^3.0.0",
              "css-loader": "^3.2.0",
              "extract-text-webpack-plugin": "^3.0.2",
              "file-loader": "^4.2.0",
              "html-webpack-plugin": "^3.2.0",
              "mini-css-extract-plugin": "^0.8.0",
              "pug": "^2.0.4",
              "pug-loader": "^2.4.0",
              "style-loader": "^1.0.0",
              "webpack": "^4.40.2",
              "webpack-cli": "^3.3.9",
              "webpack-dev-server": "^3.8.1",
              "webpack-merge": "^4.2.2"
    }
  }
</code>```

Actually what I want, after build, A dist folder contain a build.js or whatever its name and all public folder assets in the same directory. I tried with some below codes to build the project.

Webpack.config.js

```<code> const path = require("path");
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    const config = {
      entry: {
      app: "./app.js"
             },
      target: "node",
      output: {
      path: path.resolve(__dirname, "dist"),
      filename: "[name].bundle.js"
             },
      devServer: {
      port: 3000
            },
      plugins: [
      new HtmlWebpackPlugin({
         template: "./views/index.pug"
          })
        ],
     module: {
       rules: [
               {
                test: /\.pug$/,
                use: ["pug-loader"]
               },
               {
                test: /\.css$/,
                use: ["style-loader", "css-loader"]
               },
               {
                test: /\.(png|svg|jpg|gif)$/,
                use: ["file-loader"]
                },
               {
                test: [/.js$/],
                exclude: /(node_modules)/,
                  use: {
                      loader: "babel-loader",
                      options: {
                      presets: ["@babel/preset-env"]
                      }
                  }
               },
               {
                   test: /\.css$/,
                   use: ExtractTextPlugin.extract({
                   fallback: "style-loader",
                   use: "css-loader"
                  })
                }
              ]
          }
      };
 module.exports = (env, argv) => {
     if (argv.mode === "development") {
      }
     if (argv.mode === "production") {
      }
     return config;
  };
</code>```

答:
I know this question is old, but just in case somebody is looking for an answer.

You need another Webpack config for app.js, which is express entry point.
Call it webpack.server.js or webpack.server.config.js or whatever convenient. Make sure to include webpack-node-externals:
https://www.npmjs.com/package/webpack-node-externals

It may look something like this:

```<code>//webpack.server.js

const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');

module.exports = {

  return ({
    entry: {
      app: ./src/server/app.js,
    },
    output: {
      path: path.join(__dirname, 'dist'),
      publicPath: '/',
      filename: '[name].js',
    },
    target: 'node',
    node: {
      __dirname: false,
      __filename: false,
    },
    externals: [nodeExternals()],
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    },
  });
};

</code>```

Also use webpack-dev-middleware in your app.js.
See the below link:

https://webpack.js.org/guides/development/

In package.json include a script that looks something like this:

```<code>"server:dev": "webpack --config webpack.config.js && webpack --mode development --config webpack.server.js && node ./dist/app.js",

</code>```

In your webpack.config.js make the entry point the js file that imports your front-end assets..
That is your stylesheets and any other js codes..
Not sure what css framework you are using.
But, I am using tailwindcss and I have a js entry point file that imports tailwindcss and my other js codes.
So essentially you may need two webpack config files one for the front-end and one for the express server.
Hope I am making sense.

Body:
I am stuck to build the node js project using webpack and I am using pug engine for front end.

My Project Structure:

bin
controller
  - csv.controller.js
public
  - stylesheets
  - javascript
  - images
routes
  - csv.route.js
  - index.route.js
views
  - layouts
   -- layout.pug
  -index.pug
app.js

Package.json File

{
  "name": "csv",
  "version": "0.0.0",
  "private": true,
  "scripts": {
          "build": "webpack --mode=production",
          "build:dev": "webpack --mode=development",
          "start":"nodemon ./app.js",
          "start:dev": "webpack-dev-server --mode=development"
             },
  "dependencies": {
          "body-parser": "^1.19.0",
          "compression": "^1.7.4",
          "cookie-parser": "~1.4.4",
          "csv-parser": "^2.3.1",
          "csv-writer": "^1.5.0",
          "debug": "~2.6.9",
          "express": "^4.17.1",
          "express-fileupload": "^1.1.6-alpha.5",
          "fast-csv": "^3.4.0",
          "http-errors": "~1.6.3",
          "morgan": "^1.9.1",
          "multer": "^1.4.2",
          "npm-check-updates": "^3.1.23",
          "request": "^2.88.0"
         },
        "devDependencies": {
              "@babel/core": "^7.6.2",
              "@babel/preset-env": "^7.6.2",
              "babel-loader": "^8.0.6",
              "clean-webpack-plugin": "^3.0.0",
              "css-loader": "^3.2.0",
              "extract-text-webpack-plugin": "^3.0.2",
              "file-loader": "^4.2.0",
              "html-webpack-plugin": "^3.2.0",
              "mini-css-extract-plugin": "^0.8.0",
              "pug": "^2.0.4",
              "pug-loader": "^2.4.0",
              "style-loader": "^1.0.0",
              "webpack": "^4.40.2",
              "webpack-cli": "^3.3.9",
              "webpack-dev-server": "^3.8.1",
              "webpack-merge": "^4.2.2"
    }
  }

Actually what I want, after build, A dist folder contain a build.js or whatever its name and all public folder assets in the same directory. I tried with some below codes to build the project.

Webpack.config.js

 const path = require("path");
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    const config = {
      entry: {
      app: "./app.js"
             },
      target: "node",
      output: {
      path: path.resolve(__dirname, "dist"),
      filename: "[name].bundle.js"
             },
      devServer: {
      port: 3000
            },
      plugins: [
      new HtmlWebpackPlugin({
         template: "./views/index.pug"
          })
        ],
     module: {
       rules: [
               {
                test: /\.pug$/,
                use: ["pug-loader"]
               },
               {
                test: /\.css$/,
                use: ["style-loader", "css-loader"]
               },
               {
                test: /\.(png|svg|jpg|gif)$/,
                use: ["file-loader"]
                },
               {
                test: [/.js$/],
                exclude: /(node_modules)/,
                  use: {
                      loader: "babel-loader",
                      options: {
                      presets: ["@babel/preset-env"]
                      }
                  }
               },
               {
                   test: /\.css$/,
                   use: ExtractTextPlugin.extract({
                   fallback: "style-loader",
                   use: "css-loader"
                  })
                }
              ]
          }
      };
 module.exports = (env, argv) => {
     if (argv.mode === "development") {
      }
     if (argv.mode === "production") {
      }
     return config;
  };

Body:
I know this question is old, but just in case somebody is looking for an answer.

You need another Webpack config for app.js, which is express entry point.
Call it webpack.server.js or webpack.server.config.js or whatever convenient. Make sure to include webpack-node-externals:
https://www.npmjs.com/package/webpack-node-externals

It may look something like this:

//webpack.server.js

const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');

module.exports = {

  return ({
    entry: {
      app: ./src/server/app.js,
    },
    output: {
      path: path.join(__dirname, 'dist'),
      publicPath: '/',
      filename: '[name].js',
    },
    target: 'node',
    node: {
      __dirname: false,
      __filename: false,
    },
    externals: [nodeExternals()],
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    },
  });
};

Also use webpack-dev-middleware in your app.js.
See the below link:

https://webpack.js.org/guides/development/

In package.json include a script that looks something like this:

"server:dev": "webpack --config webpack.config.js && webpack --mode development --config webpack.server.js && node ./dist/app.js",

In your webpack.config.js make the entry point the js file that imports your front-end assets..
That is your stylesheets and any other js codes..
Not sure what css framework you are using.
But, I am using tailwindcss and I have a js entry point file that imports tailwindcss and my other js codes.
So essentially you may need two webpack config files one for the front-end and one for the express server.
Hope I am making sense.


问:
Python function: Find Change from purchase amount
I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back.

Would it be best to set up a dictionary?

答:
Gee, you mean this isn't problem 2b in every programming course any more?  Eh, probably not, they don't seem to teach people how to make change any more either.  (Or maybe they do: is this a homework assignment?)

If you find someone over about 50 and have them make change for you, it works like this.  Say you have a check for $3.52 and you hand the cashier a twnty.  They'll make change by saying "three fifty-two" then

count back three pennies, saying "three, four, five" (3.55)

count back 2 nickels, (3.60, 3.65)

count back a dime (3.75)

a quarter (4 dollars)

a dollar bill (five dollars)

a $5 bill (ten dollars)

a $10 bill (twenty.)

That's at heart a recursive process: you count back the current denomination until the current amount plus the next denomination comes out even.  Then move up to the next denomination.

You can, of course, do it iteratively, as above.

OwnerDisplayName: Jason

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Oddthinking

OwnerDisplayName: Charlie Martin


问:
Split string into parts of equal length c++
I want to iteratively break up a string of arbitrary length into substrings of length = 80 until the size of the final substring is either less than 80 or 0.
Assume the string is not divisible by 80 so length of final substring is not necessarily 80.
What am I doing wrong here?

```<code>#include <string>
#include <math.h>

string sub;

for (int i = 0; i < ceil(str.length()/80); i++) {
            if(str.length()/80 >= 1){
                sub = str.substr(i*80, 80);
            }
            if(str.length()/80 == 0){
                 sub = str.substr(i*80, str.length()%80);
            }
            if(sub.length() <= 0){
                 return;
</code>```

答:
ceil(str.length()/80) is wrong because it's an integer division. ceil(str.length()/80.0) would work better. It feels wrong to be using floating point arithmetic at all however.

```<code>if(str.length()/80 >= 1){
     sub = str.substr(i*80, 80);
}
if(str.length()/80 == 0){
     sub = str.substr(i*80, str.length()%80);
}
</code>```

Seems OK, but it's unnecessarily complex because it is allowed that the second argument to substr exceeds the length of the string, the rest of the string is selected in that case. So this sub = str.substr(i*80, 80); is all you need to do.

Here's how I would code it

```<code>for (size_t i = 0; i < str.size(); i += 80)
{
     string sub = str.substr(i, 80);
     ...
}
</code>```

Body:
I want to iteratively break up a string of arbitrary length into substrings of length = 80 until the size of the final substring is either less than 80 or 0.
Assume the string is not divisible by 80 so length of final substring is not necessarily 80.
What am I doing wrong here?

#include <string>
#include <math.h>

string sub;

for (int i = 0; i < ceil(str.length()/80); i++) {
            if(str.length()/80 >= 1){
                sub = str.substr(i*80, 80);
            }
            if(str.length()/80 == 0){
                 sub = str.substr(i*80, str.length()%80);
            }
            if(sub.length() <= 0){
                 return;

Body:
ceil(str.length()/80) is wrong because it's an integer division. ceil(str.length()/80.0) would work better. It feels wrong to be using floating point arithmetic at all however.

if(str.length()/80 >= 1){
     sub = str.substr(i*80, 80);
}
if(str.length()/80 == 0){
     sub = str.substr(i*80, str.length()%80);
}

Seems OK, but it's unnecessarily complex because it is allowed that the second argument to substr exceeds the length of the string, the rest of the string is selected in that case. So this sub = str.substr(i*80, 80); is all you need to do.

Here's how I would code it

for (size_t i = 0; i < str.size(); i += 80)
{
     string sub = str.substr(i, 80);
     ...
}


问:
How to run your tests in class level parallelism only after one of your class has finished with it's tests
I got stucked in rather unique problem and I'm sure some of you might have faced similar problem at some point.

So I have total 10 Test classes in my testNg suite and I want them to run in parallel. This is easy but the problem is one of my class lets assume class Test A, not only sets up the test data but also tests some functionality of the application, hence I can not use it under BeforeSuite or BeforeTest annotation. The Test data created via the execution of tests under this class is important for other test classes to run, hence I'm really scratching my head how to implement Class level parallelism in such a way that the parallel run only initiate after the tests under Tests A class finishes it's execution.

Summary

Class Test A

```<code>public class TestsA {

   @BeforeClass
   public setupTestClass(){
   -----some code--------
  }
  @Test
  public test1(){
 ------some code---
}
</code>```

I want this TestA class to run first and then instantiate other test classes in parallel.
Any help regarding this would be really appreciated.

Thanks

答:
By default all the Test methods will have a priority '0' value. So if you want a specific test method to execute before all the other tests then you could set the priority as -1 for that particular Test. Lesser the priority first will be its execution in testng. So test with priority as -1 precedes all the other tests with priority '0'.

Example Setting priority for a single Test method

```<code>public class ClassA {

@Test(priority = -1)
public void b(){
    System.out.println("Test1");
}

@Test
public void a(){
    System.out.println("Test2");
}
</code>```

}

Example 2: Setting priority for the entire class

```<code>@Test(priority = -1)
public class ClassA {

public void b(){
    System.out.println("Test1");
}

public void a(){
    System.out.println("Test2");
}
</code>```

}

Output For both the examples:

Test1

Test2

Body:
I got stucked in rather unique problem and I'm sure some of you might have faced similar problem at some point.

So I have total 10 Test classes in my testNg suite and I want them to run in parallel. This is easy but the problem is one of my class lets assume class Test A, not only sets up the test data but also tests some functionality of the application, hence I can not use it under BeforeSuite or BeforeTest annotation. The Test data created via the execution of tests under this class is important for other test classes to run, hence I'm really scratching my head how to implement Class level parallelism in such a way that the parallel run only initiate after the tests under Tests A class finishes it's execution.

Summary

Class Test A

public class TestsA {

   @BeforeClass
   public setupTestClass(){
   -----some code--------
  }
  @Test
  public test1(){
 ------some code---
}

I want this TestA class to run first and then instantiate other test classes in parallel.
Any help regarding this would be really appreciated.

Thanks

Body:
By default all the Test methods will have a priority '0' value. So if you want a specific test method to execute before all the other tests then you could set the priority as -1 for that particular Test. Lesser the priority first will be its execution in testng. So test with priority as -1 precedes all the other tests with priority '0'.

Example Setting priority for a single Test method

public class ClassA {

@Test(priority = -1)
public void b(){
    System.out.println("Test1");
}

@Test
public void a(){
    System.out.println("Test2");
}

}

Example 2: Setting priority for the entire class

@Test(priority = -1)
public class ClassA {

public void b(){
    System.out.println("Test1");
}

public void a(){
    System.out.println("Test2");
}

}

Output For both the examples:

Test1

Test2


问:
Flex / Grid layouts not working on button or fieldset elements
I'm trying to center inner elements of a <button>-tag with flexbox's justify-content: center. But Safari does not center them. I can apply the same style to any other tags and it works as intended (see the
-tag). Only the button is left-aligned.

Try Firefox or Chrome and you can see the difference.

Is there any user agent style I have to overwrite? Or any other solution to this problem?

div {
  display: flex;
  flex-direction: column;
  width: 100%;
}
button, p {
  display: flex;
  flex-direction: row;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <button>
    <span>Test</span>
    <span>Test</span>
  </button>
  <p>
    <span>Test</span>
    <span>Test</span>
  </p>
</div></code>```

And a jsfiddle:
http://jsfiddle.net/z3sfwtn2/2/

答:
Starting Chrome 83, the button now works as inline-grid/grid/inline-flex/flex.

Here is a snippet (for those using Chrome 83 and up):

button {
  display: inline-flex;
  height: 2rem;
  align-items: flex-end;
  width: 4rem;
  -webkit-appearance: none;
  justify-content: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--

The align-items keyword should fail in Chrome 81 or earlier, but work in Chrome 83 or later. To see the error, the button needs styles that make it more of an extrinsic container. In other words, it needs a height or width set.

-->
<button>Hi</button>
<input type="button" value="Hi"></code>```

Body:
I'm trying to center inner elements of a <button>-tag with flexbox's justify-content: center. But Safari does not center them. I can apply the same style to any other tags and it works as intended (see the
-tag). Only the button is left-aligned.

Try Firefox or Chrome and you can see the difference.

Is there any user agent style I have to overwrite? Or any other solution to this problem?

div {
  display: flex;
  flex-direction: column;
  width: 100%;
}
button, p {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

  <button>
    Test
    Test
  </button>

    Test
    Test

And a jsfiddle:
http://jsfiddle.net/z3sfwtn2/2/

Body:
Starting Chrome 83, the button now works as inline-grid/grid/inline-flex/flex.

Here is a snippet (for those using Chrome 83 and up):

button {
  display: inline-flex;
  height: 2rem;
  align-items: flex-end;
  width: 4rem;
  -webkit-appearance: none;
  justify-content: flex-end;
}

<!--

The align-items keyword should fail in Chrome 81 or earlier, but work in Chrome 83 or later. To see the error, the button needs styles that make it more of an extrinsic container. In other words, it needs a height or width set.

-->
<button>Hi</button>
<input type="button" value="Hi">


问:
Baseline correction on epoched EEG dat
I am new to the Neuroscience topic and I am supposed to baseline correct some EEG data that I have already epoched. I have been googling to try to find out how to do this on Matlab but I am not sure what the concept is. Can anyone help? I know it's a very general question but I am not sure what to ask. If someone can point me in the right direction or even tell me how to do it, I'd be very thankful.</p>

答: You have to subtract the mean of the first samples of every channel from the whole length of the channel. Typically the baseline window is 100ms or more before the event.</p>

Title: Baseline correction on epoched EEG dat


问:
Couldnt display data from firebase in recyclerview
I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.

But the values are not getting retrieved. It displays a blank activity. I have attached the code.

Applications.java

```<code>import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Applications extends AppCompatActivity {

    DatabaseReference databaseReference;
    FirebaseDatabase firebaseDatabase;
    RecyclerView recyclerView;
    FirebaseUser user;
    FirebaseAuth mAuth;
    ArrayList<Post> posts;
    MyAdap adap;
    ProgressDialog pd;
    long maxid=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applications);
        recyclerView = findViewById(R.id.work);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        posts = new ArrayList<>();
        pd= new ProgressDialog(Applications.this);
        pd.setMessage("Loading...");
        pd.show();

        getSupportActionBar().setTitle("Your Applications");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Job Applications");

        Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    Post p = ds.getValue(Post.class);
                    posts.add(p);
                }
                pd.dismiss();
                adap = new MyAdap(Applications.this, posts);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                pd.dismiss();
            }
        });
    }
}
</code>```

Posts.java

```<code>    public class Post {
    private String jobtitle, jobtype, company, location;

    public Post() {
    }

    public Post(String jobtitle, String jobtype, String company, String location) {
        this.jobtitle = jobtitle;
        this.jobtype = jobtype;
        this.company = company;
        this.location = location;
    }

    public String getJobtitle() {
        return jobtitle;
    }

    public void setJobtitle(String jobtitle) {
        this.jobtitle = jobtitle;
    }

    public String getJobtype() {
        return jobtype;
    }

    public void setJobtype(String jobtype) {
        this.jobtype = jobtype;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
</code>```

MyAdap.java

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdap extends RecyclerView.Adapter<MyAdap.ViewHolder> {

    Context cb;
    ArrayList<Post> posts;

    public MyAdap(Context c, ArrayList<Post> applications){
        cb=c;
        posts=applications;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.jobTitle.setText(posts.get(position).getJobtitle());
        holder.jobType.setText(posts.get(position).getJobtype());
        holder.location.setText(posts.get(position).getLocation());
        holder.companyName.setText(posts.get(position).getCompany());
    }

    @Override
    public int getItemCount() {
        return posts.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView jobTitle, jobType,companyName,location;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            jobTitle = itemView.findViewById(R.id.jobTitle);
            jobType = itemView.findViewById(R.id.jobType);
            companyName = itemView.findViewById(R.id.companyName);
            location = itemView.findViewById(R.id.location);
        }
    }
}
</code>```

Here is the image of the database.

答:
You are not attaching adapter to recycle view

```<code>adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap)
</code>```

you need to set adpater to recycle view

Body:
I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.

But the values are not getting retrieved. It displays a blank activity. I have attached the code.

Applications.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Applications extends AppCompatActivity {

    DatabaseReference databaseReference;
    FirebaseDatabase firebaseDatabase;
    RecyclerView recyclerView;
    FirebaseUser user;
    FirebaseAuth mAuth;
    ArrayList<Post> posts;
    MyAdap adap;
    ProgressDialog pd;
    long maxid=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applications);
        recyclerView = findViewById(R.id.work);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        posts = new ArrayList<>();
        pd= new ProgressDialog(Applications.this);
        pd.setMessage("Loading...");
        pd.show();

        getSupportActionBar().setTitle("Your Applications");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Job Applications");

        Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    Post p = ds.getValue(Post.class);
                    posts.add(p);
                }
                pd.dismiss();
                adap = new MyAdap(Applications.this, posts);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                pd.dismiss();
            }
        });
    }
}

Posts.java

    public class Post {
    private String jobtitle, jobtype, company, location;

    public Post() {
    }

    public Post(String jobtitle, String jobtype, String company, String location) {
        this.jobtitle = jobtitle;
        this.jobtype = jobtype;
        this.company = company;
        this.location = location;
    }

    public String getJobtitle() {
        return jobtitle;
    }

    public void setJobtitle(String jobtitle) {
        this.jobtitle = jobtitle;
    }

    public String getJobtype() {
        return jobtype;
    }

    public void setJobtype(String jobtype) {
        this.jobtype = jobtype;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

MyAdap.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdap extends RecyclerView.Adapter<MyAdap.ViewHolder> {

    Context cb;
    ArrayList<Post> posts;

    public MyAdap(Context c, ArrayList<Post> applications){
        cb=c;
        posts=applications;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.jobTitle.setText(posts.get(position).getJobtitle());
        holder.jobType.setText(posts.get(position).getJobtype());
        holder.location.setText(posts.get(position).getLocation());
        holder.companyName.setText(posts.get(position).getCompany());
    }

    @Override
    public int getItemCount() {
        return posts.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView jobTitle, jobType,companyName,location;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            jobTitle = itemView.findViewById(R.id.jobTitle);
            jobType = itemView.findViewById(R.id.jobType);
            companyName = itemView.findViewById(R.id.companyName);
            location = itemView.findViewById(R.id.location);
        }
    }
}

Here is the image of the database.

Body:
You are not attaching adapter to recycle view

adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap)

you need to set adpater to recycle view


问:
Replace table column value in Apache POI
I am using apache POI 3.7. I am trying to replace the value of a table column in a word document (docx). However, what I have done is it keeps appending the value of the current value in the document. But if a table column value is null, it places the value. Can you give me some thoughts how to resolve this. Below is the code I have done so far.

Thanks in advance.

```<code>package test.doc;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class POIDocXTableTest {

    public static void main(String[] args)throws IOException {
        String fileName = "C:\\Test.docx";
        InputStream fis = new FileInputStream(fileName);
        XWPFDocument document = new XWPFDocument(fis);
        List<XWPFParagraph> paragraphs = document.getParagraphs();

        for (int x=0; x<paragraphs.size();x++)
        {
            XWPFParagraph paragraph = paragraphs.get(x);
            System.out.println(paragraph.getParagraphText());
        }
        List<XWPFTable> tables = document.getTables();
        for (int x=0; x<tables.size();x++)
        {
            XWPFTable table = tables.get(x);
            List<XWPFTableRow> tableRows = table.getRows();
            tableRows.remove(x);
            for (int r=0; r<tableRows.size();r++)
            {
                System.out.println("Row "+ (r+1)+ ":");
                XWPFTableRow tableRow = tableRows.get(r);
                List<XWPFTableCell> tableCells = tableRow.getTableCells();
                for (int c=0; c<tableCells.size();c++)
                {
                    System.out.print("Column "+ (c+1)+ ": ");
                    XWPFTableCell tableCell = tableCells.get(c);
                    //tableCell.setText("TAE");
                    String tableCellVal = tableCell.getText();
                    if ((c+1)==2){
                        if (tableCellVal!=null){
                            if (tableCellVal.length()>0){
                                 char c1 = tableCellVal.charAt(0);
                                 String s2 = "-TEST";
                                 char c2 = s2.charAt(0);
                                 String test = tableCell.getText().replace(tableCellVal,s2);
                                 tableCell.setText(test);
                            }else{
                                //tableCell.setText("NULL");
                            }
                        }
                    }
                    System.out.println("tableCell.getText(" + (c) + "):" + tableCellVal);
                }
            }
            System.out.println("\n");
        }
        OutputStream out = new FileOutputStream(fileName);
        document.write(out);
        out.close();
    }
}
</code>```

答:
Adding on to Josh's solution, the map I am building has ended up with over a thousand tags and continues to grow. To cut down on processing, I decided to build a small subset of the tags that I know appear in the paragraph, typically ending up with a map of only one or two tags that I then pass as the Map to the replaceInParagraphs method provided above. Also, using the Substitution object to store the substitution text, allows me to add methods into that object (such as formatting) that I can call once the substitution has been completed. Using the subset Map also allows me to know what replacements have been made in any paragraph.

```<code>private Map<String, Substitution> buildTagList(Map<String, Substitution> replacements, List<XWPFParagraph> xwpfParagraphs, String start, String end) {

    Map<String, Substitution> returnMap = new HashMap<String, Substitution> ();
    for (XWPFParagraph paragraph : xwpfParagraphs) {
        List<XWPFRun> runs = paragraph.getRuns();
        // Check is there is a tag in the paragraph
        TextSegment found = paragraph.searchText(start, new PositionInParagraph());
        String runText = "";
        XWPFRun run = null;
        if ( found != null ) {
            StringBuilder b = new StringBuilder();
            for (int runPos = found.getBeginRun(); runPos < runs.size(); runPos++) {
                run = runs.get(runPos);
                b.append(run.getText(run.getTextPosition()));
                runText = b.toString();
            }
            // Now we need to find all tags in the run
            boolean finished = false;
            int tagStart = 0;
            int tagEnd = 0;
            while ( ! finished ) {
                // get the first tag
                tagStart = runText.indexOf(start,tagStart);
                tagEnd = runText.indexOf(end, tagEnd);
                if ( tagStart >= 0 ) {
                    String tag = runText.substring(tagStart, tagEnd + end.length());
                    Substitution s = replacements.get(tag);
                    if (s != null) {
                        returnMap.putIfAbsent(tag,s);
                    }
                }
                else
                    finished = true;
                tagStart = tagEnd + end.length();
                tagEnd = tagStart;
            }
        }
    }
    return returnMap;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using apache POI 3.7. I am trying to replace the value of a table column in a word document (docx). However, what I have done is it keeps appending the value of the current value in the document. But if a table column value is null, it places the value. Can you give me some thoughts how to resolve this. Below is the code I have done so far.

Thanks in advance.

package test.doc;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class POIDocXTableTest {

    public static void main(String[] args)throws IOException {
        String fileName = "C:\\Test.docx";
        InputStream fis = new FileInputStream(fileName);
        XWPFDocument document = new XWPFDocument(fis);
        List<XWPFParagraph> paragraphs = document.getParagraphs();

        for (int x=0; x<paragraphs.size();x++)
        {
            XWPFParagraph paragraph = paragraphs.get(x);
            System.out.println(paragraph.getParagraphText());
        }
        List<XWPFTable> tables = document.getTables();
        for (int x=0; x<tables.size();x++)
        {
            XWPFTable table = tables.get(x);
            List<XWPFTableRow> tableRows = table.getRows();
            tableRows.remove(x);
            for (int r=0; r<tableRows.size();r++)
            {
                System.out.println("Row "+ (r+1)+ ":");
                XWPFTableRow tableRow = tableRows.get(r);
                List<XWPFTableCell> tableCells = tableRow.getTableCells();
                for (int c=0; c<tableCells.size();c++)
                {
                    System.out.print("Column "+ (c+1)+ ": ");
                    XWPFTableCell tableCell = tableCells.get(c);
                    //tableCell.setText("TAE");
                    String tableCellVal = tableCell.getText();
                    if ((c+1)==2){
                        if (tableCellVal!=null){
                            if (tableCellVal.length()>0){
                                 char c1 = tableCellVal.charAt(0);
                                 String s2 = "-TEST";
                                 char c2 = s2.charAt(0);
                                 String test = tableCell.getText().replace(tableCellVal,s2);
                                 tableCell.setText(test);
                            }else{
                                //tableCell.setText("NULL");
                            }
                        }
                    }
                    System.out.println("tableCell.getText(" + (c) + "):" + tableCellVal);
                }
            }
            System.out.println("\n");
        }
        OutputStream out = new FileOutputStream(fileName);
        document.write(out);
        out.close();
    }
}

Body:
Adding on to Josh's solution, the map I am building has ended up with over a thousand tags and continues to grow. To cut down on processing, I decided to build a small subset of the tags that I know appear in the paragraph, typically ending up with a map of only one or two tags that I then pass as the Map to the replaceInParagraphs method provided above. Also, using the Substitution object to store the substitution text, allows me to add methods into that object (such as formatting) that I can call once the substitution has been completed. Using the subset Map also allows me to know what replacements have been made in any paragraph.

private Map<String, Substitution> buildTagList(Map<String, Substitution> replacements, List<XWPFParagraph> xwpfParagraphs, String start, String end) {

    Map<String, Substitution> returnMap = new HashMap<String, Substitution> ();
    for (XWPFParagraph paragraph : xwpfParagraphs) {
        List<XWPFRun> runs = paragraph.getRuns();
        // Check is there is a tag in the paragraph
        TextSegment found = paragraph.searchText(start, new PositionInParagraph());
        String runText = "";
        XWPFRun run = null;
        if ( found != null ) {
            StringBuilder b = new StringBuilder();
            for (int runPos = found.getBeginRun(); runPos < runs.size(); runPos++) {
                run = runs.get(runPos);
                b.append(run.getText(run.getTextPosition()));
                runText = b.toString();
            }
            // Now we need to find all tags in the run
            boolean finished = false;
            int tagStart = 0;
            int tagEnd = 0;
            while ( ! finished ) {
                // get the first tag
                tagStart = runText.indexOf(start,tagStart);
                tagEnd = runText.indexOf(end, tagEnd);
                if ( tagStart >= 0 ) {
                    String tag = runText.substring(tagStart, tagEnd + end.length());
                    Substitution s = replacements.get(tag);
                    if (s != null) {
                        returnMap.putIfAbsent(tag,s);
                    }
                }
                else
                    finished = true;
                tagStart = tagEnd + end.length();
                tagEnd = tagStart;
            }
        }
    }
    return returnMap;
}


问:
How can I save the headers and values in Html

```

<p>My purpose is to extract this output into a table and save it as a csv file. How can i extract this script as i want?</p>

<p>all dates should be on top, all names should be on the far right, all values should be between the two.</p>

```Hisse      2012.12             2013.3             2013.4 ...
ANA      1,114,919,783.60   1,142,792,778.19     1,091,028,645.38  ...
DEN      55,200,000.00      55,920,000.00        45,960,000.00  ....
.
.
.
```

答: According to the provided

Title: How can I save the headers and values in Html <script> as a table in the csv file?

Body:
I'm new to writing code. Using slenium and beautifulsoup, I managed to reach the script I want among dozens of scripts on the web page. I am looking for script [17]. When these codes are executed, the script [17] gives a result as follows.

the last part of my codes

html=driver.page_source
soup=BeautifulSoup(html, "html.parser")
scripts=soup.find_all("script")
x=scripts[17]
print(x)

result, output
note: The list of dates is ahead of the script [17]. slide the bar. Dummy Data

Dummy Data

My purpose is to extract this output into a table and save it as a csv file. How can i extract this script as i want?

all dates should be on top, all names should be on the far right, all values should be between the two.

Hisse      2012.12             2013.3             2013.4 ...
ANA      1,114,919,783.60   1,142,792,778.19     1,091,028,645.38  ...
DEN      55,200,000.00      55,920,000.00        45,960,000.00  ....
.
.
.

Body:
According to the provided <script> in your question, you can do something like code below to have a list of Dates for each name ANA, DEN ..:

for _ in range(1, len(aaa.split("<b>'"))-1):
  s = aaa.split("<b>'")[_].split("'")
  print(_)
  lst = []
  for i in s:
    if "</B>" in i:
      name = i.split('>')[1].split("<")[0]
      print("{} = ".format(name), end="")
    if any(j.isdigit() for j in i) and ',' in i:
      lst.append(i)
  print(lst)

It's just an example code, so it's not that beautiful :)

Hope this will help you.


问:
Loading spinner is not hiding after response is retrieved in component
I have an Angular app that includes an authentication module. I am currently working on the registration component and would like to include a loading spinner that by default is hidden then displays while waiting for the data to return.

For this use case I would like the spinner to start after the form is submitted and hide once the response is received from the observable.

Currently, everything works except the spinner doesn't hide once the response is received. I can even see my flag isLoading change to false but the spinner just keeps spinning.

Here is my component code for the registration:
registration.component.ts

```<code>import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AuthService } from '@modules/auth/services';

@Component({
    selector: 'sb-register',
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl: './register.component.html',
    styleUrls: ['register.component.scss'],
})
export class RegisterComponent {
    isLoading = false;

    constructor(private authService: AuthService) { }
    // ngOnInit() {}
    onSubmit(form: NgForm) {
        if (!form.valid) {
            return;
        }
        const firstName = form.value.firstName;
        const lastName = form.value.lastName;
        const email = form.value.email;
        const password = form.value.password;

        this.isLoading = true;
        this.authService.signup(firstName, lastName, email, password).subscribe(
            resData => {
                console.log(resData);
                this.isLoading = false;
                console.log(this.isLoading);
            },
            error => {
                console.log(error);
                this.isLoading = false;
            }
        );

        form.reset();
    }
}
</code>```

and here is my corresponding template:
registration.component.html

```<code><sb-layout-auth>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-7">
                <div class="card shadow-lg border-0 rounded-lg mt-5">
                    <div class="card-header">
                        <h3 class="text-center font-weight-light my-4">Create Account</h3>
                    </div>
                    <div class="card-body">
                    <div *ngIf="isLoading"  style="text-align: center;">
                        <sb-loading-spinner></sb-loading-spinner>
                    </div>
                        <form #authForm="ngForm" (ngSubmit)="onSubmit(authForm)" *ngIf="!isLoading">
                            <div class="form-row">
                                <div class="col-md-6">
                                    <div class="form-group"><label class="small mb-1" for="inputFirstName">First
                                            Name</label>
                                            <input
                                                class="form-control py-4"
                                                id="firstName"
                                                type="text"
                                                placeholder="Enter first name"
                                                ngModel
                                                name="firstName"
                                                required
                                            />
                                        </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group"><label class="small mb-1" for="inputLastName">Last
                                            Name</label>
                                            <input
                                                class="form-control py-4"
                                                id="lastName"
                                                type="text"
                                                placeholder="Enter last name"
                                                ngModel
                                                name="lastName"
                                                required
                                            />
                                        </div>
                                </div>
                            </div>
                            <div class="form-group"><label class="small mb-1"
                                    for="inputEmailAddress">Email</label>
                                    <input
                                        class="form-control py-4"
                                        type="email"
                                        aria-describedby="emailHelp"
                                        placeholder="Enter email address"
                                        type="email"
                                        id="email"
                                        class="form-control"
                                        ngModel
                                        name="email"
                                        required
                                        email
                                    />
                                </div>
                            <div class="form-row">
                                <div class="col-md-6">
                                    <div class="form-group"><label class="small mb-1"
                                            for="inputPassword">Password</label>
                                            <input
                                            class="form-control py-4"
                                            type="password"
                                            placeholder="password"
                                            type="password"
                                            id="password"
                                            ngModel
                                            name="password"
                                            required
                                            minlength="6"
                                            placeholder="Enter password"
                                            />
                                        </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group"><label class="small mb-1" for="inputConfirmPassword">Confirm
                                            Password</label>
                                            <input
                                                class="form-control py-4"
                                                type="password"
                                                placeholder="Confirm password"
                                                type="password"
                                                id="confirm_password"
                                                ngModel
                                                name="confirm_password"
                                                required
                                                minlength="6"
                                                placeholder="Enter password"
                                                />
                                            </div>
                                </div>
                            </div>
                            <div class="form-group mt-4 mb-0">
                                <!-- <a class="btn btn-primary btn-block" -->
                            <button
                                class="btn btn-primary btn-block"
                                type="submit"
                                [disabled]="!authForm.valid"
                            >Create Account
                            </button>
                                    <!-- routerLink="/dashboard">Create Account</a></div> -->
                            </div>
                        </form>
                    </div>
                    <div class="card-footer text-center">
                        <div class="small"><a routerLink="/auth/login">Have an account? Go to login</a></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</sb-layout-auth>
</code>```

Here is my auth service as well that generates the observable:
auth.service.ts
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';

```<code>interface AuthResponseData {
    status: string,
    res: string,
    message: string
}

@Injectable({ providedIn: 'root' })
export class AuthService {
    constructor(private http: HttpClient) { }

    signup(firstName: string, lastName: string, email: string, password: string) {
        return this.http.post<AuthResponseData>(
            'http://localhost:5000/v1/auth/register',
            {
                firstName: firstName,
                lastName: lastName,
                email: email,
                password: password
            }
        );
    }

    login(email: string, password: string) {
        return this.http.post<AuthResponseData>(
            'http://localhost:5000/v1/auth/login',
            {
                email: email,
                password: password
            }
        );
    }
}
</code>```

答: Your component is using On Push change detection, which means change detection will only run when Inputs change or an event was triggered. Setting loading inside the subscription handler wont cause a change detection cycle. You could inject ChangeDetectorRef and call markForCheck() after setting loading to force a check.

Body:
I have an Angular app that includes an authentication module. I am currently working on the registration component and would like to include a loading spinner that by default is hidden then displays while waiting for the data to return.

For this use case I would like the spinner to start after the form is submitted and hide once the response is received from the observable.

Currently, everything works except the spinner doesn't hide once the response is received. I can even see my flag isLoading change to false but the spinner just keeps spinning.

Here is my component code for the registration:
registration.component.ts

import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AuthService } from '@modules/auth/services';

@Component({
    selector: 'sb-register',
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl: './register.component.html',
    styleUrls: ['register.component.scss'],
})
export class RegisterComponent {
    isLoading = false;

    constructor(private authService: AuthService) { }
    // ngOnInit() {}
    onSubmit(form: NgForm) {
        if (!form.valid) {
            return;
        }
        const firstName = form.value.firstName;
        const lastName = form.value.lastName;
        const email = form.value.email;
        const password = form.value.password;

        this.isLoading = true;
        this.authService.signup(firstName, lastName, email, password).subscribe(
            resData => {
                console.log(resData);
                this.isLoading = false;
                console.log(this.isLoading);
            },
            error => {
                console.log(error);
                this.isLoading = false;
            }
        );

        form.reset();
    }
}

and here is my corresponding template:
registration.component.html

<sb-layout-auth>

Create Account

                        <sb-loading-spinner></sb-loading-spinner>

                        <form #authForm="ngForm" (ngSubmit)="onSubmit(authForm)" *ngIf="!isLoading">

First
                                            Name
                                            <input
                                                class="form-control py-4"
                                                id="firstName"
                                                type="text"
                                                placeholder="Enter first name"
                                                ngModel
                                                name="firstName"
                                                required
                                            />

Last
                                            Name
                                            <input
                                                class="form-control py-4"
                                                id="lastName"
                                                type="text"
                                                placeholder="Enter last name"
                                                ngModel
                                                name="lastName"
                                                required
                                            />

Email
                                    <input
                                        class="form-control py-4"
                                        type="email"
                                        aria-describedby="emailHelp"
                                        placeholder="Enter email address"
                                        type="email"
                                        id="email"
                                        class="form-control"
                                        ngModel
                                        name="email"
                                        required
                                        email
                                    />

Password
                                            <input
                                            class="form-control py-4"
                                            type="password"
                                            placeholder="password"
                                            type="password"
                                            id="password"
                                            ngModel
                                            name="password"
                                            required
                                            minlength="6"
                                            placeholder="Enter password"
                                            />

Confirm
                                            Password
                                            <input
                                                class="form-control py-4"
                                                type="password"
                                                placeholder="Confirm password"
                                                type="password"
                                                id="confirm_password"
                                                ngModel
                                                name="confirm_password"
                                                required
                                                minlength="6"
                                                placeholder="Enter password"
                                                />

                            <button
                                class="btn btn-primary btn-block"
                                type="submit"
                                [disabled]="!authForm.valid"
                            >Create Account
                            </button>

                        </form>

Have an account? Go to login

</sb-layout-auth>

Here is my auth service as well that generates the observable:
auth.service.ts
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';

interface AuthResponseData {
    status: string,
    res: string,
    message: string
}

@Injectable({ providedIn: 'root' })
export class AuthService {
    constructor(private http: HttpClient) { }

    signup(firstName: string, lastName: string, email: string, password: string) {
        return this.http.post<AuthResponseData>(
            'http://localhost:5000/v1/auth/register',
            {
                firstName: firstName,
                lastName: lastName,
                email: email,
                password: password
            }
        );
    }

    login(email: string, password: string) {
        return this.http.post<AuthResponseData>(
            'http://localhost:5000/v1/auth/login',
            {
                email: email,
                password: password
            }
        );
    }
}


问:
How to protect a button in disabled mode?
I want to disable a button if user doesnt have rights to access it. I am
                            disabling at Page_Load event

```<code> Page_Load() {
      if(!userhasrights) {
           btn.Enabled=false;
      }
 }
</code>```

but after rendering asp.net just sets its disabled property to disabled which
                        a hacker can easily set to 'true' & can access the button. How can i
                        protect my button in disabled mode?

答:
As per knowledge and experience security should apply as close as your code need it.

Like just before executing code that required special previledge.

Body:
I want to disable a button if user doesnt have rights to access it. I am
                            disabling at Page_Load event

 Page_Load() {
      if(!userhasrights) {
           btn.Enabled=false;
      }
 }

but after rendering asp.net just sets its disabled property to disabled which
                        a hacker can easily set to 'true' & can access the button. How can i
                        protect my button in disabled mode?


问:
Playing encrypted MP4

I'm making a (local - Multi-Platform) video protection app but I don't know what is the right solution to first "encrypt->save on HDD" and then "load from HDD->decrypt->play" encrypted video.

I read about MPEG-DASH and some DRMs and found this Bento4 command:

```<code>mp4dash --encryption-key=000102030405060708090a0b0c0d0e0f:00112233445566778899aabbccddeeff --encryption-args="--property 1:ClearLeadFragments:10 --property 2:ClearLeadFragments:10" movie.mp4
</code>```

but I'm not sure that MPEG-DASH can be a part of solution or not.
 How can I solve this?

答: HLS + S3 + CloudFront + MediaConvert + VideoJS.</p>

Title: Playing encrypted MP4

Body:
I'm making a (local - Multi-Platform) video protection app but I don't know what is the right solution to first "encrypt->save on HDD" and then "load from HDD->decrypt->play" encrypted video.

I read about MPEG-DASH and some DRMs and found this Bento4 command:

mp4dash --encryption-key=000102030405060708090a0b0c0d0e0f:00112233445566778899aabbccddeeff --encryption-args="--property 1:ClearLeadFragments:10 --property 2:ClearLeadFragments:10" movie.mp4

but I'm not sure that MPEG-DASH can be a part of solution or not.
 How can I solve this?


问:
How to nest multiple left join and subqueries in SQL
How can I nest two subqueries and two left joins at the same time? I currently have my query (query1) as below which works perfect..  But it involves connecting two outside queries which have to be updated separtely by data date.

I want to extend query1 by applying subquery (query2) out for practice and to also update everything in one script.

NOTE:  Query is written in MS Access.

Any help is much appreciated!

```<code>SELECT DISTINCT
Acct.AccountNumber
, Acct.ABCat AS Cat
, Acct.fName AS FirstName
, Acct.lName AS LastName
, Acct.Age AS Age
, o.Type, o.OFirstLoginDate
, o.OLastLoginDate
, m.Type
, m.LstDepDate AS LastDepDate
FROM
table1 AS Acct
LEFT JOIN
        OB_table AS o
        ON Acct.AccountNumber = o.AccountNumber

LEFT JOIN
        MB_table AS m
        ON Acct.AccountNumber = m.AccountNumber
WHERE
Acct.Cat IN (9,12,16,17)
AND Acct.DataDate = 20200430
AND Acct.Status = 'Open';
</code>```

Query2
Using Subqueries and Left Join
I get the error

```<code>Syntax error (missing operator) in query expression 'Acct.AccountNumber = o.AccountNumber
LEFT JOIN
(SELECT DISTINCT
ParentAccount AS AccountNumber
,TYPE
,LstDepDate AS LastDepDate
FROM MBtable
WHERE ProcessDate = 20200430
</code>```

```<code>SELECT DISTINCT
Acct.AccountNumber
, Acct.ABCat AS Cat
, Acct.fName AS FirstName
, Acct.lName AS LastName
, Acct.Age AS Age
, o.Type, o.OFirstLoginDate
, o.OLastLoginDate
, m.Type
, m.LstDepDate AS LastDepDate
FROM
table1 AS Acct
LEFT JOIN
(
SELECT DISTINCT
Online.Account AS AccountNumber
, Online.TYPE
, Online.OBFLDate AS OFirstLoginDate
, Online.OBLLDate AS OLastLoginDate
FROM OBtable AS Online
WHERE Online.DataDate=20200430
And Online.OBFLDate Is Not Null
)
AS o
ON Acct.AccountNumber = o.AccountNumber
LEFT JOIN
(
SELECT DISTINCT
ParentAccount AS AccountNumber
, TYPE
, LstDepDate AS LastDepDate
FROM MBtable
WHERE ProcessDate = 20200430
AND FDate IS NOT NULL
ORDER BY LDate DESC
)
AS m
ON Acct.AccountNumber = m.AccountNumber
WHERE Acct.Cat IN (9,12,16,17)
 AND Acct.DataDate=20200430
AND Acct.Status = 'Open';
</code>```

答:
You don't give details on the meaning of "does not work".  Still I think your case can be a good candidate for the usage of "outer apply", if you use MS SQL Server.
Real life example, when to use OUTER / CROSS APPLY in SQL</p>

Body:
How can I nest two subqueries and two left joins at the same time? I currently have my query (query1) as below which works perfect..  But it involves connecting two outside queries which have to be updated separtely by data date.

I want to extend query1 by applying subquery (query2) out for practice and to also update everything in one script.

NOTE:  Query is written in MS Access.

Any help is much appreciated!

SELECT DISTINCT
Acct.AccountNumber
, Acct.ABCat AS Cat
, Acct.fName AS FirstName
, Acct.lName AS LastName
, Acct.Age AS Age
, o.Type, o.OFirstLoginDate
, o.OLastLoginDate
, m.Type
, m.LstDepDate AS LastDepDate
FROM
table1 AS Acct
LEFT JOIN
        OB_table AS o
        ON Acct.AccountNumber = o.AccountNumber

LEFT JOIN
        MB_table AS m
        ON Acct.AccountNumber = m.AccountNumber
WHERE
Acct.Cat IN (9,12,16,17)
AND Acct.DataDate = 20200430
AND Acct.Status = 'Open';

Query2
Using Subqueries and Left Join
I get the error

Syntax error (missing operator) in query expression 'Acct.AccountNumber = o.AccountNumber
LEFT JOIN
(SELECT DISTINCT
ParentAccount AS AccountNumber
,TYPE
,LstDepDate AS LastDepDate
FROM MBtable
WHERE ProcessDate = 20200430

SELECT DISTINCT
Acct.AccountNumber
, Acct.ABCat AS Cat
, Acct.fName AS FirstName
, Acct.lName AS LastName
, Acct.Age AS Age
, o.Type, o.OFirstLoginDate
, o.OLastLoginDate
, m.Type
, m.LstDepDate AS LastDepDate
FROM
table1 AS Acct
LEFT JOIN
(
SELECT DISTINCT
Online.Account AS AccountNumber
, Online.TYPE
, Online.OBFLDate AS OFirstLoginDate
, Online.OBLLDate AS OLastLoginDate
FROM OBtable AS Online
WHERE Online.DataDate=20200430
And Online.OBFLDate Is Not Null
)
AS o
ON Acct.AccountNumber = o.AccountNumber
LEFT JOIN
(
SELECT DISTINCT
ParentAccount AS AccountNumber
, TYPE
, LstDepDate AS LastDepDate
FROM MBtable
WHERE ProcessDate = 20200430
AND FDate IS NOT NULL
ORDER BY LDate DESC
)
AS m
ON Acct.AccountNumber = m.AccountNumber
WHERE Acct.Cat IN (9,12,16,17)
 AND Acct.DataDate=20200430
AND Acct.Status = 'Open';


问:
How to fix no module found error in running Django Test
I am trying to run some simple tests for my blog app. I installed social_django beacsue I want users to be  able to sign in with either their Facebook, Twitter or Google Account.

On running my test using python manage.py test I get this error.

```<code>Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_fr  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    django.setup()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 143, in create
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: 'django.test.TestCase' isn't a subclass of AppConfig.
PS C:\Semicolon\Software Engineering\Web Development\Back End\Django Projects\christian_blog\christian_blog> ^C
PS C:\Semicolon\Software Engineering\Web Development\Back End\Django Projects\christian_blog\christian_blog> python manage.py test
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    django.setup()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 90, in create
    module = import_module(entry)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'social_django'
</code>```

Here is my test code. I am using the default tests.py file created in my 'app'.

```<code>from django.test import TestCase
from christian_blog_app.models import Post
from django.utils import timezone
from django.core.urlresolvers import reverse
from christian_blog.settings import social_django, crispy_forms, coverage, social_login

# Create your tests here.

class PostTest(TestCase):

    def create_post(self, title="only a test", body="Testing if the created title matches the expected title"):
        return Post.objects.create(title=title, body=body, created_at=timezone.now())

    def test_post_creation(self):
        w = self.create_post()
        self.assertTrue(isinstance(w, Post))
        self.assertEqual(w.__str__(), w.title)
</code>```

What do you think I am doing wrong? How do I fix this?

答: I had to install social_django and some other apps again. It fixed the problem.</p>

Body:
I am trying to run some simple tests for my blog app. I installed social_django beacsue I want users to be  able to sign in with either their Facebook, Twitter or Google Account.

On running my test using python manage.py test I get this error.

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_fr  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    django.setup()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 143, in create
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: 'django.test.TestCase' isn't a subclass of AppConfig.
PS C:\Semicolon\Software Engineering\Web Development\Back End\Django Projects\christian_blog\christian_blog> ^C
PS C:\Semicolon\Software Engineering\Web Development\Back End\Django Projects\christian_blog\christian_blog> python manage.py test
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    django.setup()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 90, in create
    module = import_module(entry)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'social_django'

Here is my test code. I am using the default tests.py file created in my 'app'.

from django.test import TestCase
from christian_blog_app.models import Post
from django.utils import timezone
from django.core.urlresolvers import reverse
from christian_blog.settings import social_django, crispy_forms, coverage, social_login

# Create your tests here.

class PostTest(TestCase):

    def create_post(self, title="only a test", body="Testing if the created title matches the expected title"):
        return Post.objects.create(title=title, body=body, created_at=timezone.now())

    def test_post_creation(self):
        w = self.create_post()
        self.assertTrue(isinstance(w, Post))
        self.assertEqual(w.__str__(), w.title)

What do you think I am doing wrong? How do I fix this?


问:
How do I iterate through a file containing a list of floating point numbers in Python?
I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold.

numbers.txt -

5.0

15.0

25.0

This is my python code -

```<code>in_file = open("numbers.txt", "r")
number = float(in_file.read())  # error in python
user_input = float(input("Threshold: "))
if number > user_input:
    print(number)
in_file.close()

</code>```

Python is unable to convert the string to a float because the numbers have a new line after each number and python is trying to convert that into a float. I tried to change line 2 in my code to add a strip method but it still comes up with the same error.

答:
You can try this workaround</p>

```<code>inputdata = []
with open('data.txt') as f:
    for row in f:
        try:
            number = float(row)
            inputdata.append(number)
        except:
            pass
</code>```

Body:
I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold.

numbers.txt -

5.0

15.0

25.0

This is my python code -

in_file = open("numbers.txt", "r")
number = float(in_file.read())  # error in python
user_input = float(input("Threshold: "))
if number > user_input:
    print(number)
in_file.close()

Python is unable to convert the string to a float because the numbers have a new line after each number and python is trying to convert that into a float. I tried to change line 2 in my code to add a strip method but it still comes up with the same error.

Body:
You can try this workaround

inputdata = []
with open('data.txt') as f:
    for row in f:
        try:
            number = float(row)
            inputdata.append(number)
        except:
            pass