问:
laravel 6 npm run dev failed
I recently start learning laravel and already did 2 project, but suddenly the NPM RUN DEV failed when i create new laravel 6 project.

I can still run my old project and also already tried rm -rf node_modules && npm cache clean --force && npm install.

here is the error in terms :

```<code> @ dev C:\xampp\htdocs\SimplePOS
 npm run development

 @ development C:\xampp\htdocs\SimplePOS
 cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
C:\Users\Eric\AppData\Roaming\npm\node_modules\cross-env\src\index.js:23
    )
    ^
SyntaxError: Unexpected token )
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Eric\AppData\Roaming\npm\node_modules\cross-env\src\bin\cross-env.js:3:18)

npm ERR! Windows_NT 10.0.17134
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "development"
npm ERR! node v6.11.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script 'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\xampp\htdocs\SimplePOS\npm-debug.log

npm ERR! Windows_NT 10.0.17134
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
npm ERR! node v6.11.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script 'npm run development'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run development
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\xampp\htdocs\SimplePOS\npm-debug.log
</code>```

can someone help this newbie fix this problem?

答:
I used package.json of another system.

```<code>{
"private": true,
"scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "npm run development -- --watch",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
    "axios": "^0.19",
    "bootstrap": "^4.0.0",
    "cross-env": "^5.1",
    "jquery": "^3.2",
    "laravel-mix": "^4.0.7",
    "lodash": "^4.17.13",
    "popper.js": "^1.12",
    "resolve-url-loader": "^2.3.1",
    "sass": "^1.20.1",
    "sass-loader": "7.*",
    "vue": "^2.5.17",
    "vue-template-compiler": "^2.6.10"
}
</code>```

}

Title: laravel 6 npm run dev failed

Body:
I recently start learning laravel and already did 2 project, but suddenly the NPM RUN DEV failed when i create new laravel 6 project.

I can still run my old project and also already tried rm -rf node_modules && npm cache clean --force && npm install.

here is the error in terms :

 @ dev C:\xampp\htdocs\SimplePOS
 npm run development

 @ development C:\xampp\htdocs\SimplePOS
 cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
C:\Users\Eric\AppData\Roaming\npm\node_modules\cross-env\src\index.js:23
    )
    ^
SyntaxError: Unexpected token )
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Eric\AppData\Roaming\npm\node_modules\cross-env\src\bin\cross-env.js:3:18)

npm ERR! Windows_NT 10.0.17134
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "development"
npm ERR! node v6.11.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script 'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\xampp\htdocs\SimplePOS\npm-debug.log

npm ERR! Windows_NT 10.0.17134
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
npm ERR! node v6.11.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script 'npm run development'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run development
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\xampp\htdocs\SimplePOS\npm-debug.log

can someone help this newbie fix this problem?

Body:
I used package.json of another system.

{
"private": true,
"scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "npm run development -- --watch",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
    "axios": "^0.19",
    "bootstrap": "^4.0.0",
    "cross-env": "^5.1",
    "jquery": "^3.2",
    "laravel-mix": "^4.0.7",
    "lodash": "^4.17.13",
    "popper.js": "^1.12",
    "resolve-url-loader": "^2.3.1",
    "sass": "^1.20.1",
    "sass-loader": "7.*",
    "vue": "^2.5.17",
    "vue-template-compiler": "^2.6.10"
}

}


来源: stackexchange

问:
Align ImageView to top right corner
I have a RelativeLayout with images next to each other. The number of images will be variable.

```<code>    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>
</code>```

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

答:
```<code><RelativeLayout android:id="@id/multipleImages"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/border"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>

    <ImageView
        android:id="@+id/multi_image_last"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="2dp"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:scaleType="fitXY"
        app:srcCompat="@drawable/imag4"/>

</RelativeLayout>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Align ImageView to top right corner

Body:
I have a RelativeLayout with images next to each other. The number of images will be variable.

    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.


问:
Google Drive api react-native
I'm new in react-native and I need upload a image to Google drive, I try to use a google-drive-api-wrapper but I have a error 403 and I don't know what is the problem, someone could explain me How could I do this?, I show my code but I remove the webclientid

I try to guide me with this example
https://gist.github.com/luyx2412/2cddb9033d65403d595e069b95dad005

```<code>GoogleDrive= async() =>{
    await this.initialGoogle();
    GDrive.init();

    // GDrive.permissions.create(
    //     fileid, {
    //         role: "reader",
    //         type: "anyone"
    //     });

    const options = {
        title: 'Select Avatar',
        customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
        storageOptions: {
          skipBackup: true,
          path: 'images',
        },
      };

    ImagePicker.launchImageLibrary(options, (response) => {
        console.log(response);
        if (response.uri) {
            // response.data is the actual image data.
            // response.type can give you the mime for pictures only
            // response.fileName for the name of the file.
            console.log(response.data);
            GDrive.files.createFileMultipart(
                response.data,
                response.type, {
                    parents: ["root"],
                    name: response.fileName,
                }, false);

        }
    });
}

initialGoogle = async () => {
    await GoogleSignin.configure({
        scopes: ['https://www.googleapis.com/auth/drive'],
        webClientId: '',
        shouldFetchBasicProfile: true,
        offlineAccess: false
    });

    // await GoogleSignin.signInSilently();
    //set api token
    GoogleSignin.getTokens();
}
</code>```

error [Error: {"error":{"errors":[{"domain":"global","reason":"insufficientPermissions","message":"Insufficient Permission: Request had insufficient authentication scopes."}],"code":403,"message":"Insufficient Permission: Request had insufficient authentication scopes."}}]

答:
You just need to get the image path, and then use the react-native-fs to read that image. After this pass the base64 image to GDrive wrapper.</p>

```<code>RNFS.readFile(filePath, 'base64').then(res => {
        GDrive.files
          .createFileMultipart(
            res,
            "'image/jpg'",
            {
              parents: ['root'], //or any path
              name: newImageName,
            },
            true,
          )
          .then(response => {
            Alert.alert(
              'Image saved to Google Drive.',
              'Delete image from device?',[
                {text: 'Ok', onPress: () => this.unlinkImage(newFilepath)},
                {
                  text: 'Cancel',
                  onPress: () => console.log('Cancel Pressed'),
                  style: 'cancel',
                }
              ],
              {cancelable: false},
            );
          }).catch = err => {
          console.log('error', err);
        };
      });
