问:
How to add expiry time to static files in http header?
I'm trying hard to increase the page speed of my wordpress site. As suggested by google pagespeed insights, I'm trying to add expiry to images in http header for all static files like images,css and js.

This is what shown by the pagespeed insight.

I added the expiry in htaccess file in root folder of the wordpress folder. But still no expiry time added to these files. How do I solve this?

Below are the http header response returned by chrome and firefox respectively.

The .htaccess file in root folder (/opt/bitnami/apps/wordpress/htdocs):

```<code># BEGIN W3TC CDN
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
# END W3TC CDN
# BEGIN W3TC Browser Cache
<IfModule mod_mime.c>
    AddType text/css .css
    AddType text/x-component .htc
    AddType application/x-javascript .js
    AddType application/javascript .js2
    AddType text/javascript .js3
    AddType text/x-js .js4
    AddType text/html .html .htm
    AddType text/richtext .rtf .rtx
    AddType image/svg+xml .svg
    AddType text/plain .txt
    AddType text/xsd .xsd
    AddType text/xsl .xsl
    AddType text/xml .xml
    AddType video/asf .asf .asx .wax .wmv .wmx
    AddType video/avi .avi
    AddType image/bmp .bmp
    AddType application/java .class
    AddType video/divx .divx
    AddType application/msword .doc .docx
    AddType application/vnd.ms-fontobject .eot
    AddType application/x-msdownload .exe
    AddType image/gif .gif
    AddType application/x-gzip .gz .gzip
    AddType image/x-icon .ico
    AddType image/jpeg .jpg .jpeg .jpe
    AddType image/webp .webp
    AddType application/json .json
    AddType application/vnd.ms-access .mdb
    AddType audio/midi .mid .midi
    AddType video/quicktime .mov .qt
    AddType audio/mpeg .mp3 .m4a
    AddType video/mp4 .mp4 .m4v
    AddType video/mpeg .mpeg .mpg .mpe
    AddType application/vnd.ms-project .mpp
    AddType application/x-font-otf .otf
    AddType application/vnd.ms-opentype ._otf
    AddType application/vnd.oasis.opendocument.database .odb
    AddType application/vnd.oasis.opendocument.chart .odc
    AddType application/vnd.oasis.opendocument.formula .odf
    AddType application/vnd.oasis.opendocument.graphics .odg
    AddType application/vnd.oasis.opendocument.presentation .odp
    AddType application/vnd.oasis.opendocument.spreadsheet .ods
    AddType application/vnd.oasis.opendocument.text .odt
    AddType audio/ogg .ogg
    AddType application/pdf .pdf
    AddType image/png .png
    AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
    AddType audio/x-realaudio .ra .ram
    AddType image/svg+xml .svg .svgz
    AddType application/x-shockwave-flash .swf
    AddType application/x-tar .tar
    AddType image/tiff .tif .tiff
    AddType application/x-font-ttf .ttf .ttc
    AddType application/vnd.ms-opentype ._ttf
    AddType audio/wav .wav
    AddType audio/wma .wma
    AddType application/vnd.ms-write .wri
    AddType application/font-woff .woff
    AddType application/font-woff2 .woff2
    AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
    AddType application/zip .zip
</IfModule>
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css A31536000
    ExpiresByType text/x-component A31536000
    ExpiresByType application/x-javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType text/x-js A31536000
    ExpiresByType text/html A3600
    ExpiresByType text/richtext A3600
    ExpiresByType image/svg+xml A3600
    ExpiresByType text/plain A3600
    ExpiresByType text/xsd A3600
    ExpiresByType text/xsl A3600
    ExpiresByType text/xml A3600
    ExpiresByType video/asf A31536000
    ExpiresByType video/avi A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType application/java A31536000
    ExpiresByType video/divx A31536000
    ExpiresByType application/msword A31536000
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-msdownload A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType application/x-gzip A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType image/webp A31536000
    ExpiresByType application/json A31536000
    ExpiresByType application/vnd.ms-access A31536000
    ExpiresByType audio/midi A31536000
    ExpiresByType video/quicktime A31536000
    ExpiresByType audio/mpeg A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/mpeg A31536000
    ExpiresByType application/vnd.ms-project A31536000
    ExpiresByType application/x-font-otf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType application/vnd.oasis.opendocument.database A31536000
    ExpiresByType application/vnd.oasis.opendocument.chart A31536000
    ExpiresByType application/vnd.oasis.opendocument.formula A31536000
    ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
    ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
    ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
    ExpiresByType application/vnd.oasis.opendocument.text A31536000
    ExpiresByType audio/ogg A31536000
    ExpiresByType application/pdf A31536000
    ExpiresByType image/png A31536000
    ExpiresByType application/vnd.ms-powerpoint A31536000
    ExpiresByType audio/x-realaudio A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType application/x-shockwave-flash A31536000
    ExpiresByType application/x-tar A31536000
    ExpiresByType image/tiff A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType audio/wav A31536000
    ExpiresByType audio/wma A31536000
    ExpiresByType application/vnd.ms-write A31536000
    ExpiresByType application/font-woff A31536000
    ExpiresByType application/font-woff2 A31536000
    ExpiresByType application/vnd.ms-excel A31536000
    ExpiresByType application/zip A31536000
</IfModule>
<IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/bmp application/java application/msword application/vnd.ms-fontobject application/x-msdownload image/x-icon image/webp application/json application/vnd.ms-access application/vnd.ms-project application/x-font-otf application/vnd.ms-opentype application/vnd.oasis.opendocument.database application/vnd.oasis.opendocument.chart application/vnd.oasis.opendocument.formula application/vnd.oasis.opendocument.graphics application/vnd.oasis.opendocument.presentation application/vnd.oasis.opendocument.spreadsheet application/vnd.oasis.opendocument.text audio/ogg application/pdf application/vnd.ms-powerpoint image/svg+xml application/x-shockwave-flash image/tiff application/x-font-ttf application/vnd.ms-opentype audio/wav application/vnd.ms-write application/font-woff application/font-woff2 application/vnd.ms-excel
    <IfModule mod_mime.c>
        # DEFLATE by extension
        AddOutputFilter DEFLATE js css htm html xml
    </IfModule>
</IfModule>
<FilesMatch "\.(css|htc|less|js|js2|js3|js4|CSS|HTC|LESS|JS|JS2|JS3|JS4)$">
    FileETag MTime Size
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header append Cache-Control "public"
         Header set X-Powered-By "W3 Total Cache/0.9.6"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(html|htm|rtf|rtx|svg|txt|xsd|xsl|xml|HTML|HTM|RTF|RTX|SVG|TXT|XSD|XSL|XML)$">
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
        Header set Pragma "public"
        Header append Cache-Control "public"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|WEBP|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|_TTF|WAV|WMA|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW|ZIP)$">
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header append Cache-Control "max-age=84600, public"
         Header set X-Powered-By "W3 Total Cache/0.9.6"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(bmp|class|doc|docx|eot|exe|ico|webp|json|mdb|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|pot|pps|ppt|pptx|svg|svgz|swf|tif|tiff|ttf|ttc|_ttf|wav|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|BMP|CLASS|DOC|DOCX|EOT|EXE|ICO|WEBP|JSON|MDB|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|POT|PPS|PPT|PPTX|SVG|SVGZ|SWF|TIF|TIFF|TTF|TTC|_TTF|WAV|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW)$">
    <IfModule mod_headers.c>
         Header unset Last-Modified
    </IfModule>
</FilesMatch>

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css A31536000
    ExpiresByType text/x-component A31536000
    ExpiresByType application/x-javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType text/x-js A31536000
    ExpiresByType text/html A3600
    ExpiresByType text/richtext A3600
    ExpiresByType image/svg+xml A3600
    ExpiresByType text/plain A3600
    ExpiresByType text/xsd A3600
    ExpiresByType text/xsl A3600
    ExpiresByType text/xml A3600
    ExpiresByType video/asf A31536000
    ExpiresByType video/avi A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType application/java A31536000
    ExpiresByType video/divx A31536000
    ExpiresByType application/msword A31536000
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-msdownload A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType application/x-gzip A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType application/json A31536000
    ExpiresByType application/vnd.ms-access A31536000
    ExpiresByType audio/midi A31536000
    ExpiresByType video/quicktime A31536000
    ExpiresByType audio/mpeg A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/mpeg A31536000
    ExpiresByType application/vnd.ms-project A31536000
    ExpiresByType application/x-font-otf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType application/vnd.oasis.opendocument.database A31536000
    ExpiresByType application/vnd.oasis.opendocument.chart A31536000
    ExpiresByType application/vnd.oasis.opendocument.formula A31536000
    ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
    ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
    ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
    ExpiresByType application/vnd.oasis.opendocument.text A31536000
    ExpiresByType audio/ogg A31536000
    ExpiresByType application/pdf A31536000
    ExpiresByType image/png A31536000
    ExpiresByType application/vnd.ms-powerpoint A31536000
    ExpiresByType audio/x-realaudio A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType application/x-shockwave-flash A31536000
    ExpiresByType application/x-tar A31536000
    ExpiresByType image/tiff A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType audio/wav A31536000
    ExpiresByType audio/wma A31536000
    ExpiresByType application/vnd.ms-write A31536000
    ExpiresByType application/font-woff A31536000
    ExpiresByType application/font-woff2 A31536000
    ExpiresByType application/vnd.ms-excel A31536000
    ExpiresByType application/zip A31536000
</IfModule>

<IfModule mod_expires.c>
    # Enable expirations
    ExpiresActive On
    # Default directive
    ExpiresDefault "access plus 1 month"
    # My favicon
    ExpiresByType image/x-icon "access plus 1 year"
    # Images
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    # CSS
    ExpiresByType text/css "access plus 1 month"
    # Javascript
    ExpiresByType application/javascript "access plus 1 year"
</IfModule>
</code>```

