问:
Why error installing L5-Swagger in laravel 6 app?
I have laravel 6 backend rest api app and I want to create Swagger docs for add I found
https://github.com/DarkaOnLine/L5-Swagger
plugin which I suppose could use usefull creating  Swagger docs
But I encountered erros publishing config. I suppose I really need this step.

```<code>$ php artisan --version
Laravel Framework 6.13.1
serge@athoe:/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI$ composer require "darkaonline/l5-swagger"
Using version ^6.0 for darkaonline/l5-swagger
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
  - Installing symfony/yaml (v4.4.4): Downloading (100%)
  - Installing swagger-api/swagger-ui (v3.25.0): Downloading (100%)
  - Installing doctrine/annotations (v1.8.0): Downloading (100%)
  - Installing zircote/swagger-php (3.0.3): Downloading (100%)
  - Installing darkaonline/l5-swagger (6.0.3): Downloading (100%)
darkaonline/l5-swagger suggests installing zircote/swagger-php:~2.0 (!!! Require Swagger-PHP ~2.0 for @SWG annotations support !!!)
Package anahkiasen/underscore-php is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating optimized autoload files
Warning: Ambiguous class resolution, "App\library\ChunkReadFilter" was found in both "/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/app/library/importBoxRooms.php" and "/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/app/library/importTasks.php", the first will be used.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-cors
Discovered Package: barryvdh/laravel-ide-helper
Discovered Package: beyondcode/laravel-dump-server
Discovered Package: cviebrock/eloquent-sluggable
Discovered Package: darkaonline/l5-swagger
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: intervention/image
Discovered Package: laravel/tinker
Discovered Package: laravolt/avatar
Discovered Package: maatwebsite/excel
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: orangehill/iseed
Discovered Package: spatie/laravel-activitylog
Discovered Package: spatie/laravel-image-optimizer
Discovered Package: tymon/jwt-auth
Package manifest generated successfully.
serge@athoe:/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI$ php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
Copied File [/vendor/darkaonline/l5-swagger/config/l5-swagger.php] To [/config/l5-swagger.php]

   League\Flysystem\Exception  : Impossible to create the root directory "".

  at /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:112
    108|             clearstatcache(false, $root);
    109|
    110|             if ( ! is_dir($root)) {
    111|                 $errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : '';
  > 112|                 throw new Exception(sprintf('Impossible to create the root directory "%s". %s', $root, $errorMessage));
    113|             }
    114|         }
    115|     }
    116|

  Exception trace:

  1   League\Flysystem\Adapter\Local::ensureDirectory()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:78

  2   League\Flysystem\Adapter\Local::__construct()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:235

  Please use the argument -v to see more details.
serge@athoe:/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI$ php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" -v

   League\Flysystem\Exception  : Impossible to create the root directory "".

  at /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:112
    108|             clearstatcache(false, $root);
    109|
    110|             if ( ! is_dir($root)) {
    111|                 $errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : '';
  > 112|                 throw new Exception(sprintf('Impossible to create the root directory "%s". %s', $root, $errorMessage));
    113|             }
    114|         }
    115|     }
    116|

  Exception trace:

  1   League\Flysystem\Adapter\Local::ensureDirectory()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:78

  2   League\Flysystem\Adapter\Local::__construct()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:235

  3   Illuminate\Foundation\Console\VendorPublishCommand::publishDirectory("/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/darkaonline/l5-swagger/src/../resources/views")
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:200

  4   Illuminate\Foundation\Console\VendorPublishCommand::publishItem("/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/darkaonline/l5-swagger/src/../resources/views")
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:163

  5   Illuminate\Foundation\Console\VendorPublishCommand::publishTag()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:76

  6   Illuminate\Foundation\Console\VendorPublishCommand::handle()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32

  7   call_user_func_array([])
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32

  8   Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/Util.php:36

  9   Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:90

  10  Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Object(Closure))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:34

  11  Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), [])
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/Container.php:590

  12  Illuminate\Container\Container::call()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Console/Command.php:201

  13  Illuminate\Console\Command::execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Command/Command.php:255

  14  Symfony\Component\Console\Command\Command::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Console/Command.php:188

  15  Illuminate\Console\Command::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Application.php:1012

  16  Symfony\Component\Console\Application::doRunCommand(Object(Illuminate\Foundation\Console\VendorPublishCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Application.php:272

  17  Symfony\Component\Console\Application::doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Application.php:148

  18  Symfony\Component\Console\Application::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Console/Application.php:93

  19  Illuminate\Console\Application::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:131

  20  Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/artisan:37
</code>```

Googling for decision I tried run :

```<code>chown -R www-data:root .
</code>```

But it did not help.

also I do not have any problems with settging other plugins, configurations.

How fix it ?

Thanks!

答:
As far as I see from your stack trace, the command fails to create a views directory (./resources/views/vendor/l5-swagger).

Note: chown -R www-data:root . - this command can create some new problems..

After that command, owner is www-data (but you start artisan commands as serge).

After that command, group is root (but serge may not be part of that group).

You have to verify that your user (serge) has proper permissions there (./resources/views, ./resources/views/vendor).

To check current permissions run: ls -la ./resources, ls -la ./resources/views, and ls -la ./resources/views/vendor (if vendor exists already)

Maybe you need something like: sudo chmod -R serge.www-data (serge - owner, www-data - group)

However, it mostly depends on your specific setup and desired result.

Body:
I have laravel 6 backend rest api app and I want to create Swagger docs for add I found
https://github.com/DarkaOnLine/L5-Swagger
plugin which I suppose could use usefull creating  Swagger docs
But I encountered erros publishing config. I suppose I really need this step.

$ php artisan --version
Laravel Framework 6.13.1
serge@athoe:/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI$ composer require "darkaonline/l5-swagger"
Using version ^6.0 for darkaonline/l5-swagger
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
  - Installing symfony/yaml (v4.4.4): Downloading (100%)
  - Installing swagger-api/swagger-ui (v3.25.0): Downloading (100%)
  - Installing doctrine/annotations (v1.8.0): Downloading (100%)
  - Installing zircote/swagger-php (3.0.3): Downloading (100%)
  - Installing darkaonline/l5-swagger (6.0.3): Downloading (100%)