</code>```

Title: Google Drive api react-native

Body:
I'm new in react-native and I need upload a image to Google drive, I try to use a google-drive-api-wrapper but I have a error 403 and I don't know what is the problem, someone could explain me How could I do this?, I show my code but I remove the webclientid

I try to guide me with this example
https://gist.github.com/luyx2412/2cddb9033d65403d595e069b95dad005

GoogleDrive= async() =>{
    await this.initialGoogle();
    GDrive.init();

    // GDrive.permissions.create(
    //     fileid, {
    //         role: "reader",
    //         type: "anyone"
    //     });

    const options = {
        title: 'Select Avatar',
        customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
        storageOptions: {
          skipBackup: true,
          path: 'images',
        },
      };

    ImagePicker.launchImageLibrary(options, (response) => {
        console.log(response);
        if (response.uri) {
            // response.data is the actual image data.
            // response.type can give you the mime for pictures only
            // response.fileName for the name of the file.
            console.log(response.data);
            GDrive.files.createFileMultipart(
                response.data,
                response.type, {
                    parents: ["root"],
                    name: response.fileName,
                }, false);

        }
    });
}

initialGoogle = async () => {
    await GoogleSignin.configure({
        scopes: ['https://www.googleapis.com/auth/drive'],
        webClientId: '',
        shouldFetchBasicProfile: true,
        offlineAccess: false
    });

    // await GoogleSignin.signInSilently();
    //set api token
    GoogleSignin.getTokens();
}

error [Error: {"error":{"errors":[{"domain":"global","reason":"insufficientPermissions","message":"Insufficient Permission: Request had insufficient authentication scopes."}],"code":403,"message":"Insufficient Permission: Request had insufficient authentication scopes."}}]

Body:
You just need to get the image path, and then use the react-native-fs to read that image. After this pass the base64 image to GDrive wrapper.

RNFS.readFile(filePath, 'base64').then(res => {
        GDrive.files
          .createFileMultipart(
            res,
            "'image/jpg'",
            {
              parents: ['root'], //or any path
              name: newImageName,
            },
            true,
          )
          .then(response => {
            Alert.alert(
              'Image saved to Google Drive.',
              'Delete image from device?',[
                {text: 'Ok', onPress: () => this.unlinkImage(newFilepath)},
                {
                  text: 'Cancel',
                  onPress: () => console.log('Cancel Pressed'),
                  style: 'cancel',
                }
              ],
              {cancelable: false},
            );
          }).catch = err => {
          console.log('error', err);
        };
      });


答: Try adding marginTop to your RelativeLayout, so when you add negative margin to the last image, it won't dissappear</p>

Title: Align ImageView to top right corner


问:
Angular Material Paginator Using Data from Front-End
I am getting all the data together all at once from the back-end and using angular material paginator. All the data is shown in the same page. Can someone tell me how to divide the data based on page size using the angular material paginator and show the data in different pages.

The data which I am displaying in the UI is not in a table format with columns but a list of data in card format. It is an Ionic 4 Angular 8 application with ionic elements in HTML and I have placed the mat-paginator inside the ion-header tag.

答:
All you need to do is add the paginator below the table and specify the page size:

<mat-paginator [pageSize]="10"></mat-paginator>
```


问:
Unable to add Roboto font to Rails 6 using TailwindCSS
Currently I'm trying to use Roboto in my application to have a font similar to five thirty eight. However, when I try to edit the configuration for Tailwind and restart the server I don't see the font.

Here is the the link I'm using to load the font that I got from  google fonts:

```<code>  <head>
    <title>ArtsyDecor</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= stylesheet_pack_tag 'application', media: 'all',  'data-turbolinks-track': 'reload' %>
    <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
  </head>
</code>```

I then added the Roboto font to the tailwind.config.js on my rails app.

```<code>module.exports = {
  theme: {
    fontFamily: {
      sans: '"Roboto"'
      display: ['"Roboto"', '"sans-serif"'],
      body: ['"Roboto"', '"sans-serif"'],
    },
    extend: {}
  },
  variants: {},
  plugins: []
}
</code>```

But when I restart the server I don't see Roboto being the main font. It seems the tailwind configuration is being overwritten somewhere.

What seems to be wrong?

答: I think there is a typo. the font is defined in single and double quotes. use only single or double quotes.</p>

Body:
Currently I'm trying to use Roboto in my application to have a font similar to five thirty eight. However, when I try to edit the configuration for Tailwind and restart the server I don't see the font.

Here is the the link I'm using to load the font that I got from  google fonts:

    <title>ArtsyDecor</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= stylesheet_pack_tag 'application', media: 'all',  'data-turbolinks-track': 'reload' %>
    <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">

I then added the Roboto font to the tailwind.config.js on my rails app.

module.exports = {
  theme: {
    fontFamily: {
      sans: '"Roboto"'
      display: ['"Roboto"', '"sans-serif"'],
      body: ['"Roboto"', '"sans-serif"'],
    },
    extend: {}
  },
  variants: {},
  plugins: []
}

But when I restart the server I don't see Roboto being the main font. It seems the tailwind configuration is being overwritten somewhere.

What seems to be wrong?


问:
Making indexes to my sql table for a query with "where" and "order by" clauses
I have a table in a mysql db. My query looks like

```<code>SELECT device_id,date,timestamp,power,floor
from tableData
where date=%s
and floor=%s
order by timestamp desc
limit 1
</code>```

I have created index on my table for quicker results . My indexes:

```<code>+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table      | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| minionData |          1 | idx1     |            1 | date        | A         |        9447 |     NULL | NULL   | YES  | BTREE      |         |               |
| minionData |          1 | idx1     |            2 | floor       | A         |       12072 |     NULL | NULL   | YES  | BTREE      |         |               |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
</code>```

So my question is for the particular query I am using, indexes on data and floor columns are good enough or should i index on timestamp column also, for increasing the query performance?

答:
Adding an index to each single column does not allow the database to properly optimize the query (only one index will be used at a time).

To start with: to optimize the where clause, you would need a compound index on both columns, like:

```<code>tableData(date, floor)
</code>```

But to make this even more efficient, you could also add the column that is used for sorting in the ìndex, so:

```<code>tableData(date, floor, timestamp)
</code>```

If you are running MySQL 8.0, you can make the index descending on column timestamp:

```<code>tableData(date, floor, timestamp desc)
</code>```

Finally: one option would be to add the other columns that you select in the index, to make it a covering index; this could allow the entire query to be executed using the index only (ie without looking at the table data):

```<code>tableData(date, floor, timestamp desc, device_id, power)
</code>```

For many more information on how to optimize the use of indexes in MySQL, I would recommend reading the great MySQL index cookbook written by Rick James (which is also an active SO user).

Body:
I have a table in a mysql db. My query looks like

SELECT device_id,date,timestamp,power,floor
from tableData
where date=%s
and floor=%s
order by timestamp desc
limit 1

I have created index on my table for quicker results . My indexes:

+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table      | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| minionData |          1 | idx1     |            1 | date        | A         |        9447 |     NULL | NULL   | YES  | BTREE      |         |               |
| minionData |          1 | idx1     |            2 | floor       | A         |       12072 |     NULL | NULL   | YES  | BTREE      |         |               |
+------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

So my question is for the particular query I am using, indexes on data and floor columns are good enough or should i index on timestamp column also, for increasing the query performance?

Body:
Adding an index to each single column does not allow the database to properly optimize the query (only one index will be used at a time).

To start with: to optimize the where clause, you would need a compound index on both columns, like:

tableData(date, floor)

But to make this even more efficient, you could also add the column that is used for sorting in the ìndex, so:

tableData(date, floor, timestamp)

If you are running MySQL 8.0, you can make the index descending on column timestamp:

tableData(date, floor, timestamp desc)

Finally: one option would be to add the other columns that you select in the index, to make it a covering index; this could allow the entire query to be executed using the index only (ie without looking at the table data):

tableData(date, floor, timestamp desc, device_id, power)

For many more information on how to optimize the use of indexes in MySQL, I would recommend reading the great MySQL index cookbook written by Rick James (which is also an active SO user).


问:
Kivy - Saving object's values changed in Popup, so that after closing it, when I open the popup again it opens with new values
I want to change some button labels of a class in a popup and retain the new label after reopening the popup. If you run my app, you can see that after pressing "Press me" button, a popup appears with a button with a label "Default", after pressing on it, it changes the label to "New". I want to be able to close the popup, press the "Press me" button and see the button in a popup with a label "New".

My .py file

```<code>from kivy.uix.floatlayout import FloatLayout
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.app import App
from kivy.uix.widget import Widget

import time

Window.clearcolor = (1, 1, 1, 1)
Window.size = (800, 480)

class MyGrid(Widget):
    def btn(self):
        show_popup(T, "Window")

class T(FloatLayout):
    pass

def show_popup(tab, name):
    show = tab()
    popupWindow = Popup(title = name, content = show, size_hint = (None,None), size = (800,384), auto_dismiss = True)
    popupWindow.open()
    return popupWindow

class TimeApp(App):
    def build(self):
        return MyGrid()

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

my .kv file

```<code><MyGrid>
    Button:
        text: "Press me"
        on_press: root.btn()