答:
I solved the problem with the following steps:
First checked my apache site configuration and make sure "AllowOverride all" present like below.

```<code><Directory /var/www/mysite>
    AllowOverride all
</Directory>
</code>```

Then tried the following commands:

```<code>sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo service apache2 restart
</code>```

Body:
I'm trying hard to increase the page speed of my wordpress site. As suggested by google pagespeed insights, I'm trying to add expiry to images in http header for all static files like images,css and js.

This is what shown by the pagespeed insight.

I added the expiry in htaccess file in root folder of the wordpress folder. But still no expiry time added to these files. How do I solve this?

Below are the http header response returned by chrome and firefox respectively.

The .htaccess file in root folder (/opt/bitnami/apps/wordpress/htdocs):

# BEGIN W3TC CDN
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
# END W3TC CDN
# BEGIN W3TC Browser Cache
<IfModule mod_mime.c>
    AddType text/css .css
    AddType text/x-component .htc
    AddType application/x-javascript .js
    AddType application/javascript .js2
    AddType text/javascript .js3
    AddType text/x-js .js4
    AddType text/html .html .htm
    AddType text/richtext .rtf .rtx
    AddType image/svg+xml .svg
    AddType text/plain .txt
    AddType text/xsd .xsd
    AddType text/xsl .xsl
    AddType text/xml .xml
    AddType video/asf .asf .asx .wax .wmv .wmx
    AddType video/avi .avi
    AddType image/bmp .bmp
    AddType application/java .class
    AddType video/divx .divx
    AddType application/msword .doc .docx
    AddType application/vnd.ms-fontobject .eot
    AddType application/x-msdownload .exe
    AddType image/gif .gif
    AddType application/x-gzip .gz .gzip
    AddType image/x-icon .ico
    AddType image/jpeg .jpg .jpeg .jpe
    AddType image/webp .webp
    AddType application/json .json
    AddType application/vnd.ms-access .mdb
    AddType audio/midi .mid .midi
    AddType video/quicktime .mov .qt
    AddType audio/mpeg .mp3 .m4a
    AddType video/mp4 .mp4 .m4v
    AddType video/mpeg .mpeg .mpg .mpe
    AddType application/vnd.ms-project .mpp
    AddType application/x-font-otf .otf
    AddType application/vnd.ms-opentype ._otf
    AddType application/vnd.oasis.opendocument.database .odb
    AddType application/vnd.oasis.opendocument.chart .odc
    AddType application/vnd.oasis.opendocument.formula .odf
    AddType application/vnd.oasis.opendocument.graphics .odg
    AddType application/vnd.oasis.opendocument.presentation .odp
    AddType application/vnd.oasis.opendocument.spreadsheet .ods
    AddType application/vnd.oasis.opendocument.text .odt
    AddType audio/ogg .ogg
    AddType application/pdf .pdf
    AddType image/png .png
    AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
    AddType audio/x-realaudio .ra .ram
    AddType image/svg+xml .svg .svgz
    AddType application/x-shockwave-flash .swf
    AddType application/x-tar .tar
    AddType image/tiff .tif .tiff
    AddType application/x-font-ttf .ttf .ttc
    AddType application/vnd.ms-opentype ._ttf
    AddType audio/wav .wav
    AddType audio/wma .wma
    AddType application/vnd.ms-write .wri
    AddType application/font-woff .woff
    AddType application/font-woff2 .woff2
    AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
    AddType application/zip .zip
</IfModule>
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css A31536000
    ExpiresByType text/x-component A31536000
    ExpiresByType application/x-javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType text/x-js A31536000
    ExpiresByType text/html A3600
    ExpiresByType text/richtext A3600
    ExpiresByType image/svg+xml A3600
    ExpiresByType text/plain A3600
    ExpiresByType text/xsd A3600
    ExpiresByType text/xsl A3600
    ExpiresByType text/xml A3600
    ExpiresByType video/asf A31536000
    ExpiresByType video/avi A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType application/java A31536000
    ExpiresByType video/divx A31536000
    ExpiresByType application/msword A31536000
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-msdownload A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType application/x-gzip A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType image/webp A31536000
    ExpiresByType application/json A31536000
    ExpiresByType application/vnd.ms-access A31536000
    ExpiresByType audio/midi A31536000
    ExpiresByType video/quicktime A31536000
    ExpiresByType audio/mpeg A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/mpeg A31536000
    ExpiresByType application/vnd.ms-project A31536000
    ExpiresByType application/x-font-otf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType application/vnd.oasis.opendocument.database A31536000
    ExpiresByType application/vnd.oasis.opendocument.chart A31536000
    ExpiresByType application/vnd.oasis.opendocument.formula A31536000
    ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
    ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
    ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
    ExpiresByType application/vnd.oasis.opendocument.text A31536000
    ExpiresByType audio/ogg A31536000
    ExpiresByType application/pdf A31536000
    ExpiresByType image/png A31536000
    ExpiresByType application/vnd.ms-powerpoint A31536000
    ExpiresByType audio/x-realaudio A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType application/x-shockwave-flash A31536000
    ExpiresByType application/x-tar A31536000
    ExpiresByType image/tiff A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType audio/wav A31536000
    ExpiresByType audio/wma A31536000
    ExpiresByType application/vnd.ms-write A31536000
    ExpiresByType application/font-woff A31536000
    ExpiresByType application/font-woff2 A31536000
    ExpiresByType application/vnd.ms-excel A31536000
    ExpiresByType application/zip A31536000
</IfModule>
<IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/bmp application/java application/msword application/vnd.ms-fontobject application/x-msdownload image/x-icon image/webp application/json application/vnd.ms-access application/vnd.ms-project application/x-font-otf application/vnd.ms-opentype application/vnd.oasis.opendocument.database application/vnd.oasis.opendocument.chart application/vnd.oasis.opendocument.formula application/vnd.oasis.opendocument.graphics application/vnd.oasis.opendocument.presentation application/vnd.oasis.opendocument.spreadsheet application/vnd.oasis.opendocument.text audio/ogg application/pdf application/vnd.ms-powerpoint image/svg+xml application/x-shockwave-flash image/tiff application/x-font-ttf application/vnd.ms-opentype audio/wav application/vnd.ms-write application/font-woff application/font-woff2 application/vnd.ms-excel
    <IfModule mod_mime.c>
        # DEFLATE by extension
        AddOutputFilter DEFLATE js css htm html xml
    </IfModule>
</IfModule>
<FilesMatch "\.(css|htc|less|js|js2|js3|js4|CSS|HTC|LESS|JS|JS2|JS3|JS4)$">
    FileETag MTime Size
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header append Cache-Control "public"
         Header set X-Powered-By "W3 Total Cache/0.9.6"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(html|htm|rtf|rtx|svg|txt|xsd|xsl|xml|HTML|HTM|RTF|RTX|SVG|TXT|XSD|XSL|XML)$">
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
        Header set Pragma "public"
        Header append Cache-Control "public"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|WEBP|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|_TTF|WAV|WMA|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW|ZIP)$">
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header append Cache-Control "max-age=84600, public"
         Header set X-Powered-By "W3 Total Cache/0.9.6"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(bmp|class|doc|docx|eot|exe|ico|webp|json|mdb|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|pot|pps|ppt|pptx|svg|svgz|swf|tif|tiff|ttf|ttc|_ttf|wav|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|BMP|CLASS|DOC|DOCX|EOT|EXE|ICO|WEBP|JSON|MDB|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|POT|PPS|PPT|PPTX|SVG|SVGZ|SWF|TIF|TIFF|TTF|TTC|_TTF|WAV|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW)$">
    <IfModule mod_headers.c>
         Header unset Last-Modified
    </IfModule>