darkaonline/l5-swagger suggests installing zircote/swagger-php:~2.0 (!!! Require Swagger-PHP ~2.0 for @SWG annotations support !!!)
Package anahkiasen/underscore-php is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating optimized autoload files
Warning: Ambiguous class resolution, "App\library\ChunkReadFilter" was found in both "/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/app/library/importBoxRooms.php" and "/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/app/library/importTasks.php", the first will be used.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-cors
Discovered Package: barryvdh/laravel-ide-helper
Discovered Package: beyondcode/laravel-dump-server
Discovered Package: cviebrock/eloquent-sluggable
Discovered Package: darkaonline/l5-swagger
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: intervention/image
Discovered Package: laravel/tinker
Discovered Package: laravolt/avatar
Discovered Package: maatwebsite/excel
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: orangehill/iseed
Discovered Package: spatie/laravel-activitylog
Discovered Package: spatie/laravel-image-optimizer
Discovered Package: tymon/jwt-auth
Package manifest generated successfully.
serge@athoe:/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI$ php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
Copied File [/vendor/darkaonline/l5-swagger/config/l5-swagger.php] To [/config/l5-swagger.php]

   League\Flysystem\Exception  : Impossible to create the root directory "".

  at /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:112
    108|             clearstatcache(false, $root);
    109|
    110|             if ( ! is_dir($root)) {
    111|                 $errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : '';
  > 112|                 throw new Exception(sprintf('Impossible to create the root directory "%s". %s', $root, $errorMessage));
    113|             }
    114|         }
    115|     }
    116|

  Exception trace:

  1   League\Flysystem\Adapter\Local::ensureDirectory()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:78

  2   League\Flysystem\Adapter\Local::__construct()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:235

  Please use the argument -v to see more details.