<T>:
    Button:
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        text: "Default"
        on_press: self.text = "New"
</code>```

答:
One way that you can do it, is by keeping a reference to the popup.

The py side:

Window.clearcolor = (1, 1, 1, 1)
Window.size = (800, 480)

class MyGrid(Widget):

    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.popupWindow = Popup(content=T(), size_hint=(None, None),
                                 size=(800, 384), auto_dismiss=True)

    def btn(self):
        self.show_popup("Window")

    def show_popup(self, name):
        self.popupWindow.title = name
        self.popupWindow.open()

class T(FloatLayout):
    pass

class TimeApp(App):
    def build(self):
        return MyGrid()

if __name__ == "__main__":
    TimeApp().run()
```

Body:
I want to change some button labels of a class in a popup and retain the new label after reopening the popup. If you run my app, you can see that after pressing "Press me" button, a popup appears with a button with a label "Default", after pressing on it, it changes the label to "New". I want to be able to close the popup, press the "Press me" button and see the button in a popup with a label "New".

My .py file

from kivy.uix.floatlayout import FloatLayout
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.app import App
from kivy.uix.widget import Widget

import time

Window.clearcolor = (1, 1, 1, 1)
Window.size = (800, 480)

class MyGrid(Widget):
    def btn(self):
        show_popup(T, "Window")

class T(FloatLayout):
    pass

def show_popup(tab, name):
    show = tab()
    popupWindow = Popup(title = name, content = show, size_hint = (None,None), size = (800,384), auto_dismiss = True)
    popupWindow.open()
    return popupWindow

class TimeApp(App):
    def build(self):
        return MyGrid()

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

my .kv file

<MyGrid>
    Button:
        text: "Press me"
        on_press: root.btn()

<T>:
    Button:
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        text: "Default"
        on_press: self.text = "New"


问:
Background Images Not Loading In Elementor
My website is not loading the background images on live version - it just shows the text and a grey screen.

I built the site using Elementor.

Here are the pages

(all service pages).

I compressed all images to about 100K so they shouldn't be too big to load. The one one the homepage is 99K and it loads.

Thanks

答:
Please try to replace your URLs. Log in to your Wordpress account on whichever server it is hosted. </p>

<p>On your Dashboard screen, navigate to Elementor -> Tools. In General tab, regenerate CSS files.  </p>

Body:
Please try to replace your URLs. Log in to your Wordpress account on whichever server it is hosted.

On your Dashboard screen, navigate to Elementor -> Tools. In General tab, regenerate CSS files.


问:
Router.use() requires middleware function but got a undefined
I am trying to set up my node server / REST api.

For this i have a few different files:

division_model.js:

```<code>    module.exports = function(express, sequelize)
{
    var router = express.Router();
    router.route('/division');
    var DataTypes = require("sequelize");

    var Division = sequelize.define('division', {
            id: DataTypes.INTEGER,
            organization_id: DataTypes.INTEGER,
            location_id: DataTypes.INTEGER,
            name: DataTypes.STRING,
            parent_id: DataTypes.INTEGER

        }, {    freezeTableName: true,
            instanceMethods: {
                retrieveAll: function (onSuccess, onError) {
                    Division.findAll({}, {raw: true})
                        .ok(onSuccess).error(onError);
                },
                retrieveById: function (user_id, onSuccess, onError) {
                    Division.find({where: {id: user_id}}, {raw: true})
                        .success(onSuccess).error(onError);
                },
                add: function (onSuccess, onError) {
                    var username = this.username;
                    var password = this.password;

                    var shasum = crypto.createHash('sha1');
                    shasum.update(password);
                    password = shasum.digest('hex');

                    Division.build({username: username, password: password})
                        .save().ok(onSuccess).error(onError);
                },
                updateById: function (user_id, onSuccess, onError) {
                    var id = user_id;
                    var username = this.username;
                    var password = this.password;

                    var shasum = crypto.createHash('sha1');
                    shasum.update(password);
                    password = shasum.digest('hex');

                    Division.update({username: username, password: password}, {where: {id: id}})
                        .success(onSuccess).error(onError);
                },
                removeById: function (user_id, onSuccess, onError) {
                    Division.destroy({where: {id: user_id}}).success(onSuccess).error(onError);
                }
            }
        }
    );

// on routes that end in /users/:user_id
// ----------------------------------------------------
    router.route('/division/:division_id')

// update a user (accessed at PUT http://localhost:8080/api/users/:user_id)
        .put(function (req, res) {
            var user = User.build();

            Division.username = req.body.username;
            Division.password = req.body.password;

            Division.updateById(req.params.division_id, function (success) {
                console.log(success);
                if (success) {
                    res.json({message: 'User updated!'});
                } else {
                    res.send(401, "User not found");
                }
            }, function (error) {
                res.send("User not found");
            });
        })

// get a user by id(accessed at GET http://localhost:8080/api/users/:user_id)
        .get(function (req, res) {
            var Division = Division.build();

            Division.retrieveById(req.params.division_id, function (users) {
                if (users) {
                    res.json(users);
                } else {
                    res.status(401).send("User not found");
                }
            }, function (error) {
                res.send("User not found");
            });
        })

// delete a user by id (accessed at DELETE http://localhost:8080/api/users/:user_id)
        .delete(function (req, res) {
            var division = Division.build();

            division.removeById(req.params.division_id, function (users) {
                if (users) {
                    res.json({message: 'User removed!'});
                } else {
                    res.status(401).send("User not found");
                }
            }, function (error) {
                res.send("User not found");
            });
        });
};
</code>```

And my server.js

```<code>    // BASE SETUP
// =============================================================================
var express = require('express'),
    bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');
// =============================================================================

// IMPORT MODELS
// =============================================================================
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
var env = app.get('env') == 'development' ? 'dev' : app.get('env');
var port = process.env.PORT || 8080;

var Sequelize = require('sequelize');

// db config
var env = "dev";
var config = require('./database.json')[env];
var password = config.password ? config.password : null;

// initialize database connection
var sequelize = new Sequelize(
    config.database,
    config.user,
    config.password,
    {
        logging: console.log,
        define: {
            timestamps: false
        }
    }
);
//================================================================================

var division_model = require('./Divisions/division_model')(express,sequelize, router);

app.use('/division', division_model);

// REGISTER ROUTES
// =============================================================================
app.use('/api', app.router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
</code>```

However with this i get the following error message when starting the server:

```<code>          throw new TypeError('Router.use() requires middleware function but got a
            ^
TypeError: Router.use() requires middleware function but got a undefined
    at Function.<anonymous> (/var/www/example/backend/node_modules/express/lib/router/index.js:446:13)
    at Array.forEach (native)
    at Function.use (/var/www/example/backend/node_modules/express/lib/router/index.js:444:13)
    at EventEmitter.<anonymous> (/var/www/example/backend/node_modules/express/lib/application.js:187:21)
    at Array.forEach (native)
    at EventEmitter.use (/var/www/example/backend/node_modules/express/lib/application.js:184:7)
    at Object.<anonymous> (/var/www/example/backend/server.js:42:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
</code>```

Can anyone tell me why this is happening?

答:
because you are exporting module with a function inside so you need to return your router at the end of your function at division_model.js

```<code>return router;
</code>```

this should work

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set up my node server / REST api.

For this i have a few different files:

division_model.js:

    module.exports = function(express, sequelize)
{
    var router = express.Router();
    router.route('/division');
    var DataTypes = require("sequelize");

    var Division = sequelize.define('division', {
            id: DataTypes.INTEGER,
            organization_id: DataTypes.INTEGER,
            location_id: DataTypes.INTEGER,
            name: DataTypes.STRING,
            parent_id: DataTypes.INTEGER

        }, {    freezeTableName: true,
            instanceMethods: {
                retrieveAll: function (onSuccess, onError) {
                    Division.findAll({}, {raw: true})
                        .ok(onSuccess).error(onError);
                },
                retrieveById: function (user_id, onSuccess, onError) {
                    Division.find({where: {id: user_id}}, {raw: true})
                        .success(onSuccess).error(onError);
                },
                add: function (onSuccess, onError) {
                    var username = this.username;
                    var password = this.password;

                    var shasum = crypto.createHash('sha1');
                    shasum.update(password);
                    password = shasum.digest('hex');

                    Division.build({username: username, password: password})
                        .save().ok(onSuccess).error(onError);
                },
                updateById: function (user_id, onSuccess, onError) {
                    var id = user_id;
                    var username = this.username;
                    var password = this.password;

                    var shasum = crypto.createHash('sha1');
                    shasum.update(password);
                    password = shasum.digest('hex');

                    Division.update({username: username, password: password}, {where: {id: id}})
                        .success(onSuccess).error(onError);
                },
                removeById: function (user_id, onSuccess, onError) {
                    Division.destroy({where: {id: user_id}}).success(onSuccess).error(onError);
                }
            }
        }
    );

// on routes that end in /users/:user_id
// ----------------------------------------------------
    router.route('/division/:division_id')

// update a user (accessed at PUT http://localhost:8080/api/users/:user_id)
        .put(function (req, res) {
            var user = User.build();

            Division.username = req.body.username;
            Division.password = req.body.password;

            Division.updateById(req.params.division_id, function (success) {
                console.log(success);
                if (success) {
                    res.json({message: 'User updated!'});
                } else {
                    res.send(401, "User not found");
                }
            }, function (error) {
                res.send("User not found");
            });
        })

// get a user by id(accessed at GET http://localhost:8080/api/users/:user_id)
        .get(function (req, res) {
            var Division = Division.build();

            Division.retrieveById(req.params.division_id, function (users) {
                if (users) {
                    res.json(users);
                } else {
                    res.status(401).send("User not found");
                }
            }, function (error) {
                res.send("User not found");
            });
        })

// delete a user by id (accessed at DELETE http://localhost:8080/api/users/:user_id)
        .delete(function (req, res) {
            var division = Division.build();

            division.removeById(req.params.division_id, function (users) {
                if (users) {
                    res.json({message: 'User removed!'});
                } else {
                    res.status(401).send("User not found");
                }
            }, function (error) {
                res.send("User not found");
            });
        });
};

And my server.js

    // BASE SETUP
// =============================================================================
var express = require('express'),
    bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');
// =============================================================================

// IMPORT MODELS
// =============================================================================
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
var env = app.get('env') == 'development' ? 'dev' : app.get('env');
var port = process.env.PORT || 8080;

var Sequelize = require('sequelize');

// db config
var env = "dev";
var config = require('./database.json')[env];
var password = config.password ? config.password : null;

// initialize database connection
var sequelize = new Sequelize(
    config.database,
    config.user,
    config.password,
    {
        logging: console.log,
        define: {
            timestamps: false
        }
    }
);
//================================================================================

var division_model = require('./Divisions/division_model')(express,sequelize, router);

app.use('/division', division_model);

// REGISTER ROUTES
// =============================================================================
app.use('/api', app.router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

However with this i get the following error message when starting the server:

          throw new TypeError('Router.use() requires middleware function but got a
            ^
TypeError: Router.use() requires middleware function but got a undefined
    at Function.<anonymous> (/var/www/example/backend/node_modules/express/lib/router/index.js:446:13)
    at Array.forEach (native)
    at Function.use (/var/www/example/backend/node_modules/express/lib/router/index.js:444:13)
    at EventEmitter.<anonymous> (/var/www/example/backend/node_modules/express/lib/application.js:187:21)
    at Array.forEach (native)
    at EventEmitter.use (/var/www/example/backend/node_modules/express/lib/application.js:184:7)
    at Object.<anonymous> (/var/www/example/backend/server.js:42:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)

Can anyone tell me why this is happening?

Body:
because you are exporting module with a function inside so you need to return your router at the end of your function at division_model.js

return router;

this should work


问:
ASP.NET MVC3 URL and hiding Id's
I have a heap of entities that are keyed by ID. In one screen I load a "Subject" based on the ID like so: "/Results/Subject/53" On that same screen I have a combo box that maintains a list of all subjects. The user can change the selection in this combo to another subject and I load the results for that subject using ajax. When I do this the URL in the browser is stale as I might be now be looking at /Results/Subject/45 If a user reloads I reload the original document and not the new one.

I would either like to update the URL (which sounds hacky as) or I would like to base my navigation on something else besides the Id as part of the URL. How can I do this? How can I load controllers for specific items without specifying the Id as part of the URL.

答:
You can also pass the id via the HTTP GET parameter: /Results/Subject?id=45 or HTTP POST parameter.

However, I doubt that this will answer your question.

A colleague of mine has encountered the similar problem, and he solved it by altering the browser URL string (by attaching a specific #anchor to it).

Title: ASP.NET MVC3 URL and hiding Id's


问:
Variable becomes undefined when access in a class method
I defined a class variable in a constructor which holds a reference to an imported class instance.

However, when I try to access the variable in my class methods I keep getting undefined for that variable.

Exported class

```<code>import models from '../../database/models'

const {User} = models;

class UserRepository {
  constructor(){
    this.model = User;
  }

 async create({firstname, lastname, email, isadmin, password}){
  return await this.model.create({firstname, lastname, email, isadmin, password})
  }
}

export default new UserRepository();
</code>```

Class using the exported class

```<code>import repository from './repository';
import { sendSuccessMessage } from '../../utils'

class UserController {
  constructor() {
    this.model = repository;
  }

  async createUser({ body }, res, next) {
    try {
      const result = await this.model.create(body);
      sendSuccessMessage(res, 200, result);
    } catch( e ){
      next(e)
    }
  }
}

export default new UserController();
</code>```

However, using the variable repository directory in createUser as specified below:

const result = await repository.create(body);

works as expected.

Current call chain

```<code>// routes.js file
import controller from './controller'

export default [
  {
    path: '/signup',
    method: 'post',
    handlers: [controller.createUser] // createUser from class UserController
  }
]

// utitlity.js file
export const routesLoader = (routes, router) => {
 for (const route of routes) {
   const { path, handlers, method } = route;
   (router)[method](path, handlers);
 }
};

// app.js file
import express from 'express';
import routes from './routes.js';
import { routesLoader } from './utils';

const router = express.Router();

routesLoader(routes, router);

// server.js file
import http from 'http';
import app from './app';

const { PORT = 3000 } = process.env;

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`server listening on localhost: ${PORT}`);
});
</code>```

Error

```<code>TypeError: Cannot read property 'create' of undefined
at _callee$ (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user/controller.js:16:39)
at tryCatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:45:40)
at Generator.invoke [as _invoke] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:271:22)
at Generator.prototype.<computed> [as next] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:97:21)
at asyncGeneratorStep (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:21:12
at createUser (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user\controller.js:70:28)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:275:10)
at cors (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:188:7)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:224:17
at originCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:214:15)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:199:9)
</code>```

Technologies used

```<code>@babel/node: "^7.8.4"
terminal: git bash
Os: windows
</code>```

答:
How is UserController.createUser called? Sounds like its this is not set up correctly. Let's say we initialized the class like this:

```<code>const userController = new UserController();
</code>```

Then, one source for missing this can be if you only pass an exact reference to the method

```<code>setImmediate(userController.createUser);
</code>```

instead of a way that retains this:

```<code>setImmediate(() => {
   userController.createUser()
});
</code>```

In other words, you want to invocate the method using dot notation and involve the class instance.

Body:
I defined a class variable in a constructor which holds a reference to an imported class instance.

However, when I try to access the variable in my class methods I keep getting undefined for that variable.

Exported class

import models from '../../database/models'

const {User} = models;

class UserRepository {
  constructor(){
    this.model = User;
  }

 async create({firstname, lastname, email, isadmin, password}){
  return await this.model.create({firstname, lastname, email, isadmin, password})
  }
}

export default new UserRepository();

Class using the exported class

import repository from './repository';
import { sendSuccessMessage } from '../../utils'

class UserController {
  constructor() {
    this.model = repository;
  }

  async createUser({ body }, res, next) {
    try {
      const result = await this.model.create(body);
      sendSuccessMessage(res, 200, result);
    } catch( e ){
      next(e)
    }
  }
}

export default new UserController();

However, using the variable repository directory in createUser as specified below:

const result = await repository.create(body);

works as expected.

Current call chain

// routes.js file
import controller from './controller'

export default [
  {
    path: '/signup',
    method: 'post',
    handlers: [controller.createUser] // createUser from class UserController
  }
]

// utitlity.js file
export const routesLoader = (routes, router) => {
 for (const route of routes) {
   const { path, handlers, method } = route;
   (router)[method](path, handlers);
 }
};

// app.js file
import express from 'express';
import routes from './routes.js';
import { routesLoader } from './utils';

const router = express.Router();

routesLoader(routes, router);

// server.js file
import http from 'http';
import app from './app';

const { PORT = 3000 } = process.env;

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`server listening on localhost: ${PORT}`);
});