</FilesMatch>

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css A31536000
    ExpiresByType text/x-component A31536000
    ExpiresByType application/x-javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType text/x-js A31536000
    ExpiresByType text/html A3600
    ExpiresByType text/richtext A3600
    ExpiresByType image/svg+xml A3600
    ExpiresByType text/plain A3600
    ExpiresByType text/xsd A3600
    ExpiresByType text/xsl A3600
    ExpiresByType text/xml A3600
    ExpiresByType video/asf A31536000
    ExpiresByType video/avi A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType application/java A31536000
    ExpiresByType video/divx A31536000
    ExpiresByType application/msword A31536000
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-msdownload A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType application/x-gzip A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType application/json A31536000
    ExpiresByType application/vnd.ms-access A31536000
    ExpiresByType audio/midi A31536000
    ExpiresByType video/quicktime A31536000
    ExpiresByType audio/mpeg A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/mpeg A31536000
    ExpiresByType application/vnd.ms-project A31536000
    ExpiresByType application/x-font-otf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType application/vnd.oasis.opendocument.database A31536000
    ExpiresByType application/vnd.oasis.opendocument.chart A31536000
    ExpiresByType application/vnd.oasis.opendocument.formula A31536000
    ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
    ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
    ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
    ExpiresByType application/vnd.oasis.opendocument.text A31536000
    ExpiresByType audio/ogg A31536000
    ExpiresByType application/pdf A31536000
    ExpiresByType image/png A31536000
    ExpiresByType application/vnd.ms-powerpoint A31536000
    ExpiresByType audio/x-realaudio A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType application/x-shockwave-flash A31536000
    ExpiresByType application/x-tar A31536000
    ExpiresByType image/tiff A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType audio/wav A31536000
    ExpiresByType audio/wma A31536000
    ExpiresByType application/vnd.ms-write A31536000
    ExpiresByType application/font-woff A31536000
    ExpiresByType application/font-woff2 A31536000
    ExpiresByType application/vnd.ms-excel A31536000
    ExpiresByType application/zip A31536000
</IfModule>

<IfModule mod_expires.c>
    # Enable expirations
    ExpiresActive On
    # Default directive
    ExpiresDefault "access plus 1 month"
    # My favicon
    ExpiresByType image/x-icon "access plus 1 year"
    # Images
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    # CSS
    ExpiresByType text/css "access plus 1 month"
    # Javascript
    ExpiresByType application/javascript "access plus 1 year"
</IfModule>

Body:
I solved the problem with the following steps:
First checked my apache site configuration and make sure "AllowOverride all" present like below.

<Directory /var/www/mysite>
    AllowOverride all
</Directory>

Then tried the following commands:

sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo service apache2 restart


来源: stackexchange

问:
Unzip 7z archive with password using bash script
I want to unzip a folder with multiple *.7z archives, all with same password.

Unfortunately, using this:

```<code>    #!/bin/bash
    password="12345678"
    cd /server/disc/folders.../folderWithArchives
    for package in ./*.7z;
    do
    7z -x -P{$password} $package
    done
</code>```

gives me

Error:
Incorrect command line

Have you any ideas how to fix it?

I've tried shellcheck and it gave me this:

```<code>#!/bin/bash
password="12345678"
cd /server/disc/folders.../folderWithArchives || exit
for package in ./*.7z;
do
7z -x -P$password "$package"
done
</code>```

but it still doesn't work

OS: Ubuntu 16.04.6 LTS

shell:  GNU bash, version 4.3.48

答:
I found a solution.
Everything works OK after only deleting '-' before 'x'.
Now it works and looks like this:</p>

```<code>#!/bin/bash
password="12345678"
cd /server/disc/folders.../folderWithArchives || exit
for package in ./*.7z;
do
7z x -P$password "$package"
done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to unzip a folder with multiple *.7z archives, all with same password.

Unfortunately, using this:

    #!/bin/bash
    password="12345678"
    cd /server/disc/folders.../folderWithArchives
    for package in ./*.7z;
    do
    7z -x -P{$password} $package
    done

gives me

Error:
Incorrect command line

Have you any ideas how to fix it?

I've tried shellcheck and it gave me this:

#!/bin/bash
password="12345678"
cd /server/disc/folders.../folderWithArchives || exit
for package in ./*.7z;
do
7z -x -P$password "$package"
done

but it still doesn't work

OS: Ubuntu 16.04.6 LTS

shell:  GNU bash, version 4.3.48

Body:
I found a solution.
Everything works OK after only deleting '-' before 'x'.
Now it works and looks like this:

#!/bin/bash
password="12345678"
cd /server/disc/folders.../folderWithArchives || exit
for package in ./*.7z;
do
7z x -P$password "$package"
done


问:
Unregistering BroadcastReceiver registered in Activity context results in IllegalArgumentException crash
The crash is pretty strange one.

In onStart, BroadcastReceiver that is stored in the Activity field is registered. In onStop, this BroadcastReceiver is unregistered. When BroadcastReceiver was successfully registered, I also set isRegistered field to true, and before I unregister the receiver, I check this field to see if we need

However, in Crashlytics I see that sometimes this fails, and the whole app crashes with IllegalArgumentException with Receiver not registered message, which originates from android.app.LoadedApk#forgetReceiverDispatcher. Which is pretty strange, considering that I check the flag, right?

After I looked into ContextImpl and LoadedApk classes which handle registration/unregistration and added some reflection-based diagnostics, it got even more mysterious. In short, on every crash like that I will extract the map of existing Context to BroadcastReceiver (see ContextImpl.java:1590 and LoadedApk.java:1361).

When it unregisters normally, without a crash I can see a map like this:

```<code>com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
com.mypackage.myapp.MyActivity1 instance -> list of instances that are registered for Activity1
com.mypackage.myapp.MyActivity2 instance -> list of instances that are registered for Activity2
...
</code>```

However, in the event of the crash this map looks like this:

```<code>com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
</code>```

i.e. there are no activities in which my BroadcastReceiver is registered, even though I never called unregisterReceiver!

It only happens in one specific activity, so my first guess was that this activity is leaked somehow, onDestroy lifecycle gets called, Activity entry get removed from receivers map, and then obviously the receiver won't be there when we try to unregister it. However, if that's the case, why is onStop being called after onDestroy then? And why then the receivers list is completely empty?

And if it's not the leak, then what can lead to such puzzling behaviour? I truly hope that somebody else has experienced such a strange occurrence, and may be able to help me, because right now I'm all out of ideas.

答:
Do you at any point read or write isRegistered to/from a different thread than the main application thread, for instance in a callback that is not executed by the main application thread? If so, due to possible memory consistency bugs, this may cause stale values to be read and other strange behaviour. There can be very weird behaviour if memory consistency is broken, see for instance http://jcip.net/ and http://jcip.net/listings/Holder.java . Also, do you register the BroadcastReceiver in the main application thread?

Have you tried checking the lifecycle in various ways to see if you could reproduce the bug yourself, such as turning the phone side-ways and causing lifecycle changes that way, or otherwise force lifecycle to change?

Do you set isRegistered to false after calling unregisterReceiver? I wonder whether this could be relevant, for instance if onStart is called, registration is successful, later onStop is called, un-registration is successful, later onStart is called but registration is not successful, and then onStop is called despite no BroadcastReceiver being registered due to isRegistered not having been reset. I don't know whether this is possible, but you describe "When BroadcastReceiver was successfully registered", so I wonder if there could be an issue reg. handling of unsuccessful registration. I also wonder whether this could happen if not all branches in your onStart registers the broadcast receiver.

I could guess that the following link might be relevant, but you already use a variable to check whether it has been registered or not, so I would guess not: https://developer.android.com/topic/libraries/architecture/lifecycle (though, I am uncertain whether I like or trust the wording in that text, the example it uses includes a callback).

Moreover, there's no guarantee that the component starts before the activity or fragment is stopped. This is especially true if we need to perform a long-running operation, such as some configuration check in onStart(). This can cause a race condition where the onStop() method finishes before the onStart(), keeping the component alive longer than it's needed.

Body:
The crash is pretty strange one.

In onStart, BroadcastReceiver that is stored in the Activity field is registered. In onStop, this BroadcastReceiver is unregistered. When BroadcastReceiver was successfully registered, I also set isRegistered field to true, and before I unregister the receiver, I check this field to see if we need

However, in Crashlytics I see that sometimes this fails, and the whole app crashes with IllegalArgumentException with Receiver not registered message, which originates from android.app.LoadedApk#forgetReceiverDispatcher. Which is pretty strange, considering that I check the flag, right?

After I looked into ContextImpl and LoadedApk classes which handle registration/unregistration and added some reflection-based diagnostics, it got even more mysterious. In short, on every crash like that I will extract the map of existing Context to BroadcastReceiver (see ContextImpl.java:1590 and LoadedApk.java:1361).

When it unregisters normally, without a crash I can see a map like this:

com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
com.mypackage.myapp.MyActivity1 instance -> list of instances that are registered for Activity1
com.mypackage.myapp.MyActivity2 instance -> list of instances that are registered for Activity2
...

However, in the event of the crash this map looks like this:

com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide

i.e. there are no activities in which my BroadcastReceiver is registered, even though I never called unregisterReceiver!

It only happens in one specific activity, so my first guess was that this activity is leaked somehow, onDestroy lifecycle gets called, Activity entry get removed from receivers map, and then obviously the receiver won't be there when we try to unregister it. However, if that's the case, why is onStop being called after onDestroy then? And why then the receivers list is completely empty?

And if it's not the leak, then what can lead to such puzzling behaviour? I truly hope that somebody else has experienced such a strange occurrence, and may be able to help me, because right now I'm all out of ideas.


问:
ArrayField of DateTimeField raises "django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to timestamp with time zone[]"
I am building an app in Django.

I created a new (still empty) model having an ArrayField of DateTimeField, defined as follow:

```<code>Record_time_values = ArrayField(models.DateTimeField(), blank=False, null=False)
</code>```

As I run

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

I get

django.db.utils.ProgrammingError: cannot cast type timestamp with time
  zone to timestamp with time zone[] LINE 1: ...estamp with time zone[]
  USING "Record_time_values"::timestam...

I did a little research and this is the thread that gets closest to my issue, but I don't want to go deep using SQL to fix the problem.

Does not it exist a clean way to fix the problem via pure python / Django?

In alternative, does exist a good way to store an array of DateTimeField inside a model, bypassing the arrayfield?

Complete Traceback:

```<code>(met5) C:\Users\Tommaso\Django rest framework\Udemy Django\aqi_luftdaten>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, pm_lookup, sessions
Running migrations:
  Applying pm_lookup.0003_auto_20200602_1142...Traceback (most recent call last):
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.CannotCoerce: cannot cast type timestamp with time zone to timestamp with time zone[]
LINE 1: ...estamp with time zone[] USING "Record_time_values"::timestam...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle
    fake_initial=fake_initial,
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\base\schema.py", line 535, in alter_field
    old_db_params, new_db_params, strict)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\postgresql\schema.py", line 124, in _alter_field
    new_db_params, strict,
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\base\schema.py", line 685, in _alter_field
    params,
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\base\schema.py", line 137, in execute
    cursor.execute(sql, params)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 99, in execute
    return super().execute(sql, params)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to timestamp with time zone[]