serge@athoe:/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI$ php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" -v

   League\Flysystem\Exception  : Impossible to create the root directory "".

  at /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:112
    108|             clearstatcache(false, $root);
    109|
    110|             if ( ! is_dir($root)) {
    111|                 $errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : '';
  > 112|                 throw new Exception(sprintf('Impossible to create the root directory "%s". %s', $root, $errorMessage));
    113|             }
    114|         }
    115|     }
    116|

  Exception trace:

  1   League\Flysystem\Adapter\Local::ensureDirectory()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/league/flysystem/src/Adapter/Local.php:78

  2   League\Flysystem\Adapter\Local::__construct()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:235

  3   Illuminate\Foundation\Console\VendorPublishCommand::publishDirectory("/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/darkaonline/l5-swagger/src/../resources/views")
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:200

  4   Illuminate\Foundation\Console\VendorPublishCommand::publishItem("/mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/darkaonline/l5-swagger/src/../resources/views")
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:163

  5   Illuminate\Foundation\Console\VendorPublishCommand::publishTag()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/VendorPublishCommand.php:76

  6   Illuminate\Foundation\Console\VendorPublishCommand::handle()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32

  7   call_user_func_array([])
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32

  8   Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/Util.php:36

  9   Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:90

  10  Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Object(Closure))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:34

  11  Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), [])
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Container/Container.php:590

  12  Illuminate\Container\Container::call()
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Console/Command.php:201

  13  Illuminate\Console\Command::execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Command/Command.php:255

  14  Symfony\Component\Console\Command\Command::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Console/Command.php:188

  15  Illuminate\Console\Command::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Application.php:1012

  16  Symfony\Component\Console\Application::doRunCommand(Object(Illuminate\Foundation\Console\VendorPublishCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Application.php:272

  17  Symfony\Component\Console\Application::doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/symfony/console/Application.php:148

  18  Symfony\Component\Console\Application::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Console/Application.php:93

  19  Illuminate\Console\Application::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:131

  20  Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
      /mnt/_work_sdb8/wwwroot/lar/CTasksRestAPI/artisan:37

Googling for decision I tried run :

chown -R www-data:root .

But it did not help.

also I do not have any problems with settging other plugins, configurations.

How fix it ?

Thanks!


来源: stackexchange

问:
django table has no column named Exception
Git Repository
Request to guide me on what to do.

I work on an e-commerce website with the help of Django. and I'm a beginner in Django
The following image provides a table of my database. It helps to add a product

Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.

An error occurred while migrating

Request to guide me on what to do.

答:
Take a look at here (Django Migrations Workflow)

I've seen your migrations folder on your Github repo and there was no sign of any of the fields you mentioned.

Every time you add fields to your models, you need to run following commands in terminal

```<code>python manage.py makemigrations <app name>
python manage.py migrate
</code>```

These commands are going to modify your tables.

Please markdown your question instead of putting a picture from your code.
Check this out: How do I ask a good question?

EDIT:

In your Product model, there is a field named desc. You need to set a default value for it; Otherwise, you need to update the records in your database manually.

```<code>desc = models.CharField(max_length=300, default='')
</code>```

After you do that, this error will happen to the pub_date field too. So, if your current Product objects in your database are not important, you can simply delete the database file db.sqlite3 and delete your migrations file from this address shop/migrations/0001_initial.py and try the migration commands again.

ContentLicense: CC BY-SA 4.0

Body:
Take a look at here (Django Migrations Workflow)

I've seen your migrations folder on your Github repo and there was no sign of any of the fields you mentioned.

Every time you add fields to your models, you need to run following commands in terminal

python manage.py makemigrations <app name>
python manage.py migrate

These commands are going to modify your tables.

Please markdown your question instead of putting a picture from your code.
Check this out: How do I ask a good question?

EDIT:

In your Product model, there is a field named desc. You need to set a default value for it; Otherwise, you need to update the records in your database manually.

desc = models.CharField(max_length=300, default='')

After you do that, this error will happen to the pub_date field too. So, if your current Product objects in your database are not important, you can simply delete the database file db.sqlite3 and delete your migrations file from this address shop/migrations/0001_initial.py and try the migration commands again.


问:
Hide Splash Screen in Ionic Capacitor React
How can we disable the splash screen on an Ionic App? I am using Ionic 4, Capacitor and React. I have tried to add this on capacitor.config.json

```<code>{
  "plugins": {
    "SplashScreen": {
      "launchShowDuration": 0
    }
  }
}
</code>```

The above code is not working at all.

答:
You can just add below line in config.xml

```<code><preference name="SplashScreenDelay" value="0"/>
</code>```

Body:
How can we disable the splash screen on an Ionic App? I am using Ionic 4, Capacitor and React. I have tried to add this on capacitor.config.json

{
  "plugins": {
    "SplashScreen": {
      "launchShowDuration": 0
    }
  }
}

The above code is not working at all.

Body:
You can just add below line in config.xml

<preference name="SplashScreenDelay" value="0"/>


问:
update array of objects in localstorage without leaveing a null
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

```<code>[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

```<code>[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!

答:
You have several options to do this.

Option 1: .splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

const data = [{name: " Name1", description: "Description1", comment: "Comment1"}, {name: " Name2", description: "Description2", comment: "Comment2"}, {name: " Name3", description: "Description3", comment: "Comment3"}];

const s = data.splice(1,1);

console.log(data, 'removed: =>', s);```
</div>
</div>
</p>

<p>Option 2: .filter()</p>

<blockquote>
  <p>The filter() method creates a new array with all elements that pass the test implemented by the provided function.</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [{name: "Name1", description: "Description1", comment: "Comment1"}, {name: " Name2", description: "Description2", comment: "Comment2"}, {name: " Name3", description: "Description3", comment: "Comment3"}];

console.log(data.filter(item => item && item.name !== 'Name1'))</code>```

Option 3: Loops

Body:
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!

Body:
You have several options to do this.

Option 1: .splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

const data = [{name: " Name1", description: "Description1", comment: "Comment1"}, {name: " Name2", description: "Description2", comment: "Comment2"}, {name: " Name3", description: "Description3", comment: "Comment3"}];

const s = data.splice(1,1);

console.log(data, 'removed: =>', s);

Option 2: .filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

const data = [{name: "Name1", description: "Description1", comment: "Comment1"}, {name: " Name2", description: "Description2", comment: "Comment2"}, {name: " Name3", description: "Description3", comment: "Comment3"}];

console.log(data.filter(item => item && item.name !== 'Name1'))

Option 3: Loops


问:
Failed parsing Thymeleaf template when validating form with Spring Bean Validation API
I am following this book "Spring In Action 5th Edition" example, but having this error whenever validation on form input found something invalid.

error:

```<code>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Oct 27 17:26:07 SGT 2019
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/design.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/design.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)
    at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:362)
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:189)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1371)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1117)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1056)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "design" - line 59, col 20)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 52 more
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "design" - line 59, col 20)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918)
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleStandaloneElementEnd(TemplateHandlerAdapterMarkupHandler.java:260)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:256)
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleStandaloneElementEnd(OutputExpressionInlinePreProcessorHandler.java:169)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:104)
    at org.attoparser.HtmlElement.handleStandaloneElementEnd(HtmlElement.java:79)
    at org.attoparser.HtmlMarkupHandler.handleStandaloneElementEnd(HtmlMarkupHandler.java:241)
    at org.attoparser.MarkupEventProcessorHandler.handleStandaloneElementEnd(MarkupEventProcessorHandler.java:327)
    at org.attoparser.ParsingElementMarkupUtil.parseStandaloneElement(ParsingElementMarkupUtil.java:96)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:706)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    ... 54 more
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'design' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)
    at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    ... 67 more

</code>```

Object been passed to view template:

```<code>package tacos;

import java.util.List;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import lombok.Data;

@Data
public class Taco {

    @NotNull
    @Size(min=5, message="Name must be at least 5 characters long")
    private String name;

    @NotNull
    @Size(min=2, message="You must choose at least 2 ingredient")
    private List<String> ingredients;
}
</code>```

Thymeleaf view template:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
<link rel="stylesheet" th:href="@{/styles.css}" />
</head>
<body>
<h1>Design your taco!</h1>
<img th:src="@{/images/TacoCloud.png}"/>
<form method="POST" th:object="${design}">
<div class="grid">
<div class="ingredient-group" id="wraps">
<h3>Designate your wrap:</h3>
<div th:each="ingredient : ${wrap}">
<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group" id="proteins">
<h3>Pick your protein:</h3>
<div th:each="ingredient : ${protein}">
<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group" id="cheeses">
<h3>Choose your cheese:</h3>
<div th:each="ingredient : ${cheese}">
<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group" id="veggies">
<h3>Determine your veggies:</h3>
<div th:each="ingredient : ${veggies}">
<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
<div class="ingredient-group" id="sauces">
<h3>Select your sauce:</h3>
<div th:each="ingredient : ${sauce}">
<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
<span th:text="${ingredient.name}">INGREDIENT</span><br/>
</div>
</div>
</div>
<div>
<h3>Name your taco creation:</h3>
<input type="text" th:field="*{name}"/>
<span class="validationError"
                th:if="${#fields.hasErrors('name')}"
                th:errors="*{name}">Name Error</span>
<br/>
<button>Submit your taco</button>
</div>
</form>
</body>
</html>
</code>```

Controller display form method:

```<code>    @GetMapping
    public String showDesignForm(Model model)
    {
        List<Ingredient> ingredients = Arrays.asList(
                new Ingredient("FLTO", "Flour Tortilla", Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
                new Ingredient("CARN", "Carnitas", Type.PROTEIN),
                new Ingredient("TMTO", "Diced Tomatoes", Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Type.VEGGIES),
                new Ingredient("CHED", "Cheddar", Type.CHEESE),
                new Ingredient("JACK", "Monterrey Jack", Type.CHEESE),
                new Ingredient("SLSA", "Salsa", Type.SAUCE),
                new Ingredient("SRCR", "Sour Cream", Type.SAUCE)
                );

        Type[] types = Ingredient.Type.values();
        for (Type type : types)
        {
            model.addAttribute(type.toString().toLowerCase(),
                    filterByType(ingredients, type));
        }

        model.addAttribute("design", new Taco());

        return "design";
    }
</code>```

Controller process form method:

```<code>    @PostMapping
    public String processDesign(@Valid Taco taco, Errors errors)
    {
        if (errors.hasErrors())
        {
            return "design";
        }

        // Save the taco design...
        // We will do this in chapter 3
        log.info("Processing design: " + taco);

        return "redirect:/orders/current";
    }
</code>```

I have no issue in displaying the form. All input fields are well received and processed. But whenever there is validation errors, and process form method call back to the form page "design", the form  failed to parse with above mentioned errors.

I had tried:
1. to disable validation on the Taco.name field;
2. to remove the  which displays the name field errors.
But none of them work.

Thanks in advance for your help.

答:
I had a similar problem. This is what I did to fix it.

1st - change the opening header in design.html to the following

```<code><form method="POST" th:object="${design}">
</code>```

2nd - my processDesign() method looks like this:

```<code>public String processDesign(@Valid @ModelAttribute("design") Taco taco, Errors errors) {

    if (errors.hasErrors()) {
        return "design";
    }

    // this will save our Taco Design
    // log.info("Processing design: " + design);

    return "redirect:/orders/current";
}
</code>```

I hope, that this helps and I'm not too late. In general, there are multiple similar errors in the book, that need to be fixed, but the community around it is great, so no need to worry.

Cheers

Body:
I am following this book "Spring In Action 5th Edition" example, but having this error whenever validation on form input found something invalid.

error:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Oct 27 17:26:07 SGT 2019
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/design.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/design.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)
    at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:362)
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:189)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1371)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1117)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1056)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "design" - line 59, col 20)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 52 more
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "design" - line 59, col 20)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918)
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleStandaloneElementEnd(TemplateHandlerAdapterMarkupHandler.java:260)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:256)
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleStandaloneElementEnd(OutputExpressionInlinePreProcessorHandler.java:169)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:104)
    at org.attoparser.HtmlElement.handleStandaloneElementEnd(HtmlElement.java:79)
    at org.attoparser.HtmlMarkupHandler.handleStandaloneElementEnd(HtmlMarkupHandler.java:241)
    at org.attoparser.MarkupEventProcessorHandler.handleStandaloneElementEnd(MarkupEventProcessorHandler.java:327)
    at org.attoparser.ParsingElementMarkupUtil.parseStandaloneElement(ParsingElementMarkupUtil.java:96)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:706)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    ... 54 more
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'design' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)
    at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    ... 67 more

Object been passed to view template:

package tacos;

import java.util.List;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import lombok.Data;

@Data
public class Taco {

    @NotNull
    @Size(min=5, message="Name must be at least 5 characters long")
    private String name;

    @NotNull
    @Size(min=2, message="You must choose at least 2 ingredient")
    private List<String> ingredients;
}

Thymeleaf view template:

<!DOCTYPE html>

<title>Taco Cloud</title>
<link rel="stylesheet" th:href="@{/styles.css}" />

Design your taco!

<form method="POST" th:object="${design}">

Designate your wrap:

<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
INGREDIENT

Pick your protein:

<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
INGREDIENT

Choose your cheese:

<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
INGREDIENT

Determine your veggies:

<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
INGREDIENT

Select your sauce:

<input name="ingredients" type="checkbox" th:value="${ingredient.id}"
/>
INGREDIENT

Name your taco creation:

<input type="text" th:field="*{name}"/>
Name Error

<button>Submit your taco</button>

</form>

Controller display form method:

    @GetMapping
    public String showDesignForm(Model model)
    {
        List<Ingredient> ingredients = Arrays.asList(
                new Ingredient("FLTO", "Flour Tortilla", Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
                new Ingredient("CARN", "Carnitas", Type.PROTEIN),
                new Ingredient("TMTO", "Diced Tomatoes", Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Type.VEGGIES),
                new Ingredient("CHED", "Cheddar", Type.CHEESE),
                new Ingredient("JACK", "Monterrey Jack", Type.CHEESE),
                new Ingredient("SLSA", "Salsa", Type.SAUCE),
                new Ingredient("SRCR", "Sour Cream", Type.SAUCE)
                );

        Type[] types = Ingredient.Type.values();
        for (Type type : types)
        {
            model.addAttribute(type.toString().toLowerCase(),
                    filterByType(ingredients, type));
        }

        model.addAttribute("design", new Taco());

        return "design";
    }

Controller process form method:

    @PostMapping
    public String processDesign(@Valid Taco taco, Errors errors)
    {
        if (errors.hasErrors())
        {
            return "design";
        }

        // Save the taco design...
        // We will do this in chapter 3
        log.info("Processing design: " + taco);

        return "redirect:/orders/current";
    }

I have no issue in displaying the form. All input fields are well received and processed. But whenever there is validation errors, and process form method call back to the form page "design", the form  failed to parse with above mentioned errors.

I had tried:
1. to disable validation on the Taco.name field;
2. to remove the  which displays the name field errors.
But none of them work.

Thanks in advance for your help.

Body:
I had a similar problem. This is what I did to fix it.

1st - change the opening header in design.html to the following

<form method="POST" th:object="${design}">

2nd - my processDesign() method looks like this:

public String processDesign(@Valid @ModelAttribute("design") Taco taco, Errors errors) {

    if (errors.hasErrors()) {
        return "design";
    }

    // this will save our Taco Design
    // log.info("Processing design: " + design);

    return "redirect:/orders/current";
}

I hope, that this helps and I'm not too late. In general, there are multiple similar errors in the book, that need to be fixed, but the community around it is great, so no need to worry.

Cheers


问:
How to fix: "E/AndroidRuntime: FATAL EXCEPTION: main"?
I am developing an application, and every time I run it, my app crashes. When I look in Stack trace I receive this message.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: fast.com, PID: 17032
    java.lang.RuntimeException: Unable to start activity ComponentInfo{fast.com/fast.com.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference
        at fast.com.MainActivity$1.<init>(MainActivity.java:30)
        at fast.com.MainActivity.onCreate(MainActivity.java:29)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494) emphasized text
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

When I look to Stack Trace I understand nothing. If you have some time please answer because I really need it.

答:
Here is MainActivity </p>

```<code>package fast.com;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
Button haveAccountButton, signUpButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    haveAccountButton = findViewById(R.id.haveAccountButton);

    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
       FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
             if (mFirebaseUser != null ){
                 Toast.makeText(MainActivity.this, "You're logged in",
Toast.LENGTH_SHORT).show();
                 Intent i = new Intent(MainActivity.this, Home.class);
                 startActivity(i);
             }
             else{
                 Toast.makeText(MainActivity.this, "Please Login",
Toast.LENGTH_SHORT).show();
             }
        }
    };

    haveAccountButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intToSignUp = new Intent(MainActivity.this, SignUp.class);
            startActivity(intToSignUp);
        }
    });

}

}
</code>```

Body:
I am developing an application, and every time I run it, my app crashes. When I look in Stack trace I receive this message.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: fast.com, PID: 17032
    java.lang.RuntimeException: Unable to start activity ComponentInfo{fast.com/fast.com.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference
        at fast.com.MainActivity$1.<init>(MainActivity.java:30)
        at fast.com.MainActivity.onCreate(MainActivity.java:29)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494) emphasized text
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

When I look to Stack Trace I understand nothing. If you have some time please answer because I really need it.

Body:
Here is MainActivity

package fast.com;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
Button haveAccountButton, signUpButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    haveAccountButton = findViewById(R.id.haveAccountButton);

    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
       FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
             if (mFirebaseUser != null ){
                 Toast.makeText(MainActivity.this, "You're logged in",
Toast.LENGTH_SHORT).show();
                 Intent i = new Intent(MainActivity.this, Home.class);
                 startActivity(i);
             }
             else{
                 Toast.makeText(MainActivity.this, "Please Login",
Toast.LENGTH_SHORT).show();
             }
        }
    };

    haveAccountButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intToSignUp = new Intent(MainActivity.this, SignUp.class);
            startActivity(intToSignUp);
        }
    });

}

}


问:
Why isn't "--comment" working when "-- comment" does?
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?</p>

```<code><?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>
</code>```

答:
From the manual:
the “-- ” (double-dash) comment style requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on).

ContentLicense: CC BY-SA 3.0

Body:
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?

<?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>


问:
"SyntaxError: Cannot use import statement outside a module" when running a Jest test with Vue Js
I followed this tutorial https://frontstuff.io/build-your-first-vue-js-component to build a vue js component.
I then followed this tutorial https://frontstuff.io/unit-test-your-first-vuejs-component to unit test the component.
The unit test fails at the import statement on the component and returns this error:

● Test suite failed to run

```<code>C:\Users\SHINIGAMI-ALFSABAH\Documents\Workspace\Dev\Vue\star-rating\node_modules\vue-awesome\icons\star.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module

  12 |
  13 | <script>