Error

TypeError: Cannot read property 'create' of undefined
at _callee$ (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user/controller.js:16:39)
at tryCatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:45:40)
at Generator.invoke [as _invoke] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:271:22)
at Generator.prototype.<computed> [as next] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:97:21)
at asyncGeneratorStep (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:21:12
at createUser (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user\controller.js:70:28)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:275:10)
at cors (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:188:7)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:224:17
at originCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:214:15)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:199:9)

Technologies used

@babel/node: "^7.8.4"
terminal: git bash
Os: windows

Body:
How is UserController.createUser called? Sounds like its this is not set up correctly. Let's say we initialized the class like this:

const userController = new UserController();

Then, one source for missing this can be if you only pass an exact reference to the method

setImmediate(userController.createUser);

instead of a way that retains this:

setImmediate(() => {
   userController.createUser()
});

In other words, you want to invocate the method using dot notation and involve the class instance.


问:
Why does Android Studio never show layout decorations when I open it?
As you can see in the image below, every time I open a project in Android Studio, the layout decorations option is deselected. How can I have it selected for default?

答: look on the top left of constraintLayout that you currently open, click on the eye icon and then click Show Layout Decorations. then you will be able to see it. but i don't know how to access it.


问:
Request timeout while uploading movie to app service
I am having trouble uploading a big movie on to the Azure app service which I created. I get request timeout after 4-5 mins while uploading the movie (greater than 150MB). For the frontend, I am using VueJS and send multiple files by doing promisify all settled function. Don't have any issues while using it locally. For backend, I am using Nodejs(fastify) with a multer package and I am using an in-memory storage option. Once I receive the file basically I upload it to Azure blob storage.

Do I have to send movie data in chunks from the frontend to backend? how to achieve it when I have multiple files.

Can we use socket io?

I tried using socket io. however, my browser freezes if I send a big file and I am totally new to sockets.

I am not sure how can I fix this issue. It would be great if someone can guide me and show me an example.

Looking forward to hearing from you guys

thanks,
meet

答:
Problems for uploading files to server