LINE 1: ...estamp with time zone[] USING "Record_time_values"::timestam...
</code>```

答:
Ok, reproduced. This happens when you alter a column to an array from a normal datetimefield. If you just create the field as an array field with datetimefield, then the problem does not occur.

Since the table is still empty, you should do some migration maintenance and instead of creating the field and then altering it, create it the right way. This may involve rolling back one or more migrations, that may destroy data in other tables. If that's a problem, then you should backup those tables before doing this. See Reversing migrations for details.

Body:
I am building an app in Django.

I created a new (still empty) model having an ArrayField of DateTimeField, defined as follow:

Record_time_values = ArrayField(models.DateTimeField(), blank=False, null=False)

As I run

python manage.py makemigrations
python manage.py migrate

I get

django.db.utils.ProgrammingError: cannot cast type timestamp with time
  zone to timestamp with time zone[] LINE 1: ...estamp with time zone[]
  USING "Record_time_values"::timestam...

I did a little research and this is the thread that gets closest to my issue, but I don't want to go deep using SQL to fix the problem.

Does not it exist a clean way to fix the problem via pure python / Django?

In alternative, does exist a good way to store an array of DateTimeField inside a model, bypassing the arrayfield?

Complete Traceback:

(met5) C:\Users\Tommaso\Django rest framework\Udemy Django\aqi_luftdaten>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, pm_lookup, sessions
Running migrations:
  Applying pm_lookup.0003_auto_20200602_1142...Traceback (most recent call last):
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.CannotCoerce: cannot cast type timestamp with time zone to timestamp with time zone[]
LINE 1: ...estamp with time zone[] USING "Record_time_values"::timestam...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle
    fake_initial=fake_initial,
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\base\schema.py", line 535, in alter_field
    old_db_params, new_db_params, strict)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\postgresql\schema.py", line 124, in _alter_field
    new_db_params, strict,
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\base\schema.py", line 685, in _alter_field
    params,
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\base\schema.py", line 137, in execute
    cursor.execute(sql, params)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 99, in execute
    return super().execute(sql, params)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to timestamp with time zone[]
LINE 1: ...estamp with time zone[] USING "Record_time_values"::timestam...


问:
Project created using JHipster is available to everyone?
Hello folks i am newbie i wanted to know suppose i am creating a web application using JHipster. Will my code available to everyone?.
I mean will the code be submitted to open source community?</p>

答:
The generated code belongs to you, it's not shared.

Now, if you're afraid of your code leaking out because you're working  in a highly secured domain (e.g. Finance), it's another story.

The generator is open source so you can audit what it does.

But it would be simpler to configure your firewall so that it blocks outgoing traffic while still allowing incoming traffic. Generator should require only getting artifacts from public repositories (npm, maven) during generation phase.

It's like using a compiler, how do you know that it does not upload your source code somewhere? Either you audit the compiler code or you protect yourself with a firewall specifically configured each time you use it.

Finally, you should evaluate the risk of leaking generated code which has usually little value in comparison with the code that you manual add which is where business value is.


问:
Add-Content With Condition On One Line
I'm trying to get all of this to be on one line, but everything I try doesn't work.  I tried `b but that doesn't backspace you to the line above.  I tried putting the condition inline with the first Add-Content, but that didn't work either.</p>

```<code>Add-Content $txtpath "p: $strPhone x $strXTEN  |  "
if ($strMobile -ne $null) { Add-Content $txtpath "`m: strMobile  |  " }
Add-Content $txtpath "$strFax"
</code>```

答:
It looks like Microsoft listened and added the -NoNewLine Parameter to Add-Content back in 2015:

https://devblogs.microsoft.com/scripting/the-powershell-5-nonewline-parameter/

ContentLicense: CC BY-SA 3.0

Title: Add-Content With Condition On One Line

Body:
I'm trying to get all of this to be on one line, but everything I try doesn't work.  I tried `b but that doesn't backspace you to the line above.  I tried putting the condition inline with the first Add-Content, but that didn't work either.

Add-Content $txtpath "p: $strPhone x $strXTEN  |  "
if ($strMobile -ne $null) { Add-Content $txtpath "`m: strMobile  |  " }
Add-Content $txtpath "$strFax"


问:
Algorithm of checking if the number is prime
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

```<code>bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}
</code>```

Thanks in advance

答: A number that is not prime will be divisible by at least one prime number. Hence a way to speed up the algorithm (at the cost of memory) would be to store a list of the prime numbers you have already encountered, and only check whether any of these divide the number you are currently checking in each iteration.</p>

Body:
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}

Thanks in advance


问:
Can an  contain a  in HTML5?
I have a structure which is as follows:

```<code><a href="#">
  <footer>
    <p>Some text</p>
    <h2>A Heading</h2>
  </footer>
</a>
</code>```

This works and displays as expected in all browsers (even IE6 with the HTML5shiv.js) except Firefox 3.6. In Firefox 3.6 the display is completely screwed and if you use Firebug to inspect the DOM, the  element is empty and the elements which should be inside it are outside of it.

All the tags are closed correctly. The  is set to display:block in the CSS.

The W3C validator validates the document and does not mark this structure as incorrect.

The spec states that an  element may be classed as flow content when it contains other flow content. The  is flow content.

Is it just that Firefox 3.6 doesn't render HTML entirely correctly?

Any ideas for a fix?

Ta!

答:
Firefox 3.6 doesn't implement the HTML5 parsing algorithm; it has an HTML4 "parser", basically.

I think your workaround options are:

Avoid "block level" HTML tags inside the footer.

Put a  as a child of  wrapping the .

Put a
 as a child of  wrapping the .

Title: Can an <a> contain a <footer> in HTML5?

Body:
I have a structure which is as follows:

Some text

A Heading

This works and displays as expected in all browsers (even IE6 with the HTML5shiv.js) except Firefox 3.6. In Firefox 3.6 the display is completely screwed and if you use Firebug to inspect the DOM, the  element is empty and the elements which should be inside it are outside of it.

All the tags are closed correctly. The  is set to display:block in the CSS.

The W3C validator validates the document and does not mark this structure as incorrect.

The spec states that an  element may be classed as flow content when it contains other flow content. The  is flow content.

Is it just that Firefox 3.6 doesn't render HTML entirely correctly?

Any ideas for a fix?

Ta!

Body:
Firefox 3.6 doesn't implement the HTML5 parsing algorithm; it has an HTML4 "parser", basically.

I think your workaround options are:

Avoid "block level" HTML tags inside the footer.

Put a <span> as a child of <a> wrapping the <footer>.

Put a <div> as a child of <a> wrapping the <footer>.


问:
Vue: how to display multiple global router-view
I'm trying to set up multiple router-view to show login modal and i don't want to use nested routes because this modal should be reachable from any ware I'm my app and it should not change currently viewed component.
How to do that?

app.vue