> 14 |     import 'vue-awesome/icons/star'
     | ^
  15 |     import Icon from 'vue-awesome/components/Icon'
  16 |
  17 |     export default {

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at src/components/Rating.vue:14:1
  at Object.<anonymous> (src/components/Rating.vue:67:3)
</code>```

Any help will be appreciated.

答:
I found an answer on SO from a previous similar question Unexpected token 'import' error while running Jest tests?

Basically I had to change my transformIgnorePatterns array in my jest config from:

transformIgnorePatterns: ["/node_modules/"],

to

transformIgnorePatterns: ["/node_modules/(?!vue-awesome)"],

making sure jest compiles 'vue-awesome' module to use in the test.

Body:
I followed this tutorial https://frontstuff.io/build-your-first-vue-js-component to build a vue js component.
I then followed this tutorial https://frontstuff.io/unit-test-your-first-vuejs-component to unit test the component.
The unit test fails at the import statement on the component and returns this error:

● Test suite failed to run

C:\Users\SHINIGAMI-ALFSABAH\Documents\Workspace\Dev\Vue\star-rating\node_modules\vue-awesome\icons\star.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module

  12 |
  13 |


答:
If you want to delete items from an array it's better you use array method

```<code>array.splice(index, 1);
</code>```

If you want to delete item from the object

```<code>delete array[x]

let newArray = array.filter(x => x)
</code>```

so newArray is without null value

Title: update array of objects in localstorage without leaveing a null

Body:
If you want to delete items from an array it's better you use array method

array.splice(index, 1);

If you want to delete item from the object

delete array[x]

let newArray = array.filter(x => x)

so newArray is without null value


问:
How to select active Word document from Access VBA
I wrote some VBA in Access which to export data to one Excel sheet and two Word docs. If I have no other Word docs open everything works. If another instance of Word is running, some of my selections and data ends up in this other open Word document.

The error occurs at the Selection.EndKey.... point. I know that it is because I am referencing that selection in Word from Access.

How do I reference that selection, so it does it in the "wDoct" document?

The selection takes the last line and makes it bold, then moves one tab to the right and inserts more data.

Public Sub ExportToWord()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim wDoct As Word.Document
Dim rs As DAO.Recordset
Dim exApp As Excel.Application
Dim exWb As Excel.Workbook
Dim exWs As Excel.Worksheet
Dim nextrow As Long
Dim rng As Word.Range

Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Users\Peter\Documents\testdoc.docm", ReadOnly:=False)
Set wDoct = wApp.Documents.Open("C:\Users\Peter\Documents\Trends.docx")
Set rs = CurrentDb.OpenRecordset("Overall")
Set exApp = New Excel.Application
Set exWb = exApp.Workbooks.Open("C:\Users\Peter\Documents\727TRACKER.xlsx", ReadOnly:=False)
Set exWs = exWb.Worksheets("MIS")

If Not rs.EOF Then rs.MoveLast

wDoc.Bookmarks("name").Range.Text = Nz(rs!Name, "")

nextrow = exWs.Cells(exWs.Rows.Count, "A").End(xlUp).Row + 1 'select last row in tracker
exWs.Range("A" & nextrow).Value = Nz(rs!Name, "")  'insert to last row

wDoct.Content.InsertAfter Text:=vbCr & Nz(rs!Name, "") & "date" 'insert last row in Word
Selection.EndKey Unit:=wdStory  'this is where it fails (select last row in and make bold)
Selection.MoveStart Unit:=wdLine, Count:=-1
Set rng = Selection.Range

With rng.Font
    .Bold = True
End With

Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.TypeText Text:=vbTab
Selection.Font.Bold = wdToggle
Selection.TypeText Text:=Nz(rs!Name, "")

Set rs = CurrentDb.OpenRecordset("Grades")

If Not rs.EOF Then rs.MoveLast

wDoc.Bookmarks("briefQ").Range.Text = Nz(rs!PlanQ, "")
wDoc.Bookmarks("briefQmin").Range.Text = Nz(rs!PlanQMin, "")

With wDoc.Content.Find
    .Text = "True"
    .Replacement.Text = "X"
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
End With

With wDoc.Content.Find
    .Text = "False"
    .Replacement.Text = ""
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
End With

Dim ctlList As Control, strItems As String, index As Integer

Set ctlList = Forms!Grades1!List96

For index = 0 To ctlList.ListCount - 1
    If ctlList.Selected(index) Then
        strItems = strItems & ctlList.Column(0, _
          index) & ";"
    End If
Next index

wDoc.Bookmarks("type").Range.Text = strItems

wApp.DisplayAlerts = False
wDoc.SaveAs2 "C:\Users\Peter\Documents\" & rs!ID & "_gradesheet.docm"
wDoc.Close
wDoct.Save
wApp.Quit

exApp.DisplayAlerts = False
exWb.Close True

Set exWs = Nothing
Set exWb = Nothing
exApp.Quit
Set exApp = Nothing

Set wApp = Nothing
Set wDoc = Nothing
Set wDoct = Nothing
Set rng = Nothing

End Sub
```

答:
I solved it using this instead:</p>
```<code>wDoct.Content.InsertAfter Text:=vbCr & Nz(rs!name, "") & "date" 'insert last row in          Word
wDoct.Content.InsertAfter Text:=vbTab & "name"
wDoct.Range(Start:=wDoct.Paragraphs.Last.Range.Start,     End:=wDoct.Paragraphs.Last.Range.Start + 10).Bold = True
</code>```

Body:
I solved it using this instead:

wDoct.Content.InsertAfter Text:=vbCr & Nz(rs!name, "") & "date" 'insert last row in          Word
wDoct.Content.InsertAfter Text:=vbTab & "name"
wDoct.Range(Start:=wDoct.Paragraphs.Last.Range.Start,     End:=wDoct.Paragraphs.Last.Range.Start + 10).Bold = True


问:
How do I hide Material Bottom App Bar when Coordinator Layout's child fragment is scrolled?
I wonder why app:hideOnScroll="true" is not working in my case, when I want my BottomAppBar to be hidden when scrolling.
I want to achieve something like this: Hide bottom app bar on scroll

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:elevation="0dp">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorBackgroundPrimary"
            android:theme="@style/customtoolbar"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:titleTextColor="@color/colorTextPrimary" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bar"
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorBtn"
        app:hideOnScroll="true"
        app:layout_scrollFlags="scroll|enterAlways"
        app:navigationIcon="@drawable/baseline_menu_24"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/colorPrimaryDark"
        android:src="@drawable/baseline_add_24"
        app:layout_anchor="@id/bar" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

content_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundPrimary"
    android:backgroundTint="@color/colorBackgroundPrimary"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答: root element of content_main.xml should be NestedScrollView or RecyclerView if you want to enable hideOnScroll

Body:
I wonder why app:hideOnScroll="true" is not working in my case, when I want my BottomAppBar to be hidden when scrolling.
I want to achieve something like this: Hide bottom app bar on scroll

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:elevation="0dp">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorBackgroundPrimary"
            android:theme="@style/customtoolbar"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:titleTextColor="@color/colorTextPrimary" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bar"
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorBtn"
        app:hideOnScroll="true"
        app:layout_scrollFlags="scroll|enterAlways"
        app:navigationIcon="@drawable/baseline_menu_24"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/colorPrimaryDark"
        android:src="@drawable/baseline_add_24"
        app:layout_anchor="@id/bar" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundPrimary"
    android:backgroundTint="@color/colorBackgroundPrimary"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>


问:
ModuleNotFoundError: No module named 'tensorflow' In Jupyter Notebook
I'm getting this error in my Jupyter Notebook. The complete error is bellow:

```<code>---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
 in
      1 import numpy as np # working with data
      2 import pandas as pd
----> 3 from keras.layers.core import Dense, Activation, Dropout
      4 from keras.layers.recurrent import LSTM
      5 from keras.models import Sequential

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\__init__.py in
      1 from __future__ import absolute_import
      2
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\__init__.py in
      4 from . import data_utils
      5 from . import io_utils
----> 6 from . import conv_utils
      7 from . import losses_utils
      8 from . import metrics_utils

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\conv_utils.py in
      7 from six.moves import range
      8 import numpy as np
----> 9 from .. import backend as K
     10
     11

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\__init__.py in
----> 1 from .load_backend import epsilon
      2 from .load_backend import set_epsilon
      3 from .load_backend import floatx
      4 from .load_backend import set_floatx
      5 from .load_backend import cast_to_floatx

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\load_backend.py in
     88 elif _BACKEND == 'tensorflow':
     89     sys.stderr.write('Using TensorFlow backend.\n')
---> 90     from .tensorflow_backend import *
     91 else:
     92     # Try and load external backend.

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\tensorflow_backend.py in
      3 from __future__ import print_function
      4
----> 5 import tensorflow as tf
      6 from tensorflow.python.eager import context
      7 from tensorflow.python.framework import device as tfdev

ModuleNotFoundError: No module named 'tensorflow'
</code>```

In cmd: My python version is:

```<code>C:\Users\casper>python --version
Python 3.6.5 :: Anaconda, Inc.
</code>```

Anaconda version:

```<code>C:\Users\casper>conda --version
conda 4.5.4
</code>```

In Anaconda Prompt I install Tensorflow like below:

```<code>conda create -n tensorflow python=3.6
// CPU edition
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorflow
</code>```

In Anaconda Prompt: My Tensorflow version is:

```<code>(base) C:\Users\casper>activate tensorflow

(tensorflow) C:\Users\casper>python
Python 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 12:30:02) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
2020-02-14 19:36:32.468120: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-02-14 19:36:32.474896: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> tf.__version__
'2.1.0'
>>> tf.__path__
['D:\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow']
</code>```

It's really the first time I'm working with all these libraries and technologies, I lost the track, I can see all around its different Python versions, It's really messed up for me now. How could I fix it ?

答: Remember to change to the right kernel. You can do that in Jupyter Notebook, by pressing Kernel. Then select Change kernel and select your kernel.

Body:
I'm getting this error in my Jupyter Notebook. The complete error is bellow:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
 in
      1 import numpy as np # working with data
      2 import pandas as pd
----> 3 from keras.layers.core import Dense, Activation, Dropout
      4 from keras.layers.recurrent import LSTM
      5 from keras.models import Sequential

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\__init__.py in
      1 from __future__ import absolute_import
      2
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\__init__.py in
      4 from . import data_utils
      5 from . import io_utils
----> 6 from . import conv_utils
      7 from . import losses_utils
      8 from . import metrics_utils

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\conv_utils.py in
      7 from six.moves import range
      8 import numpy as np
----> 9 from .. import backend as K
     10
     11

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\__init__.py in
----> 1 from .load_backend import epsilon
      2 from .load_backend import set_epsilon
      3 from .load_backend import floatx
      4 from .load_backend import set_floatx
      5 from .load_backend import cast_to_floatx

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\load_backend.py in
     88 elif _BACKEND == 'tensorflow':
     89     sys.stderr.write('Using TensorFlow backend.\n')
---> 90     from .tensorflow_backend import *
     91 else:
     92     # Try and load external backend.

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\tensorflow_backend.py in
      3 from __future__ import print_function
      4
----> 5 import tensorflow as tf
      6 from tensorflow.python.eager import context
      7 from tensorflow.python.framework import device as tfdev

ModuleNotFoundError: No module named 'tensorflow'

In cmd: My python version is:

C:\Users\casper>python --version
Python 3.6.5 :: Anaconda, Inc.

Anaconda version:

C:\Users\casper>conda --version
conda 4.5.4

In Anaconda Prompt I install Tensorflow like below:

conda create -n tensorflow python=3.6
// CPU edition
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorflow

In Anaconda Prompt: My Tensorflow version is:

(base) C:\Users\casper>activate tensorflow

(tensorflow) C:\Users\casper>python
Python 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 12:30:02) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
2020-02-14 19:36:32.468120: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-02-14 19:36:32.474896: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> tf.__version__
'2.1.0'
>>> tf.__path__
['D:\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow']