Check the timeout in your axios request (front end) - because you have to wait until the all files uploaded to server (https://github.com/axios/axios#creating-an-instance).

Check the domain hosting configuration (if you are hosting your backend service in nginx - check the upload limit (https://www.tecmint.com/limit-file-upload-size-in-nginx/))


问:
Your project does not reference ".NETFramework,Version=v4.6.2" framework. Add a reference to ".NETFramework,Version=v4.6.2" in the "TargetFrameworks"
I can't run my unit tests.

I have the next error:

Your project does not reference ".NETFramework,Version=v4.6.2"
  framework. Add a reference to ".NETFramework,Version=v4.6.2" in the
  "TargetFrameworks" property of your project file and then re-run NuGet
  restore.

In app.config:

```<code><startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>
</code>```

In Project > Properties > Application > TargetFramework (.NET Framework 4.6.2)

How can I fix it?

答:
That happened to me when opening a VS2015 project in VS2017. Deleting the project.assets.json from the obj folder did the trick.

Anyway, the Framework from the message was missing in the file, I did not add it there though, went with deleting it.

Body:
I can't run my unit tests.

I have the next error:

Your project does not reference ".NETFramework,Version=v4.6.2"
  framework. Add a reference to ".NETFramework,Version=v4.6.2" in the
  "TargetFrameworks" property of your project file and then re-run NuGet
  restore.

In app.config:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>

In Project > Properties > Application > TargetFramework (.NET Framework 4.6.2)

How can I fix it?


问:
When making a list, how can I make the multi-line sentence be even with the start of the other sentences?
As you can see at the bullet points 3 and 5, the sentence goes onto the next line and doesn't match up

my code:

ul {
  list-style: none;
}

ul li:before {
  content: '✓';
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu gadījumiem</li>
  <li>Apdrošināšana zādzību gadījumā</li>
</ul></code>```

答:
The below CSS will match the multiline sentence.

ul {
  list-style: none;
}

ul>li {
  position: relative;
  padding-left: 20px;
}

ul>li:before {
  content: '✓';
  position: absolute;
  left: 0;
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu gadījumie Apdrošināšana avāriju un tehnisku bojājumu gadījumie
  </li>
  <li>Apdrošināšana zādzību gadījumā Apdrošināšana zādzību gadījumā Apdrošināšana zādzību gadījumā</li>
</ul></code>```

Body:
As you can see at the bullet points 3 and 5, the sentence goes onto the next line and doesn't match up

my code:

ul {
  list-style: none;
}

ul li:before {
  content: '✓';
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}

Tehniskā palīdzība 24/7

Neierobežots norbraukums

Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā

Civiltiesiskā atbildība

Apdrošināšana avāriju un tehnisku bojājumu gadījumiem

Apdrošināšana zādzību gadījumā

Body:
The below CSS will match the multiline sentence.

ul {
  list-style: none;
}

ul>li {
  position: relative;
  padding-left: 20px;
}

ul>li:before {
  content: '✓';
  position: absolute;
  left: 0;
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}

<ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu gadījumie Apdrošināšana avāriju un tehnisku bojājumu gadījumie
  </li>
  <li>Apdrošināšana zādzību gadījumā Apdrošināšana zādzību gadījumā Apdrošināšana zādzību gadījumā</li>
</ul>


问:
Creating log4j Async logger programmatically
I am using Log4J 2.10.

I am trying to create async logger\appender programmatically. I need to have two things:

I should be able to specify file path for log file at run time.

I need to specify pattern at run time.

I could come up with code below. But I cannot add RollingFileAppender to AsyncAppender. There are examples on the net using AsyncAppender.wrap. But that API doesn't seem to be available with Log4J 2.10.

Do you know how I can achieve this?

```<code>void createLog4JLogger(final String logFilePath) {

    LoggerContext context = (LoggerContext) LogManager.getContext();
    final Configuration config = context.getConfiguration();

    final PatternLayout patternLayout = PatternLayout.newBuilder().withPattern(CONVERSION_PATTERN).withCharset(Charset.defaultCharset()).build();

    final RollingFileAppender fileAppender =
            RollingFileAppender.newBuilder().withName(APPENDER_NAME).withLayout(patternLayout).withFileName(logFilePath).build();

    AppenderRef ref = AppenderRef.createAppenderRef(APPENDER_NAME, null, null);
    AppenderRef[] refs = new AppenderRef[] {ref};

    final AsyncAppender asyncAppender = AsyncAppender.newBuilder().setAppenderRefs(refs).setName(APPENDER_NAME).setConfiguration(config).build();

    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, LOGGER_NAME, LOGGER_NAME, refs, null, null, null);
    loggerConfig.addAppender(asyncAppender, null, null);

    config.addAppender(asyncAppender);
    config.addLogger(LOGGER_NAME, loggerConfig);

    context.updateLoggers(config);

    final Logger logger = LogManager.getContext().getLogger(LOGGER_NAME);

    logger.info("HELLO_WORLD");

}
</code>```

答:
You can use below code to crease async logger in log4j 2.</p>

```<code>final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.newBuilder().withConfiguration(ctx.getConfiguration()).withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - test %msg%n").build();
Appender appender = FileAppender.newBuilder().withFileName("logs/test.log").setLayout(layout)
                    .setConfiguration(config).setName("TestApp").build();
AppenderRef ref = AppenderRef.createAppenderRef("TestApp",Level.INFO, null);

config.addAppender(appender);
appender.start();
AppenderRef[] refs = new AppenderRef[] {ref};
LoggerConfig loggerConfig= AsyncLoggerConfig.createLogger(true, Level.INFO, "test","test", refs, null, config, null);
loggerConfig.addAppender(appender, Level.INFO, null);
config.addLogger("test", loggerConfig);
loggerConfig.start();
</code>```

Body:
I am using Log4J 2.10.

I am trying to create async logger\appender programmatically. I need to have two things:

I should be able to specify file path for log file at run time.

I need to specify pattern at run time.

I could come up with code below. But I cannot add RollingFileAppender to AsyncAppender. There are examples on the net using AsyncAppender.wrap. But that API doesn't seem to be available with Log4J 2.10.

Do you know how I can achieve this?

void createLog4JLogger(final String logFilePath) {

    LoggerContext context = (LoggerContext) LogManager.getContext();
    final Configuration config = context.getConfiguration();

    final PatternLayout patternLayout = PatternLayout.newBuilder().withPattern(CONVERSION_PATTERN).withCharset(Charset.defaultCharset()).build();

    final RollingFileAppender fileAppender =
            RollingFileAppender.newBuilder().withName(APPENDER_NAME).withLayout(patternLayout).withFileName(logFilePath).build();

    AppenderRef ref = AppenderRef.createAppenderRef(APPENDER_NAME, null, null);
    AppenderRef[] refs = new AppenderRef[] {ref};

    final AsyncAppender asyncAppender = AsyncAppender.newBuilder().setAppenderRefs(refs).setName(APPENDER_NAME).setConfiguration(config).build();

    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, LOGGER_NAME, LOGGER_NAME, refs, null, null, null);
    loggerConfig.addAppender(asyncAppender, null, null);

    config.addAppender(asyncAppender);
    config.addLogger(LOGGER_NAME, loggerConfig);

    context.updateLoggers(config);

    final Logger logger = LogManager.getContext().getLogger(LOGGER_NAME);

    logger.info("HELLO_WORLD");

}

Body:
You can use below code to crease async logger in log4j 2.

final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.newBuilder().withConfiguration(ctx.getConfiguration()).withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - test %msg%n").build();
Appender appender = FileAppender.newBuilder().withFileName("logs/test.log").setLayout(layout)
                    .setConfiguration(config).setName("TestApp").build();
AppenderRef ref = AppenderRef.createAppenderRef("TestApp",Level.INFO, null);

config.addAppender(appender);
appender.start();
AppenderRef[] refs = new AppenderRef[] {ref};
LoggerConfig loggerConfig= AsyncLoggerConfig.createLogger(true, Level.INFO, "test","test", refs, null, config, null);
loggerConfig.addAppender(appender, Level.INFO, null);
config.addLogger("test", loggerConfig);
loggerConfig.start();


问:
Excel VBA Code (Goal Seek) Code Simplification
I'm a total novice to VBA - everything I've "coded" so far, has purely come from the Record Macro function.  The macro works, but it is incredibly clunky.
Essentially what I'm trying to do is to run a goal seek function, take that answer, and put it into a cell.  Next, I'd increment to the next input, and do the process again (and then 38 more times). Here are the first 2 increments:

```<code>Range("B11").Select
    ActiveCell.FormulaR1C1 = "=R[-8]C[13]"
    Range("C37:D37").Select
    Range("C37").GoalSeek Goal:=0, ChangingCell:=Range("A33")
    Range("A33:B37").Select
    Selection.Copy
    Range("P3").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("R11").Select

Range("B11").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R[-7]C[13]"
    Range("C37:D37").Select
    Range("C37").GoalSeek Goal:=0, ChangingCell:=Range("A33")
    Range("A33:B37").Select
    Selection.Copy
    Range("P4").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("P5").Select
</code>```

C37:D37 is my formula for the goal seek, and A33:B37 is the output I then copy and paste into the P column.
I'd like to share this code with some colleagues, but it is very unprofessional looking in it's current state. Any ideas?

Thank you!

答:
Pᴇʜ - thank you for your answer; simple, yet effective.  That's what I needed.
In case anyone in the future stumbles across this, here is what I ended up using.</p>

```<code>Sub Calculation()

Dim x As Long

For x = 1 To 40
ThisWorkbook.Worksheets("Sheet1").Range("B11").Value = ThisWorkbook.Worksheets("Sheet1").Cells(2 + x, 15)
ThisWorkbook.Worksheets("Sheet1").Range("C37").GoalSeek Goal:=0, ChangingCell:=ThisWorkbook.Worksheets("Sheet1").Range("A33")
ThisWorkbook.Worksheets("Sheet1").Cells(2 + x, 16) = ThisWorkbook.Worksheets("Sheet1").Range("A33").Value

Next

End Sub
</code>```

Body:
I'm a total novice to VBA - everything I've "coded" so far, has purely come from the Record Macro function.  The macro works, but it is incredibly clunky.
Essentially what I'm trying to do is to run a goal seek function, take that answer, and put it into a cell.  Next, I'd increment to the next input, and do the process again (and then 38 more times). Here are the first 2 increments:

Range("B11").Select
    ActiveCell.FormulaR1C1 = "=R[-8]C[13]"
    Range("C37:D37").Select
    Range("C37").GoalSeek Goal:=0, ChangingCell:=Range("A33")
    Range("A33:B37").Select
    Selection.Copy
    Range("P3").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("R11").Select

Range("B11").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R[-7]C[13]"
    Range("C37:D37").Select
    Range("C37").GoalSeek Goal:=0, ChangingCell:=Range("A33")
    Range("A33:B37").Select
    Selection.Copy
    Range("P4").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("P5").Select

C37:D37 is my formula for the goal seek, and A33:B37 is the output I then copy and paste into the P column.
I'd like to share this code with some colleagues, but it is very unprofessional looking in it's current state. Any ideas?

Thank you!

Body:
Pᴇʜ - thank you for your answer; simple, yet effective.  That's what I needed.
In case anyone in the future stumbles across this, here is what I ended up using.

Sub Calculation()

Dim x As Long

For x = 1 To 40
ThisWorkbook.Worksheets("Sheet1").Range("B11").Value = ThisWorkbook.Worksheets("Sheet1").Cells(2 + x, 15)
ThisWorkbook.Worksheets("Sheet1").Range("C37").GoalSeek Goal:=0, ChangingCell:=ThisWorkbook.Worksheets("Sheet1").Range("A33")
ThisWorkbook.Worksheets("Sheet1").Cells(2 + x, 16) = ThisWorkbook.Worksheets("Sheet1").Range("A33").Value

Next

End Sub


问:
How to change character encoding in php?
i m developing one site using wordpress deepfocus theme in that i want to show header in hebrew text but if i change name of header links in hebrew then it can not show any thing (e.g if i change Home to " לשוב " then it dont display on front end.</p>

答:
Check that you're sending the correct character set to the browser. (Right click, View Page Info in Firefox)

If the encoding is anything other than UTF-8, add this to your header:

```<code>header('Content-Type: text/html; charset=UTF-8');
</code>```

Body:
Check that you're sending the correct character set to the browser. (Right click, View Page Info in Firefox)

If the encoding is anything other than UTF-8, add this to your header:

header('Content-Type: text/html; charset=UTF-8');


问:
Turkish character problems json encode - Mysql
I output with the json_encode method. It does not show Turkish characters in the output I have received. What should I do to show Turkish characters? I am using mysql. Collation of the table = utf8_turkish_ci

```<code><?php
 $con=mysqli_connect(...);
  header('Content-Type: text/html; charset=utf-8');
    mysql_set_charset('utf8', $con);
$formID = $_POST['formID'];
     $query = "SELECT ADI_SOYADI ...";

     $result = mysqli_query($con,$query);

     $rows = array();
     while($r = mysqli_fetch_array($result)) {
         $apptADI = $r['ADI_SOYADI'];
         $results = Array("ADI_SOYADI" => $apptADI);
     }

     echo json_encode($results);

     mysqli_close($con);

?>
</code>```

答:
It seems that prior to use json_encode()you should use utf8_encode()

https://www.geeksforgeeks.org/php-utf8_encode-function/

```<code> echo json_encode(utf8_encode($results));
</code>```

There is also the parameter JSON_UNESCAPED_UNICODE that  you can add to json_encode()

Body:
I output with the json_encode method. It does not show Turkish characters in the output I have received. What should I do to show Turkish characters? I am using mysql. Collation of the table = utf8_turkish_ci

<?php
 $con=mysqli_connect(...);
  header('Content-Type: text/html; charset=utf-8');
    mysql_set_charset('utf8', $con);
$formID = $_POST['formID'];
     $query = "SELECT ADI_SOYADI ...";

     $result = mysqli_query($con,$query);

     $rows = array();
     while($r = mysqli_fetch_array($result)) {
         $apptADI = $r['ADI_SOYADI'];
         $results = Array("ADI_SOYADI" => $apptADI);
     }

     echo json_encode($results);

     mysqli_close($con);

?>

Body:
It seems that prior to use json_encode()you should use utf8_encode()

https://www.geeksforgeeks.org/php-utf8_encode-function/

 echo json_encode(utf8_encode($results));

There is also the parameter JSON_UNESCAPED_UNICODE that  you can add to json_encode()


问:
Yii2 Select2 in modal searchbox is not working
I have two yii2 projects based on kartik practical A and B. Both using johnitvn/ajaxcrudmodal. It looks like single page crud with ajax modal for create and update.

I use kartik select2 in _form.php.

However, in the project that based on practical A it can work carefully. But in the project that use practical B, it shows correctly but the searchbox is not working. It cannot be clicked and I cannot type anything on it.

I already set tabindex to false.

```<code><?php
Modal::begin([
   "id" => "ajaxCrudModal",
   "footer" => "", // always need it for jquery plugin
      'size' => Modal::SIZE_DEFAULT,
      'options' => [
      'class' => 'slide',
      'tabindex' => false // important for Select2 to work properly
   ],
])
?>
<?php Modal::end(); ?>
</code>```

Can someone help? I confused why in one project it works but not working in other project??

Thanks,

Daniel

答:
I update to the latest kartik library, and used below

```<code><?php
Modal::begin([
    'id' => 'ajaxCrudModal',
    'footer' => '', // always need it for jquery plugin
])
?>
<?php Modal::end(); ?>
<?php $this->registerJs("$.fn.modal.Constructor.prototype.enforceFocus = $.noop;"); ?>
</code>```

It works well now

Body:
I have two yii2 projects based on kartik practical A and B. Both using johnitvn/ajaxcrudmodal. It looks like single page crud with ajax modal for create and update.

I use kartik select2 in _form.php.

However, in the project that based on practical A it can work carefully. But in the project that use practical B, it shows correctly but the searchbox is not working. It cannot be clicked and I cannot type anything on it.

I already set tabindex to false.

<?php
Modal::begin([
   "id" => "ajaxCrudModal",
   "footer" => "", // always need it for jquery plugin
      'size' => Modal::SIZE_DEFAULT,
      'options' => [
      'class' => 'slide',
      'tabindex' => false // important for Select2 to work properly
   ],
])
?>
<?php Modal::end(); ?>

Can someone help? I confused why in one project it works but not working in other project??

Thanks,

Daniel

Body:
I update to the latest kartik library, and used below

<?php
Modal::begin([
    'id' => 'ajaxCrudModal',
    'footer' => '', // always need it for jquery plugin
])
?>
<?php Modal::end(); ?>
<?php $this->registerJs("$.fn.modal.Constructor.prototype.enforceFocus = $.noop;"); ?>

It works well now


问:
Check values in an array in a while loop PHP
I have a function that returns an array

```<code>$statusall = Getstatusall();
</code>```

The array looks like this
this

```<code>$statusall = ['inprogress', 'complete', 'Failed', 'inprogress', 'staring'];
</code>```

I want to loop the Getstatusall function until all the array values are 'complete' or 'failed'
How should I do that in PHP?

答:
This example echo There are values not complete or failed. Repeat. while the function Getstatusall() returns an array with values that are not complete or failed.

```<code>while( array_diff( Getstatusall(), ['complete', 'failed'] ) ) {
  echo "There are values not complete or failed. Repeat.";
  // you can even do something else or nothing
}
</code>```

If you want to get the final result, this may helps:

```<code>while( array_diff( $status = Getstatusall(), ['complete', 'failed'] ) ) {
  echo "There are values not complete or failed. Repeat."
  // you can even do something else or nothing
}
var_dump( $status );
</code>```

Body:
I have a function that returns an array

$statusall = Getstatusall();

The array looks like this
this

$statusall = ['inprogress', 'complete', 'Failed', 'inprogress', 'staring'];

I want to loop the Getstatusall function until all the array values are 'complete' or 'failed'
How should I do that in PHP?

Body:
This example echo There are values not complete or failed. Repeat. while the function Getstatusall() returns an array with values that are not complete or failed.

while( array_diff( Getstatusall(), ['complete', 'failed'] ) ) {
  echo "There are values not complete or failed. Repeat.";
  // you can even do something else or nothing
}

If you want to get the final result, this may helps:

while( array_diff( $status = Getstatusall(), ['complete', 'failed'] ) ) {
  echo "There are values not complete or failed. Repeat."
  // you can even do something else or nothing
}
var_dump( $status );


问:
Docker loads login screen, but not starting node server.js - MEAN stack
Here's most up-to-date configuration since adding bounty: Configuration

UPDATE: It looks like it's getting a cors error when clicking login, which is most likely causing the issue. I've read in other posts like this one that I need to update nginx.conf. I haven't been able to figure out how to update said file since it's already dockerized assuming this is the solution to my problem. Also could be related to not referencing cosmodb in docker-comopose, but when I add this

```<code>    cosomsdb:
        build: ./backend
        ports:
        - "10255:10255"
</code>```

I get cors error still. 10255 is cosmosdb port

```<code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/user/login. (Reason: CORS request did not succeed).
2
ERROR
Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/user/login", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:3000/api/user/login: 0 Unknown Error", error: error }
core.js:6014:19
</code>```

I'm trying to build a MEAN stack docker image, but every time I run it, it says

```<code>Error: Cannot find module '../backend/middleware/check-auth'

</code>```

I don't think it's copying my files to the container correctly. I've been going through forums, but haven't been able to find a solution. I appreciate any help!

Dockerfile

```<code>FROM node

MAINTAINER Phil

WORKDIR /src

COPY . .

RUN npm install

RUN npm install -g nodemon

EXPOSE 3000

CMD ["npm", "start"]
</code>```

docker-compose.yml

```<code>version: '3'
services:
    web:
        image: nginx
        ports:
            - "80:80"
        volumes:
        - "/Users/Phil/Documents/myapp/myapp-docker/frontend/dist:/usr/share/nginx/html"
    node:
        build: ./backend
        ports:
        - "3000:3000"
</code>```

backend package.json

```<code>{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.612.0",
    "bcrypt": "^3.0.8",
    "body-parser": "^1.19.0",
    "create-hash": "^1.2.0",
    "crypto": "^1.0.1",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.8.11",
    "mongoose-unique-validator": "^2.0.3",
    "multer": "^1.4.2",
    "multer-s3": "^2.9.0"
  }
}
</code>```

server.js file

```<code>const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});

</code>```

答:
For the CORS problem, try adding the lib cors in your server.js like this:

```<code>const cors = require('cors')
app.use(cors({
  credentials: true,
  origin: [ 'http://localhost:3000' ]
}))
</code>```

Lets see if it helps.
By the way, dotenv should always come first (;

Body:
Here's most up-to-date configuration since adding bounty: Configuration

UPDATE: It looks like it's getting a cors error when clicking login, which is most likely causing the issue. I've read in other posts like this one that I need to update nginx.conf. I haven't been able to figure out how to update said file since it's already dockerized assuming this is the solution to my problem. Also could be related to not referencing cosmodb in docker-comopose, but when I add this

    cosomsdb:
        build: ./backend
        ports:
        - "10255:10255"

I get cors error still. 10255 is cosmosdb port

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/user/login. (Reason: CORS request did not succeed).
2
ERROR
Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/user/login", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:3000/api/user/login: 0 Unknown Error", error: error }
core.js:6014:19

I'm trying to build a MEAN stack docker image, but every time I run it, it says

Error: Cannot find module '../backend/middleware/check-auth'

I don't think it's copying my files to the container correctly. I've been going through forums, but haven't been able to find a solution. I appreciate any help!

Dockerfile

FROM node

MAINTAINER Phil

WORKDIR /src

COPY . .

RUN npm install

RUN npm install -g nodemon

EXPOSE 3000

CMD ["npm", "start"]

docker-compose.yml

version: '3'
services:
    web:
        image: nginx
        ports:
            - "80:80"
        volumes:
        - "/Users/Phil/Documents/myapp/myapp-docker/frontend/dist:/usr/share/nginx/html"
    node:
        build: ./backend
        ports:
        - "3000:3000"

backend package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.612.0",
    "bcrypt": "^3.0.8",
    "body-parser": "^1.19.0",
    "create-hash": "^1.2.0",
    "crypto": "^1.0.1",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.8.11",
    "mongoose-unique-validator": "^2.0.3",
    "multer": "^1.4.2",
    "multer-s3": "^2.9.0"
  }
}

server.js file

const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});