```<code>  <v-app>
    <v-app-bar app color="white" height="auto">
      <div style="width:100%" class="d-flex d-md-block">
        <v-row>
          <v-col cols="9" sm="10" md="12" class=" pa-0 order-md-1 order-2">
            <AppHeader />
          </v-col>
          <v-col
            cols="3"
            sm="2"
            md="12"
            class="pa-0 order-md-2 order-1 d-flex align-center"
          >
            <Menu />
          </v-col>
        </v-row>
      </div>
    </v-app-bar>
    <router-view class="content__holder" />
    <router-view name="modal" />
    <MpFooter />
  </v-app>
</template>

<script>
import AppHeader from "./components/AppHeader";
import Menu from "./components/menu.vue";
import MpFooter from "./components/MpFooter";

export default {
  name: "App",

  components: {
    Menu,
    AppHeader,
    MpFooter,
  },
  data: () => ({
    //
  }),
};
</script>```
```

答: If it should be accessible from anywhere in the app you might consider using Vuex. This way you can have one <Modal /> instance in your app.vue and manipulate the modal-state from anywhere through Vuex

Body:
I'm trying to set up multiple router-view to show login modal and i don't want to use nested routes because this modal should be reachable from any ware I'm my app and it should not change currently viewed component.
How to do that?

app.vue

  <v-app>
    <v-app-bar app color="white" height="auto">

        <v-row>
          <v-col cols="9" sm="10" md="12" class=" pa-0 order-md-1 order-2">
            <AppHeader />
          </v-col>
          <v-col
            cols="3"
            sm="2"
            md="12"
            class="pa-0 order-md-2 order-1 d-flex align-center"
          >
            <Menu />
          </v-col>
        </v-row>

    </v-app-bar>
    <router-view class="content__holder" />
    <router-view name="modal" />
    <MpFooter />
  </v-app>
</template>

```


问:
Android WebView skip deeplinks
I'm building an app that must perform a registration inside a WebView. However, when I try to open the website URL inside the WebView, it tries to open a deeplink starting with market://. But I cannot let it happen and the registration must be done inside my WebView.

Is there anything I can do to prevent the deeplinks?

答:
You could try overriding shouldOverrideUrlLoading:

```<code>webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view,
                WebResourceRequest request) {
        val url = request.getUrl()
        if (url.startsWith("market")) {
            // Do something?
            return true
        }
        return false
    }
})
</code>```

And return true when the current load has to be cancelled and false otherwise.

Title: Android WebView skip deeplinks

Body:
You could try overriding shouldOverrideUrlLoading:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view,
                WebResourceRequest request) {
        val url = request.getUrl()
        if (url.startsWith("market")) {
            // Do something?
            return true
        }
        return false
    }
})

And return true when the current load has to be cancelled and false otherwise.


问:
Django message is not working properly using succes message mixin
hi am trying to show message after successful booking but it's not working

this is my views.py

```<code>class booking_confirm(CreateView, SuccessMessageMixin, LoginRequiredMixin):
    form_class = booking_form1
    model = Booking
    template_name = "confirm_booking1.html"
    success_message = "booking was created successfully"
    success_url = reverse_lazy("Driver:Driverview")

    def form_valid(self, form, *args, **kwargs):
        booking = get_object_or_404(Loader_post, pk=self.kwargs.get('pk'))
        print(form.cleaned_data)
        bk = form.save(commit=False)
        bk.user = self.request.user
        bk.post = booking
        bk.approve = True
        bk.save()
        return super().form_valid(form)
</code>```

this is my html code

```<code>{% if messages %}
<ul class="messages">
    {% for message in messages %}
        <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
 </ul>
{% endif %}
</code>```

答:
views.py

```<code>class booking_confirm(CreateView, SuccessMessageMixin, LoginRequiredMixin):
form_class = booking_form1
model = Booking
template_name = "confirm_booking1.html"
messages.info(request,"booking was created successfully")

success_url = reverse_lazy("Driver:Driverview")
</code>```

html

```<code>{% if messages %}
<ul>
{% for message in messages %}
    <li class="{{ message.tags }}">{{ message }}</li>
{% endfor %}
 </ul>
{% endif %}
</code>```

Body:
hi am trying to show message after successful booking but it's not working

this is my views.py

class booking_confirm(CreateView, SuccessMessageMixin, LoginRequiredMixin):
    form_class = booking_form1
    model = Booking
    template_name = "confirm_booking1.html"
    success_message = "booking was created successfully"
    success_url = reverse_lazy("Driver:Driverview")

    def form_valid(self, form, *args, **kwargs):
        booking = get_object_or_404(Loader_post, pk=self.kwargs.get('pk'))
        print(form.cleaned_data)
        bk = form.save(commit=False)
        bk.user = self.request.user
        bk.post = booking
        bk.approve = True
        bk.save()
        return super().form_valid(form)

this is my html code

{% if messages %}

    {% for message in messages %}

{{ message }}

    {% endfor %}

{% endif %}

Body:
views.py

class booking_confirm(CreateView, SuccessMessageMixin, LoginRequiredMixin):
form_class = booking_form1
model = Booking
template_name = "confirm_booking1.html"
messages.info(request,"booking was created successfully")

success_url = reverse_lazy("Driver:Driverview")

html

{% if messages %}
<ul>
{% for message in messages %}
    <li class="{{ message.tags }}">{{ message }}</li>
{% endfor %}
 </ul>
{% endif %}


问:
Allowed Menustrip only one child at moment
How can i allow only one window at a time when i click menu in menustrip ?

Ex: i have Menustrip Ordre, Tarif, etc... when i click Ordre for the first time it will open a new form, but for the second time i want to disallow it.

```<code> private void ordresToolStripMenuItem_Click(object sender, EventArgs e)
    {

        if (Already open)
        {

        }
        else
        {
            Lordre newMDIChild = new Lordre(ClientId);
            // Set the Parent Form of the Child window.
            newMDIChild.MdiParent = this;
            // Display the new form.
            newMDIChild.Show();
        }

    }
</code>```

Thanks you in advance

答:
The way I do it is by first storing the screen in a variable in a class like so:

```<code>private Lordre _LordreChildForm = new Lordre(ClientID)
</code>```

Then make a property for it like so:

```<code>public Lordre LordreChildForm { get => _LordreChildForm; set => _LordreChildForm =
value; }
</code>```

Then on the form's Form Closing event set the value to null like so:

```<code>private void Lordre_FormClosing(object sender, FormClosingEventArgs e)
{
            ClassName.LordreChildForm= null;
}
</code>```

Now Finally you can set an if statement in the button click event handler like so:

```<code>private void LordreToolStripMenuItem_Click(object sender, EventArgs e)

{
    if(ClassName.LordreChildForm== null || ClassName.LordreChildForm.IsDisposed)
    {
        ClassName.LordreChildForm= new DeregisterClub();
        ClassName.LordreChildForm.MdiParent = this;
    }
    LordreChildForm.Dock = DockStyle.Fill;
    LordreChildForm.Show();
    LordreChildForm.Focus();
}

</code>```

Body:
How can i allow only one window at a time when i click menu in menustrip ?

Ex: i have Menustrip Ordre, Tarif, etc... when i click Ordre for the first time it will open a new form, but for the second time i want to disallow it.

 private void ordresToolStripMenuItem_Click(object sender, EventArgs e)
    {

        if (Already open)
        {

        }
        else
        {
            Lordre newMDIChild = new Lordre(ClientId);
            // Set the Parent Form of the Child window.
            newMDIChild.MdiParent = this;
            // Display the new form.
            newMDIChild.Show();
        }

    }

Thanks you in advance

Body:
The way I do it is by first storing the screen in a variable in a class like so:

private Lordre _LordreChildForm = new Lordre(ClientID)

Then make a property for it like so:

public Lordre LordreChildForm { get => _LordreChildForm; set => _LordreChildForm =
value; }

Then on the form's Form Closing event set the value to null like so:

private void Lordre_FormClosing(object sender, FormClosingEventArgs e)
{
            ClassName.LordreChildForm= null;
}

Now Finally you can set an if statement in the button click event handler like so:

private void LordreToolStripMenuItem_Click(object sender, EventArgs e)

{
    if(ClassName.LordreChildForm== null || ClassName.LordreChildForm.IsDisposed)
    {
        ClassName.LordreChildForm= new DeregisterClub();
        ClassName.LordreChildForm.MdiParent = this;
    }
    LordreChildForm.Dock = DockStyle.Fill;
    LordreChildForm.Show();
    LordreChildForm.Focus();
}


问:
problem with "title" in UINavigationController
I am having a problem with title and UINavigationController. I am using the following code at UIViewControllerCurrent and when I get back from NextViewController, the title of the NavBar is still "Previous" ..Can anyone kindly help me out with this problem ? Thanks.</p>

```<code>[self setTitle:@"Previous"];
NextViewController *controller = [[NextViewController alloc] init];
[[self navigationController] pushViewController:controller animated:YES];
[controller release], controller = nil;

- (void)viewWillAppear:(BOOL)animated; {
[self setTitle:@"Real Title"];
[super viewWillAppear:animated]; }
</code>```

答:
Try using UINavigationController delegate methods below.

```<code>- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
</code>```

Use one of the delegate method to change title.

Body:
I am having a problem with title and UINavigationController. I am using the following code at UIViewControllerCurrent and when I get back from NextViewController, the title of the NavBar is still "Previous" ..Can anyone kindly help me out with this problem ? Thanks.

[self setTitle:@"Previous"];
NextViewController *controller = [[NextViewController alloc] init];
[[self navigationController] pushViewController:controller animated:YES];
[controller release], controller = nil;

- (void)viewWillAppear:(BOOL)animated; {
[self setTitle:@"Real Title"];
[super viewWillAppear:animated]; }

Body:
Try using UINavigationController delegate methods below.

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

Use one of the delegate method to change title.


问:
Prevent FlatList re-rendering causing performance problems
I'm building a React Native App using Hooks and ES6.