It's really the first time I'm working with all these libraries and technologies, I lost the track, I can see all around its different Python versions, It's really messed up for me now. How could I fix it ?


问:
akka timer giving message Cancel timer [Message] with generation [583]
i am using akka timer

i am using twitter streams and i am trying to get the number of tweets in 5 second
here is my code

```<code>case class PerSecond(tweet:Tweet)
case class TweetPerSecondCount(tweet:Tweet)

class TweetPerSecondActor extends Actor with Timers{
var counter=0
 def receive: PartialFunction[Any, Unit] = {
    case PerSecond(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message PerSecond")
      timers.startPeriodicTimer("perSecond", TweetPerSecondCount(tweet), 5.second)

    case TweetPerSecondCount(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message TweetPerSecondCount")
      log.info("got the tweet {}",getCounter+"in 5 seconds")

    case message =>
      log.warn("Actor TweetPerSecondActor: Unhandled message received : {}", message)
      unhandled(message)
  }
}
</code>```

in play framework's controller Action i am taking the tweets objects from the twitter stream (continuous stream without stooping it)

```<code>    class Mycontroller extends Controller {

    val tweetPerSecondActor = system.actorOf......//create actor

    def tweetAveragePerSecond = Action {
        log.debug("in the action tweetAveragePerSecond")

        def getTweet: PartialFunction[StreamingMessage, Unit] = {
          case tweet: Tweet =>
            val future = ask(tweetPerSecondActor, PerSecond(tweet))
        }
        val streaming: Future[TwitterStream] = handleTwitterStreamClient.getStreamingCLient.sampleStatuses(stall_warnings = true)(getTweet)

        Ok("tweet average per second")
      }
    }
</code>```