Body:
For the CORS problem, try adding the lib cors in your server.js like this:

const cors = require('cors')
app.use(cors({
  credentials: true,
  origin: [ 'http://localhost:3000' ]
}))

Lets see if it helps.
By the way, dotenv should always come first (;


问:
Arduino sprintf float not formatting
I have this arduino sketch,

```<code>char temperature[10];
float temp = 10.55;
sprintf(temperature,"%f F", temp);
Serial.println(temperature);
</code>```

temperature prints out as

```<code>? F
</code>```

Any thoughts on how to format this float? I need it to be a char string.

答:
dtostrf() is deprecated, and it doesn't exist on every board core platforms.
On the other hand, sprintf() doesn't format floats on AVR platforms!

Title: Arduino sprintf float not formatting

Body:
I have this arduino sketch,

char temperature[10];
float temp = 10.55;
sprintf(temperature,"%f F", temp);
Serial.println(temperature);

temperature prints out as

? F

Any thoughts on how to format this float? I need it to be a char string.


问:
jwilder/nginx giving 403 permission forbidden
I'm trying to serve multiple containers with a static index.html file with a nginx reverse proxy

I've tried to follow the documentation here to create a default location

```<code>location / {
  root   /app;
  index  index.html;
  try_files $uri $uri/ /index.html;
}
</code>```

If I check my default.conf in my container with

```<code>$ docker-compose exec nginx-proxy cat /etc/nginx/conf.d/default.conf
</code>```

I get this result:

```<code>server {
        server_name _; # This is just an invalid value which will never trigger on a real hostname.
        listen 80;
        access_log /var/log/nginx/access.log vhost;
        return 503;
}
# xx.example.services
upstream xx.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer1
                        server 172.18.0.4:80;
}
server {
        server_name xx.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://xx.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}
# yy.example.services
upstream yy.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer2
                        server 172.18.0.2:80;
}
server {
        server_name yy.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://yy.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}
</code>```

If i check the content of /etc/nginx/vhost.d/default_location it is exactly what I typed in the beginning, so that's fine

However when i go to xx.example.services  I get a 403 forbidden.

To my understanding this means that no index.html file was found, but if i exec into my container and cat app/index.html it does exist!

I've checked that all my containers are on the same network.

I'm running my container with this command

```<code>docker run -d --name examplecontainer1 --expose 80 --net nginx-proxy -e VIRTUAL_HOST=xx.example.services my-container-registry
</code>```

Update
I checked the logs of my nginx-proxy container and found this error message:

[error] 29#29: *1 directory index of "/app/" is forbidden..

Tried removing $uri/ as per this SO post but this just left me with redirect cycles. Right now I'm trying to see if I can set the correct permissions, but I'm struggling

What am I missing?

答:
My issue was a basic misunderstanding that the reverse proxy can reach into the filesystem of my containers as stated by jwilder himself here.

Therefor the default location on the reverse proxy is unnecessary in my case. Instead I can simply let it point to my container, and have the nginx config in my container determine the location of my app.

Body:
I'm trying to serve multiple containers with a static index.html file with a nginx reverse proxy

I've tried to follow the documentation here to create a default location

location / {
  root   /app;
  index  index.html;
  try_files $uri $uri/ /index.html;
}

If I check my default.conf in my container with

$ docker-compose exec nginx-proxy cat /etc/nginx/conf.d/default.conf

I get this result:

server {
        server_name _; # This is just an invalid value which will never trigger on a real hostname.
        listen 80;
        access_log /var/log/nginx/access.log vhost;
        return 503;
}
# xx.example.services
upstream xx.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer1
                        server 172.18.0.4:80;
}
server {
        server_name xx.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://xx.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}
# yy.example.services
upstream yy.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer2
                        server 172.18.0.2:80;
}
server {
        server_name yy.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://yy.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}

If i check the content of /etc/nginx/vhost.d/default_location it is exactly what I typed in the beginning, so that's fine

However when i go to xx.example.services  I get a 403 forbidden.

To my understanding this means that no index.html file was found, but if i exec into my container and cat app/index.html it does exist!

I've checked that all my containers are on the same network.

I'm running my container with this command

docker run -d --name examplecontainer1 --expose 80 --net nginx-proxy -e VIRTUAL_HOST=xx.example.services my-container-registry

Update
I checked the logs of my nginx-proxy container and found this error message:

[error] 29#29: *1 directory index of "/app/" is forbidden..

Tried removing $uri/ as per this SO post but this just left me with redirect cycles. Right now I'm trying to see if I can set the correct permissions, but I'm struggling

What am I missing?