The Home screen fetches some data from API and display it as image galleries.
The Home screen is the parent component which includes a slideshow gallery and a Flatlist as children.

1) Slideshow - image gallery autoplay that run some operations (fetching URL in case user clicks on them) on each image iteration (every 3 secs) - This causes the re-render on the entire parent components and its children but it renders every 3 secs as supposed

2) Flatlist - just a simple Flatlist that takes an array of images - this should only rendered once when the parent component is initially loaded first

The problem

Every 3 seconds a new image is displayed in the slideshow, a function runs to fetch some props for the image displayed, the parent component is re-rendered but there is no need for Flatlist in the second gallery to run again since the array of images is the same as initially loaded (not changed)

This is my Parent code

```<code>const getTopTenMovies = (state) => state.moviescreen.popularmovies    //fetching data from Redux
const upcomingMovies = (state) => state.moviescreen.upcomingmovies

const MoviesScreen = (props) => {
  const topTenMovies = useSelector(getTopTenMovies);
  const [imageIndex, setImageIndex] = useState("");

  /* useEffect below runs every time imageIndex changes (a new image is displayed every 3 secs) */
  useEffect(() => {
      setCarouselMovieId(selectedImageItem.id);
      setCarouselMovieTitle(selectedImageItem.title);
  }, [imageIndex]);

  /* user clicks on an image and is taken to another screen
  const fetchMovieHandler = async (movieId, movieTitle) => {
      props.navigation.navigate({
        routeName: "MovieDetail",
        params: {
          assetId: movieId,
          assetName: movieTitle,
        },
      });
  };

  return (
    <ImageGallery
      data={topTenMovies}
      currentImage=setImageIndex(index)
      ...
    />

    <View style={styles.containerRow}>
          <FlatList
            horizontal={true}
            data={upcomingMovies}
            initialNumToRender={5}
            windowSize={10}
            removeClippedSubviews={true}
            keyExtractor={(item) => item.id.toString()}
            renderItem={(itemData) => (
              <HomeItem
                id={itemData.item.id}
                poster={itemData.item.poster_path}
                onAssetSelection={fetchMovieHandler}
              />
            )}
          />
        </View>
      </View>
  )
}
</code>```

The  component renders the individual images within the Flatlist and passes the parameters (movieId, movieTitle) to the fetchMovieHandler function.

HomeItem code below...

```<code>class HomeItem extends React.PureComponent {
  render() {
    const assetHandler = async () => {
      this.props.onAssetSelection(this.props.id, this.props.title);
    };
    console.log("HomeItem is called");
    return (
      <TouchableOpacity onPress={assetHandler}>
          <View>
              <Image
                key={this.props.id}
                source={{
                  uri: `https://*******${this.props.poster}`,
                }}
              />
          </View>
      </TouchableOpacity>
    );
  }
}

export default React.memo(HomeItem);
</code>```

Every 3 seconds the HomeItem is called and I see 10 log entries (one for each image and render - upcomingMovies has 10 images). From the UI everything looks fines since the images dont seems to change probably because I've defined the HomeItem as PureComponent and using React.memo(HomeItem) but it is causing performance issues since I'm getting the following error:

VirtualizedList: You have a large list that is slow to update - make sure your renderItem function renders components that follow React performance best practices like PureComponent, shouldComponentUpdate, etc

I tried to include the Flatlist inside the HomeItem component but the problem persists.

答:
Following further research and thanks to @landorid suggestion I figured out that I need control the renderItem of the FlatList by declaring it in a separate function with a useCallback hook and dependency on my data source.

Tried to include Flatlist in a separate PureComponent my the re-rendering kept happening.

The ideal solution is to change this code

```<code>renderItem={(itemData) => (
  <HomeItem
     id={itemData.item.id}
     poster={itemData.item.poster_path}
     onAssetSelection={fetchMovieHandler}
  />
)}
</code>```

to something like this

```<code>.....
  const renderRow = ({ itemData }) => {
    return (
      <HomeItem
        id={itemData.item.id}
        poster={itemData.item.poster_path}
        title={itemData.item.title}
        onAssetSelection={fetchMovieHandler}
      />
    );
  };
  keyExtractor = (item) => item.id.toString();

  return (

<FlatList
     horizontal={true}
     data={upcomingMovies}
     initialNumToRender={5}
     windowSize={10}
     removeClippedSubviews={true}
     keyExtractor={keyExtractor}
     renderItem={renderRow}
 />
</code>```

and then wrapping the renderRow() function in a useCallback hook.

The problem is that my data source data={upcomingMovies} is an array of objects with 2 levels and I need to use itemData.item.title to retrieve the title value for example.

While it works in my current renderItem settings it won't work when I use it in an external function as in

```<code>  const renderRow = ({ itemData }) => {
    return (
      <HomeItem
        id={itemData.item.id}
        poster={itemData.item.poster_path}
        title={itemData.item.title}
        onAssetSelection={fetchMovieHandler}
      />
    );
  };
</code>```

I simply get, "item" variable not available

Any suggestion on how to modify the function?

Body:
I'm building a React Native App using Hooks and ES6.

The Home screen fetches some data from API and display it as image galleries.
The Home screen is the parent component which includes a slideshow gallery and a Flatlist as children.

1) Slideshow - image gallery autoplay that run some operations (fetching URL in case user clicks on them) on each image iteration (every 3 secs) - This causes the re-render on the entire parent components and its children but it renders every 3 secs as supposed

2) Flatlist - just a simple Flatlist that takes an array of images - this should only rendered once when the parent component is initially loaded first

The problem

Every 3 seconds a new image is displayed in the slideshow, a function runs to fetch some props for the image displayed, the parent component is re-rendered but there is no need for Flatlist in the second gallery to run again since the array of images is the same as initially loaded (not changed)

This is my Parent code

const getTopTenMovies = (state) => state.moviescreen.popularmovies    //fetching data from Redux
const upcomingMovies = (state) => state.moviescreen.upcomingmovies

const MoviesScreen = (props) => {
  const topTenMovies = useSelector(getTopTenMovies);
  const [imageIndex, setImageIndex] = useState("");

  /* useEffect below runs every time imageIndex changes (a new image is displayed every 3 secs) */
  useEffect(() => {
      setCarouselMovieId(selectedImageItem.id);
      setCarouselMovieTitle(selectedImageItem.title);
  }, [imageIndex]);

  /* user clicks on an image and is taken to another screen
  const fetchMovieHandler = async (movieId, movieTitle) => {
      props.navigation.navigate({
        routeName: "MovieDetail",
        params: {
          assetId: movieId,
          assetName: movieTitle,
        },
      });
  };

  return (
    <ImageGallery
      data={topTenMovies}
      currentImage=setImageIndex(index)
      ...
    />

    <View style={styles.containerRow}>
          <FlatList
            horizontal={true}
            data={upcomingMovies}
            initialNumToRender={5}
            windowSize={10}
            removeClippedSubviews={true}
            keyExtractor={(item) => item.id.toString()}
            renderItem={(itemData) => (
              <HomeItem
                id={itemData.item.id}
                poster={itemData.item.poster_path}
                onAssetSelection={fetchMovieHandler}
              />
            )}
          />
        </View>
      </View>
  )
}

The  component renders the individual images within the Flatlist and passes the parameters (movieId, movieTitle) to the fetchMovieHandler function.

HomeItem code below...

class HomeItem extends React.PureComponent {
  render() {
    const assetHandler = async () => {
      this.props.onAssetSelection(this.props.id, this.props.title);
    };
    console.log("HomeItem is called");
    return (
      <TouchableOpacity onPress={assetHandler}>
          <View>
              <Image
                key={this.props.id}
                source={{
                  uri: `https://*******${this.props.poster}`,
                }}
              />
          </View>
      </TouchableOpacity>
    );
  }
}

export default React.memo(HomeItem);

Every 3 seconds the HomeItem is called and I see 10 log entries (one for each image and render - upcomingMovies has 10 images). From the UI everything looks fines since the images dont seems to change probably because I've defined the HomeItem as PureComponent and using React.memo(HomeItem) but it is causing performance issues since I'm getting the following error:

VirtualizedList: You have a large list that is slow to update - make sure your renderItem function renders components that follow React performance best practices like PureComponent, shouldComponentUpdate, etc

I tried to include the Flatlist inside the HomeItem component but the problem persists.

Body:
Following further research and thanks to @landorid suggestion I figured out that I need control the renderItem of the FlatList by declaring it in a separate function with a useCallback hook and dependency on my data source.

Tried to include Flatlist in a separate PureComponent my the re-rendering kept happening.

The ideal solution is to change this code

renderItem={(itemData) => (
  <HomeItem
     id={itemData.item.id}
     poster={itemData.item.poster_path}
     onAssetSelection={fetchMovieHandler}
  />
)}

to something like this