when i hit the route the logs show

```<code>TweetPerSecondActor INFO - Actor TweetPerSecondActor recevied the message PerSecond
16:42:44.335 28939 [ArteciateActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Cancel timer [perSecond] with generation [758]
16:42:44.335 28939 [ArteciateActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Start timer [perSecond] with generation [759]

    6:42:44.335 28939 [TwitterActorSystem-akka.actor.default-dispatcher-6] TweetPerSecondActor INFO - Actor TweetPerSecondActor recevied the message PerSecond
    16:42:44.335 28939 [TwitterActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Cancel timer [perSecond] with generation [758]
    16:42:44.335 28939 [TwitterActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Start timer [perSecond] with generation [759]
</code>```

and if i pass the dummy string values instead of running the stream and passing the twitter object the timer works fine
like below
case class PerSecond(tweet:String)
    case class TweetPerSecondCount(tweet:String)

```<code>class TweetPerSecondActor extends Actor with Timers{
var counter=0
 def receive: PartialFunction[Any, Unit] = {
    case PerSecond(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message PerSecond")
      timers.startPeriodicTimer("perSecond", TweetPerSecondCount(tweet), 5.second)

    case TweetPerSecondCount(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message TweetPerSecondCount")
      log.info("got the tweet {}",getCounter+"in 5 seconds")

    case message =>
      log.warn("Actor TweetPerSecondActor: Unhandled message received : {}", message)
      unhandled(message)
  }
}

    class Mycontroller extends Controller {

    val tweetPerSecondActor = system.actorOf......//create actor

    def tweetAveragePerSecond = Action {
        log.debug("in the action tweetAveragePerSecond")

            val future = ask(tweetPerSecondActor, PerSecond("dummy value"))

        Ok("tweet average per second")
      }
    }
</code>```

答:
Timers in Akka are keyed (in your case the key is "perSecond") and the API guarantees that

Each timer has a key and if a new timer with same key is started the previous is cancelled

So every time the getTweet function (given that it's called for effect not for value, I prefer "procedure" but that's perhaps idiosyncratic) is called, the timer will get canceled.

Depending on what you're trying to accomplish solutions could include:

Actor per request.  You'd need to have the request return something that can be passed to future requests to get information from the actor.  Actor lifecycle management will also probably be desirable as well.

Keep one actor for the whole controller but use a unique timer key per request.  If these are periodic timers, you'll have to track which timer keys are active and cancel ones which are no longer needed (keeping arbitrarily many periodic timers running is likely to eventually degrade performance)

Body:
i am using akka timer

i am using twitter streams and i am trying to get the number of tweets in 5 second
here is my code

case class PerSecond(tweet:Tweet)
case class TweetPerSecondCount(tweet:Tweet)

class TweetPerSecondActor extends Actor with Timers{
var counter=0
 def receive: PartialFunction[Any, Unit] = {
    case PerSecond(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message PerSecond")
      timers.startPeriodicTimer("perSecond", TweetPerSecondCount(tweet), 5.second)

    case TweetPerSecondCount(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message TweetPerSecondCount")
      log.info("got the tweet {}",getCounter+"in 5 seconds")

    case message =>
      log.warn("Actor TweetPerSecondActor: Unhandled message received : {}", message)
      unhandled(message)
  }
}

in play framework's controller Action i am taking the tweets objects from the twitter stream (continuous stream without stooping it)

    class Mycontroller extends Controller {

    val tweetPerSecondActor = system.actorOf......//create actor

    def tweetAveragePerSecond = Action {
        log.debug("in the action tweetAveragePerSecond")

        def getTweet: PartialFunction[StreamingMessage, Unit] = {
          case tweet: Tweet =>
            val future = ask(tweetPerSecondActor, PerSecond(tweet))
        }
        val streaming: Future[TwitterStream] = handleTwitterStreamClient.getStreamingCLient.sampleStatuses(stall_warnings = true)(getTweet)

        Ok("tweet average per second")
      }
    }

when i hit the route the logs show

TweetPerSecondActor INFO - Actor TweetPerSecondActor recevied the message PerSecond
16:42:44.335 28939 [ArteciateActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Cancel timer [perSecond] with generation [758]
16:42:44.335 28939 [ArteciateActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Start timer [perSecond] with generation [759]

    6:42:44.335 28939 [TwitterActorSystem-akka.actor.default-dispatcher-6] TweetPerSecondActor INFO - Actor TweetPerSecondActor recevied the message PerSecond
    16:42:44.335 28939 [TwitterActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Cancel timer [perSecond] with generation [758]
    16:42:44.335 28939 [TwitterActorSystem-akka.actor.default-dispatcher-5] TimerScheduler DEBUG - Start timer [perSecond] with generation [759]

and if i pass the dummy string values instead of running the stream and passing the twitter object the timer works fine
like below
case class PerSecond(tweet:String)
    case class TweetPerSecondCount(tweet:String)

class TweetPerSecondActor extends Actor with Timers{
var counter=0
 def receive: PartialFunction[Any, Unit] = {
    case PerSecond(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message PerSecond")
      timers.startPeriodicTimer("perSecond", TweetPerSecondCount(tweet), 5.second)

    case TweetPerSecondCount(tweet) =>
      log.info("Actor TweetPerSecondActor recevied the message TweetPerSecondCount")
      log.info("got the tweet {}",getCounter+"in 5 seconds")

    case message =>
      log.warn("Actor TweetPerSecondActor: Unhandled message received : {}", message)
      unhandled(message)
  }
}

    class Mycontroller extends Controller {

    val tweetPerSecondActor = system.actorOf......//create actor

    def tweetAveragePerSecond = Action {
        log.debug("in the action tweetAveragePerSecond")

            val future = ask(tweetPerSecondActor, PerSecond("dummy value"))

        Ok("tweet average per second")
      }
    }


问:
Ruby on Rails maintenance and RSpec
How are your experiences with RoR maintenance and RSpec.

Is RSpec good for real use, I mean do developers generally use it, or is it something you can live without?

How is with maintenance aspects of RoR, web hosting - is it cheap and abundant like say PHP hosting, gem dependencies and updates, changing the database model, etc.?

I'm researching couple of technologies for the next web project and RoR seems ok at a first glance, but wouldn't like to jump into something that requires a lot to maintain. Thanks.

答:
Rspec is very popular but Rails creator thinks it's not that useful since there is Test::Unit, a built-in test library: http://www.rubyinside.com/dhh-offended-by-rspec-debate-4610.html. Personnaly, I like Rspec and use it daily.

Hosting Rails is really easy:

Heroku is quick and free until you need solid configuration

On a real server, once you setup Ruby, Apache and Passenger (or Nginx or whatever), you'll just have to configure your VHosts

Deploying is dead simple thanks to Capistrano

In general, I love Rails because everything is thought to be simple to use. Basically, the dependencies built as gems are so easy to manage thanks to Bundler.

Title: Ruby on Rails maintenance and RSpec


问:
Get Current Day w.r.t timezone
The following code snippet print the day for example. Monday (or) Tuesday etc..
But on my local machine its printing as per Indian Standard time Timezone but on my server, its printing as per UTC.

```<code>import datetime
from datetime import date
current_day_name =  (date.today().strftime("%A")).lower()
print(current_day_name)
</code>```

Can someone please suggest how do i tweak this code as per a specific timezone like Indian Standard Time (or) UTC?

答:
Here is a quote from the datetime library reference:

Because the format depends on the current locale, care should be taken when making assumptions about the output value.

So datetime depends on the locale settings.  The locale reference describes a function setlocale:

Applications typically start with a call of:

```<code>import locale
locale.setlocale(locale.LC_ALL, '')
</code>```

So, first make sure you have whichever language-pack you need (e.g. sudo apt install language-pack-id) then specify the locale as described in the documentation.

As an example, on my computer I run

```<code>>>>import locale
>>>locale.getdefaultlocale()
('en_US', 'UTF-8')
>>>datetime.date.today().strftime('%A')
'Saturday'
>>> locale.setlocale(locale.LC_ALL,'hr_HR.utf8')
'hr_HR.utf8'
>>> datetime.date.today().strftime('%A')
'subota'
</code>```

It looks like you might also need to supply tzinfo to your datetime constructor (see the datetime reference).  For example:

```<code>>>> datetime.datetime.now(datetime.timezone.utc).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 01:07:16 PM , UTC,+0000'
>>> datetime.datetime.now(datetime.timezone(
    datetime.timedelta(hours=1),'CET')).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 02:07:28 PM , CET,+0100'
</code>```

Title: Get Current Day w.r.t timezone

Body:
The following code snippet print the day for example. Monday (or) Tuesday etc..
But on my local machine its printing as per Indian Standard time Timezone but on my server, its printing as per UTC.

import datetime
from datetime import date
current_day_name =  (date.today().strftime("%A")).lower()
print(current_day_name)

Can someone please suggest how do i tweak this code as per a specific timezone like Indian Standard Time (or) UTC?

Body:
Here is a quote from the datetime library reference:

Because the format depends on the current locale, care should be taken when making assumptions about the output value.

So datetime depends on the locale settings.  The locale reference describes a function setlocale:

Applications typically start with a call of:

import locale
locale.setlocale(locale.LC_ALL, '')

So, first make sure you have whichever language-pack you need (e.g. sudo apt install language-pack-id) then specify the locale as described in the documentation.

As an example, on my computer I run

>>>import locale
>>>locale.getdefaultlocale()
('en_US', 'UTF-8')
>>>datetime.date.today().strftime('%A')
'Saturday'
>>> locale.setlocale(locale.LC_ALL,'hr_HR.utf8')
'hr_HR.utf8'
>>> datetime.date.today().strftime('%A')
'subota'

It looks like you might also need to supply tzinfo to your datetime constructor (see the datetime reference).  For example:

>>> datetime.datetime.now(datetime.timezone.utc).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 01:07:16 PM , UTC,+0000'
>>> datetime.datetime.now(datetime.timezone(
    datetime.timedelta(hours=1),'CET')).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 02:07:28 PM , CET,+0100'