.....
  const renderRow = ({ itemData }) => {
    return (
      <HomeItem
        id={itemData.item.id}
        poster={itemData.item.poster_path}
        title={itemData.item.title}
        onAssetSelection={fetchMovieHandler}
      />
    );
  };
  keyExtractor = (item) => item.id.toString();

  return (

<FlatList
     horizontal={true}
     data={upcomingMovies}
     initialNumToRender={5}
     windowSize={10}
     removeClippedSubviews={true}
     keyExtractor={keyExtractor}
     renderItem={renderRow}
 />

and then wrapping the renderRow() function in a useCallback hook.

The problem is that my data source data={upcomingMovies} is an array of objects with 2 levels and I need to use itemData.item.title to retrieve the title value for example.

While it works in my current renderItem settings it won't work when I use it in an external function as in

  const renderRow = ({ itemData }) => {
    return (
      <HomeItem
        id={itemData.item.id}
        poster={itemData.item.poster_path}
        title={itemData.item.title}
        onAssetSelection={fetchMovieHandler}
      />
    );
  };

I simply get, "item" variable not available

Any suggestion on how to modify the function?


问:
How can i check if user input is empty (react)

so i have a basic todo react app and how can i check if the user enters an empty value

How can i also make sure that the empty todo dosent get added to the todolist

答:
Provide us a sample code that you are working with, it will be easy for us to suggest things.

Assuming you using class component. In addTask method you can check if the user has entered the text or not.

```<code>export default class App extends React.Component {
  state = {
    list: [],
    task: ""
  };

  addTask = () => {
    const { task, list } = this.state;
    if (!task) {
      alert("Please enter a task");
      return false;
    }

    this.setState({ list: [...list, task] });
  };

  render() {
    const { task, list } = this.state;

    return (
      <>
        <input
          value={task}
          onChange={e => this.setState({ task: e.target.value })}
        />

        <button onClick={this.addTask}>Add task</button>

        <ul>
          {list.map(task => (
            <li>{task}</li>
          ))}
        </ul>
      </>
    );
  }
}
</code>```

https://codesandbox.io/s/intelligent-yonath-clken?file=/src/App.js:51-736

Body:
Provide us a sample code that you are working with, it will be easy for us to suggest things.

Assuming you using class component. In addTask method you can check if the user has entered the text or not.

export default class App extends React.Component {
  state = {
    list: [],
    task: ""
  };

  addTask = () => {
    const { task, list } = this.state;
    if (!task) {
      alert("Please enter a task");
      return false;
    }

    this.setState({ list: [...list, task] });
  };

  render() {
    const { task, list } = this.state;

    return (
      <>
        <input
          value={task}
          onChange={e => this.setState({ task: e.target.value })}
        />

        <button onClick={this.addTask}>Add task</button>

        <ul>
          {list.map(task => (
            <li>{task}</li>
          ))}
        </ul>
      </>
    );
  }
}

https://codesandbox.io/s/intelligent-yonath-clken?file=/src/App.js:51-736


问:
Windows Server 2019 Docker docker.exe: Error response from daemon: failed to start service utility VM (createreadwrite):
I created Windows Server 2019 VM in VMWare and I am trying to run there docker container (Ubuntu) but I get this error

docker.exe: Error response from daemon: failed to start service
  utility VM (createreadwrite)

What I already did:

I installed Hyper-V and also I enabled Containers in Windows
features.

Enable Nested Virtualization if you’re running Docker Containers
using Linux Virtual Machine running on Hyper-V Get-VM WinContainerHost | Set-VMProcessor -ExposeVirtualizationExtensions $true (machine exists, it's a Linux VM)

Enable LinuxKit system [Environment]::SetEnvironmentVariable("LCOW_SUPPORTED", "1", "Machine")

Restart Docker

Output from docker version

```<code>Client: Docker Engine - Enterprise
 Version:           19.03.5
 API version:       1.40
 Go version:        go1.12.12
 Git commit:        2ee0c57608
 Built:             11/13/2019 08:00:16
 OS/Arch:           windows/amd64
 Experimental:      false
</code>```

I already followed those threads (Linux Docker EE Containers on Windows Server 2016,Cannot start Hyper-V container) but it doesn't solved my problem.

答: I found the main issue. VMWare Workstation does not support nested virtualization for AMD Ryzen. When I installed Docker on my Win10 everything is OK.   </p>

Body:
I created Windows Server 2019 VM in VMWare and I am trying to run there docker container (Ubuntu) but I get this error

docker.exe: Error response from daemon: failed to start service
  utility VM (createreadwrite)

What I already did:

I installed Hyper-V and also I enabled Containers in Windows
features.

Enable Nested Virtualization if you’re running Docker Containers
using Linux Virtual Machine running on Hyper-V Get-VM WinContainerHost | Set-VMProcessor -ExposeVirtualizationExtensions $true (machine exists, it's a Linux VM)

Enable LinuxKit system [Environment]::SetEnvironmentVariable("LCOW_SUPPORTED", "1", "Machine")

Restart Docker

Output from docker version

Client: Docker Engine - Enterprise
 Version:           19.03.5
 API version:       1.40
 Go version:        go1.12.12
 Git commit:        2ee0c57608
 Built:             11/13/2019 08:00:16
 OS/Arch:           windows/amd64
 Experimental:      false

I already followed those threads (Linux Docker EE Containers on Windows Server 2016,Cannot start Hyper-V container) but it doesn't solved my problem.


问:
Sorting query output by Month name
I am trying to extract values from Excel using an SQL Query, but what I've been struggling with is sorting the months in their respective order. Right now the table is being sorted A-Z, I tried playing around with DATEPART, but was not very successful as I was getting an Int16 error.

```<code>Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1;
</code>```

This is the query that works, but the result is:

I am also open to any suggestions that could improve my query speed as the document is quite big, about 50k rows, thanks.

For anyone wondering the final query that worked was:

```<code>Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY SWITCH(
F1='January', 1,
F1='February', 2,
F1='March', 3,
F1='April', 4,
F1='May', 5,
F1='June', 6,
F1='July', 7,
F1='August', 8,
F1='September', 9,
F1='October', 10,
F1='November', 11,
F1='December', 12
);
</code>```

答:
Either use a CASE expression:

```<code>Select
  f1,
  SUM(f2),
  ROUND(SUM(REPLACE(f3, ',', '.')), 2),
  ROUND(SUM(REPLACE(f4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
             'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY
  CASE F1
    WHEN 'January' THEN 1
    WHEN 'February' THEN 2
    WHEN 'March' THEN 3
    WHEN 'April' THEN 4
    WHEN 'May' THEN 5
    WHEN 'June' THEN 6
    WHEN 'July' THEN 7
    WHEN 'August' THEN 8
    WHEN 'September' THEN 9
    WHEN 'October' THEN 10
    WHEN 'November' THEN 111
    WHEN 'December' THEN 12
  END;
</code>```

Or create a month table on the fly:

```<code>Select
  s.f1,
  SUM(s.f2),
  ROUND(SUM(REPLACE(s.f3, ',', '.')), 2),
  ROUND(SUM(REPLACE(s.f4, ',', '.')), 2)
FROM [Sheet1$] s
JOIN VALUES
(
  ('January', 1),
  ('February', 2),
  ('March', 3),
  ('April', 4),
  ('May', 5),
  ('June', 6),
  ('July', 7),
  ('August', 8),
  ('September', 9),
  ('October', 10),
  ('November', 11),
  ('December', 12)
) months(month_name, month_number) ON s.f1 = months.month_name
GROUP BY s.f1
ORDER BY months.month_number;
</code>```

Or create a real month table.

Title: Sorting query output by Month name

Body:
I am trying to extract values from Excel using an SQL Query, but what I've been struggling with is sorting the months in their respective order. Right now the table is being sorted A-Z, I tried playing around with DATEPART, but was not very successful as I was getting an Int16 error.

Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1;

This is the query that works, but the result is:

I am also open to any suggestions that could improve my query speed as the document is quite big, about 50k rows, thanks.

For anyone wondering the final query that worked was:

Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY SWITCH(
F1='January', 1,
F1='February', 2,
F1='March', 3,
F1='April', 4,
F1='May', 5,
F1='June', 6,
F1='July', 7,
F1='August', 8,
F1='September', 9,
F1='October', 10,
F1='November', 11,
F1='December', 12
);

Body:
Either use a CASE expression:

Select
  f1,
  SUM(f2),
  ROUND(SUM(REPLACE(f3, ',', '.')), 2),
  ROUND(SUM(REPLACE(f4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
             'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY
  CASE F1
    WHEN 'January' THEN 1
    WHEN 'February' THEN 2
    WHEN 'March' THEN 3
    WHEN 'April' THEN 4
    WHEN 'May' THEN 5
    WHEN 'June' THEN 6
    WHEN 'July' THEN 7
    WHEN 'August' THEN 8
    WHEN 'September' THEN 9
    WHEN 'October' THEN 10
    WHEN 'November' THEN 111
    WHEN 'December' THEN 12
  END;

Or create a month table on the fly:

Select
  s.f1,
  SUM(s.f2),
  ROUND(SUM(REPLACE(s.f3, ',', '.')), 2),
  ROUND(SUM(REPLACE(s.f4, ',', '.')), 2)
FROM [Sheet1$] s
JOIN VALUES
(
  ('January', 1),
  ('February', 2),
  ('March', 3),
  ('April', 4),
  ('May', 5),
  ('June', 6),
  ('July', 7),
  ('August', 8),
  ('September', 9),
  ('October', 10),
  ('November', 11),
  ('December', 12)
) months(month_name, month_number) ON s.f1 = months.month_name
GROUP BY s.f1
ORDER BY months.month_number;

Or create a real month table.


问:
Sum multiple columns in multiple rows
I have following data structure for sales:

```<code>id  year  M01  M02  M03  M04  M05 M06 M07 M08 M09 M10 M11 M12
 1  2020    0    5    4    0   10   0   0   0   0   0   0   0
 1  2019    4    3    0    0    6   0   7   0   8   0   0  10
 2  2020    0    5    4    0   10   0   0   0   0   0   0   0
 2  2019    4    3    0    0    6   0   7   0   8   0   0  10
</code>```

I need to know how many products with id=1 were sold for the last 12 month. If we are in June 2020 I need to sum M01, M02, M03, M04, M05 (WHERE year=2020) and M06, M07, M08, M09, M10, M11, M12 (WHERE year=2019) WHERE id=1. I should get a value of 36.

Please, any suggestions on how to do that in MySQL?

答:
You need to fix your data model.  Unpivot and then aggregate:

```<code>with reasonable_format as (
      select id, year, str_to_date(concat(year, '-01-01'), '%Y-%m-%d') as date, m01 as amount from sales union all
      select id, year, str_to_date(concat(year, '-02-01'), '%Y-%m-%d') as date, m02 from sales union all
      . . .
      select id, year, str_to_date(concat(year, '-02-01'), '%Y-%m-%d') as date, m12 from sales
    )
select sum(amount)
from reasonable_format rf
where id = 1 and date <= curdate - interval 1 year;
</code>```

reasonable_format is what your data should look like.

Title: Sum multiple columns in multiple rows

Body:
I have following data structure for sales:

id  year  M01  M02  M03  M04  M05 M06 M07 M08 M09 M10 M11 M12
 1  2020    0    5    4    0   10   0   0   0   0   0   0   0
 1  2019    4    3    0    0    6   0   7   0   8   0   0  10
 2  2020    0    5    4    0   10   0   0   0   0   0   0   0
 2  2019    4    3    0    0    6   0   7   0   8   0   0  10

I need to know how many products with id=1 were sold for the last 12 month. If we are in June 2020 I need to sum M01, M02, M03, M04, M05 (WHERE year=2020) and M06, M07, M08, M09, M10, M11, M12 (WHERE year=2019) WHERE id=1. I should get a value of 36.

Please, any suggestions on how to do that in MySQL?

Body:
You need to fix your data model.  Unpivot and then aggregate:

with reasonable_format as (
      select id, year, str_to_date(concat(year, '-01-01'), '%Y-%m-%d') as date, m01 as amount from sales union all
      select id, year, str_to_date(concat(year, '-02-01'), '%Y-%m-%d') as date, m02 from sales union all
      . . .
      select id, year, str_to_date(concat(year, '-02-01'), '%Y-%m-%d') as date, m12 from sales
    )
select sum(amount)
from reasonable_format rf
where id = 1 and date <= curdate - interval 1 year;

reasonable_format is what your data should look like.


问:
Best practice for showing multiple websites
I am super new to Web-developing but have to build a WebApp in which the user is supposed to:

Select a Item

Get a list of Items dependent on the fist selection and do stuff with this List

Get Information dependent on the first and second selection

Each of these steps is currently developed in a seperate html/php file.

I am looking for a good way to connect these pages with each other without data loss. And honestly I have no Idea how to achieve this.

I don't want finished code. I want ideas and hints on how to solve this, because I would like to learn something.

答:
I guess you have 2 options here.
First you could simply do a HTML form with a GET method that would lead to another page, where you would display another form with list of items you need. You can get the first selected item from $_GET.

The other solution would simply be to use AJAX, which would be more convenient. After the user selects the first item, you send AJAX request to a PHP file, get the list of items, and display them.


问:
Unable to import statsmodels
I am new to python and I am trying to learn how to use it for statistics. I have been trying to use the

from statsmodels.stats.weightstats import ztest
```

<p>But I get an error when I try to use this command.
Here is what it displayed:</p>

<pre class="lang-none prettyprint-override"><code>Python 2.7.17 (default, Nov  7 2019, 10:07:09)
[GCC 7.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from statsmodels.stats.weightstats import ztest
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/stats/__init__.py", line 1, in <module>
    from statsmodels.tools._testing import PytestTester
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/tools/__init__.py", line 1, in <module>
    from .tools import add_constant, categorical
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/tools/tools.py", line 8, in <module>
    from statsmodels.compat.python import lzip, lmap
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/compat/__init__.py", line 1, in <module>
    from statsmodels.tools._testing import PytestTester
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/tools/_testing.py", line 11, in <module>
    from statsmodels.compat.pandas import assert_equal
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/compat/pandas.py", line 4, in <module>
    import numpy as np
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/compat/numpy.py", line 46, in <module>
    NP_LT_114 = LooseVersion(np.__version__) < LooseVersion('1.14')
AttributeError: 'module' object has no attribute '__version__'
>>>
</code>```

Any help that I can get would be appreciated. I am using python 2.7.17

答:
I'm also working on python 2.7 facing exactly the same problem.
Here's how I solved it:

First thing first, it says in error message

NP_LT_114 = LooseVersion(np.version) < LooseVersion('1.14')
Thus make sure you have numpy version > 1.14

Secondly, I downgraded statsmodels from 0.11.0 to 0.10.0.

Hope it works for you too.

(numpy==1.16.5, statsmodels==0.10.0, python=2.7)

Title: Unable to import statsmodels

Body:
I am new to python and I am trying to learn how to use it for statistics. I have been trying to use the

from statsmodels.stats.weightstats import ztest

But I get an error when I try to use this command.
Here is what it displayed:

Python 2.7.17 (default, Nov  7 2019, 10:07:09)
[GCC 7.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from statsmodels.stats.weightstats import ztest
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/stats/__init__.py", line 1, in <module>
    from statsmodels.tools._testing import PytestTester
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/tools/__init__.py", line 1, in <module>
    from .tools import add_constant, categorical
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/tools/tools.py", line 8, in <module>
    from statsmodels.compat.python import lzip, lmap
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/compat/__init__.py", line 1, in <module>
    from statsmodels.tools._testing import PytestTester
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/tools/_testing.py", line 11, in <module>
    from statsmodels.compat.pandas import assert_equal
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/compat/pandas.py", line 4, in <module>
    import numpy as np
  File "/home/jico/.local/lib/python2.7/site-packages/statsmodels/compat/numpy.py", line 46, in <module>
    NP_LT_114 = LooseVersion(np.__version__) < LooseVersion('1.14')
AttributeError: 'module' object has no attribute '__version__'
>>>

Any help that I can get would be appreciated. I am using python 2.7.17


问:
Storing large objects/data on disk to free browser memory in JavaScript
I have a situation where I am dealing with very large files and trying to encrypt them.  I am running into a problem in the browser where the browser is running out of memory and so is crashing.

I was hoping to try and offload some of the larger objects/data to a local cache on disk to take these out of memory to help with this.

I've seen the CacheAPI which I thought may help, but this seems to only handle storing requests, whereas I am really dealing with arrays of bytes and objects that I want to store somewhere.

https://web.dev/cache-api-quick-guide/

Is there anything else I can use to support this, I need to support modern browsers so not IE.

答:
You can try indexedDB - it supports the data you need.

https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

localStorage size is 5000KB only, when it comes to IndexedDB you are limited by the disk space.


问:
MISCONF Redis is configured to save RDB snapshots
During writes to Redis ( SET foo bar ) I am getting the following error:

MISCONF Redis is configured to save RDB snapshots, but is currently
  not able to persist on disk. Commands that may modify the data set are
  disabled. Please check Redis logs for details about the error.

Basically I understand that the problem is that redis is not able to save data on the disk, but have no idea how to get rid of the problem.

Also the following question has the same problem, it is abandoned long time ago with no answers and most probably no attempts to solve the problem.

答: Please, be aware, that this error appears when your server is under attack. Just found that redis fails to write to '/etc/cron.d/web' where after correcting of permissions, new file consisting of mining algorithm with some hiding options was added. </p>


问:
C++ Function Calling Assembly Module
I want to write a customized module in assembly and have my C++ functions invoke it.  Instead of starting from scratch I would like to write the "draft" in C and let the compiler generates a blue print assembly source i.e.the listing file generated by the /FA compiler option.

However, I found that all the procedure names generated are already in decorated form.  Furthermore, the MASM will carry out its own name decoration again. So if I assemble my version without undecorating the compiler generated procedure name manually first I would get a linker error since the function names would not be matching.

Is possible to prevent this type of duplicated name decoration?

答:
You can declare your function as extern "C". That way, it will at most get an underscore before the name:

```<code>extern "C"{
  void foo(int bla){
  }
}
</code>```

Will become

```<code>_foo
</code>```

Title: C++ Function Calling Assembly Module

Body:
You can declare your function as extern "C". That way, it will at most get an underscore before the name:

extern "C"{
  void foo(int bla){
  }
}

Will become

_foo