问:
PowerShell Get-Content with basic manipulations so slow
I am merging a lot of large CSV files, e.g. while skipping the leading junk and appending the filename to each line:

```<code>Get-ChildItem . | Where Name -match "Q[0-4]20[0-1][0-9].csv" |
Foreach-Object {
    $file = $_.BaseName
    Get-Content $_.FullName | select-object -skip 3 | % {
        "$_,${file}" | Out-File -Append temp.csv -Encoding ASCII
    }
}
</code>```

In PowerShell this is incredibly slow even on an i7/16GB machine (~5 megabyte/minute).  Can I make it more efficient or should I just switch to e.g. Python?

答:
```<code>Measure-Command -Expression {
    Get-ChildItem C:\temp | Where Name -like "*.csv" | ForEach-Object {
        $file = $_.BaseName
        Get-Content $_.FullName | select-object -Skip 3 | ForEach-Object {
            "$_,$($file)" | Out-File -Append C:\temp\t\tempe1.csv -Encoding ASCII -Force
        }
    }
} # TotalSeconds      : 12,0526802 for 11415 lines
</code>```

If you first put everything into an array in memory, things go a lot faster:

```<code>Measure-Command -Expression {
    $arr = @()
    Get-ChildItem C:\temp | Where Name -like "*.csv" | ForEach-Object {
        $file = $_.BaseName
        $arr += Get-Content $_.FullName | select-object -Skip 3 | ForEach-Object {
            "$_,$($file)"
        }
    }
    $arr | Out-File -Append C:\temp\t\tempe2.csv -Encoding ASCII -Force
} # TotalSeconds      :  0,8197193  for 11415 lines
</code>```

EDIT: Fixed it so that your filename was added to each row.

Body:
I am merging a lot of large CSV files, e.g. while skipping the leading junk and appending the filename to each line:

Get-ChildItem . | Where Name -match "Q[0-4]20[0-1][0-9].csv" |
Foreach-Object {
    $file = $_.BaseName
    Get-Content $_.FullName | select-object -skip 3 | % {
        "$_,${file}" | Out-File -Append temp.csv -Encoding ASCII
    }
}

In PowerShell this is incredibly slow even on an i7/16GB machine (~5 megabyte/minute).  Can I make it more efficient or should I just switch to e.g. Python?

Body:
Measure-Command -Expression {
    Get-ChildItem C:\temp | Where Name -like "*.csv" | ForEach-Object {
        $file = $_.BaseName
        Get-Content $_.FullName | select-object -Skip 3 | ForEach-Object {
            "$_,$($file)" | Out-File -Append C:\temp\t\tempe1.csv -Encoding ASCII -Force
        }
    }
} # TotalSeconds      : 12,0526802 for 11415 lines

If you first put everything into an array in memory, things go a lot faster:

Measure-Command -Expression {
    $arr = @()
    Get-ChildItem C:\temp | Where Name -like "*.csv" | ForEach-Object {
        $file = $_.BaseName
        $arr += Get-Content $_.FullName | select-object -Skip 3 | ForEach-Object {
            "$_,$($file)"
        }
    }
    $arr | Out-File -Append C:\temp\t\tempe2.csv -Encoding ASCII -Force
} # TotalSeconds      :  0,8197193  for 11415 lines

EDIT: Fixed it so that your filename was added to each row.


来源: stackexchange

问:
HTML & CSS - Links doesn't work
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
  <div class="container">
    <div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>
    <div class="centered">Centered</div>
    <nav>
      <ul class="nav">
        <li class="home">Home</li>
        <li class="faq">FAQ</li>
        <li class="shop">Shop</li>
        <li class="contact">Contact us</li>
      </ul>
    </nav>
  </div>
</header></code>```

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

答:
Links are just overlapping as top value is given 173px for all of them. Just change top: 173px; to some other value for each link or instead of padding-right just use "right" and "left" positioning.  or remove all these lines below.

```<code>.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}
.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}
.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}
.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}
</code>```

You position each link as required.

ContentLicense: CC BY-SA 3.0

Title: HTML & CSS - Links doesn't work

Body:
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}

Centered

Home

FAQ

Shop

Contact us

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

Body:
Links are just overlapping as top value is given 173px for all of them. Just change top: 173px; to some other value for each link or instead of padding-right just use "right" and "left" positioning.  or remove all these lines below.

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}
.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}
.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}
.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

You position each link as required.


问:
Uploading to S3 using Python Requests
I'd like to upload xml's directly to S3 without the use of modules like boto, boto3, or tinys3.

So far I have written:

```<code> url = "https://my-test-s3.s3.amazonaws.com"
 with open(xml_file,'rb') as data:
     requests.put(url, data=data)
</code>```

and I've gone and head and set the AllowedOrigin on my S3 bucket to accept my server's address.

This does not error when running, however, it also does not seem to be uploading anything.

Any help would be appreciated --- I'd like to (a) get the thing to upload and (b) figure out how to apply AWSAccessKey and AWSSecretAccessKey to the request

答:
If you want to upload xml's directly to S3 without the use of modules like boto, boto3, or tinys3 I would recommend to use awscli:

```<code>pip install awscli
aws configure  # enter your AWSAccessKey and AWSSecretAccessKey credentials
</code>```

AWSAccessKey and AWSSecretAccessKey will be stored inside ~/.aws folder permanently after using aws configure.

And then you can upload files using python:

```<code>os.system("aws s3 cp {0} s3://your_bucket_name/{1}".format(file_path, file_name))
</code>```

Docs are here.

Title: Uploading to S3 using Python Requests

Body:
I'd like to upload xml's directly to S3 without the use of modules like boto, boto3, or tinys3.

So far I have written:

 url = "https://my-test-s3.s3.amazonaws.com"
 with open(xml_file,'rb') as data:
     requests.put(url, data=data)

and I've gone and head and set the AllowedOrigin on my S3 bucket to accept my server's address.

This does not error when running, however, it also does not seem to be uploading anything.

Any help would be appreciated --- I'd like to (a) get the thing to upload and (b) figure out how to apply AWSAccessKey and AWSSecretAccessKey to the request

Body:
If you want to upload xml's directly to S3 without the use of modules like boto, boto3, or tinys3 I would recommend to use awscli:

pip install awscli
aws configure  # enter your AWSAccessKey and AWSSecretAccessKey credentials

AWSAccessKey and AWSSecretAccessKey will be stored inside ~/.aws folder permanently after using aws configure.

And then you can upload files using python:

os.system("aws s3 cp {0} s3://your_bucket_name/{1}".format(file_path, file_name))

Docs are here.


问:
Activity is resetting values
I have an activity that sum distance according user walks. The problem is when app goes to background and after something around 50 minutes I resume activity, values start again.
I have tried too many things to solve this problem without success.

Does someone have any idea?

Thanks

答:
```<code>//add below line in manifest where initialize activity

         <activity
            android:name=".activity.MainActivity"
            android:configChanges="orientation|screenSize">
        </activity>
</code>```

Title: Activity is resetting values


问:
tar: Unrecognized archive format error when trying to unpack flower_photos.tgz, TF tutorials on OSX
I'm trying to unpack the flower_photos.tgz after curling it using

```<code>curl -O http://download.tensorflow.org/example_../images/flower_photos.tgz
tar xzf flower_photos.tgz
</code>```

This is from the image retraining tutorial for TensorFlow

Results from curling

```<code>% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100   127  100   127    0     0    255      0 --:--:-- --:--:-- --:--:--   255
</code>```

Then when I try to unpack

```<code>tar xzf flower_photos.tgz
tar: Unrecognized archive format
tar: Error exit delayed from previous errors.
</code>```

答:
try using the -L flag, i.e.

```<code>curl -OL http://download.tensorflow.org/example_../images/flower_photos.tgz
</code>```

source: https://github.com/arq5x/bedtools2/issues/189

Body:
I'm trying to unpack the flower_photos.tgz after curling it using

curl -O http://download.tensorflow.org/example_../images/flower_photos.tgz
tar xzf flower_photos.tgz

This is from the image retraining tutorial for TensorFlow

Results from curling

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100   127  100   127    0     0    255      0 --:--:-- --:--:-- --:--:--   255

Then when I try to unpack

tar xzf flower_photos.tgz
tar: Unrecognized archive format
tar: Error exit delayed from previous errors.

Body:
try using the -L flag, i.e.

curl -OL http://download.tensorflow.org/example_../images/flower_photos.tgz

source: https://github.com/arq5x/bedtools2/issues/189


问:
Python: Store pixel interpolated data into array instead of image with matplotlib
I am currently creating an image by interpolation a set of points (my_data) and then accessing the interpolated pixel data by opening the image created:

```<code>from matplotlib import pyplot as plt
import numpy as np
import matplotlib.image as mpimg

fig = plt.figure(frameon=False)
fig.set_size_inches(5, 3)
plt.axis('off')
plt.imshow(my_data, interpolation='bilinear',origin='lower')
plt.savefig("my_image.png", dpi=1000, bbox_inches='tight', pad_inches=0, frameon=None)
img_data = mpimg.imread('my_image.png')
</code>```

I want to access img_data without having to 'physically' create an image and then open said image. Any idea on how to do this?

答: You could just use scipy.interpolate, instead of relying on matplolib.

Body:
I am currently creating an image by interpolation a set of points (my_data) and then accessing the interpolated pixel data by opening the image created:

from matplotlib import pyplot as plt
import numpy as np
import matplotlib.image as mpimg

fig = plt.figure(frameon=False)
fig.set_size_inches(5, 3)
plt.axis('off')
plt.imshow(my_data, interpolation='bilinear',origin='lower')
plt.savefig("my_image.png", dpi=1000, bbox_inches='tight', pad_inches=0, frameon=None)
img_data = mpimg.imread('my_image.png')

I want to access img_data without having to 'physically' create an image and then open said image. Any idea on how to do this?


问:
ObjectUnsubscribedError after timeout
I am using an Event EventEmitter in a service component like this:

export class SettingsService {
    public sidebarColor = '#D80B0B';
    public sidebarColorUpdate: EventEmitter<string> = new >EventEmitter();
```

<p>I then subscribe to it from other components like this :</p>

<pre class="lang-js prettyprint-override"><code>this.settingsService.sidebarColorUpdate.subscribe((color: string) => {
    if (color === '#fff') {
        this.normalFontColor = 'rgba(0,0,0,.6)';
        this.dividerBgColor = 'rgba(0,0,0,.1)';
    } else {
        this.normalFontColor = 'rgba(255,255,255,.8)';
        this.dividerBgColor = 'rgba(255, 255, 255, 0.5)';
    }
 });
</code>```

And then unsubscribe in the ngOnDestroy. This works great but the problem now arises when the session times out and the router defaults back to the login page. After login in again I get this error

message: "object unsubscribed" name: "ObjectUnsubscribedError"

Why is this happening ?

答:
I can't tell why do you get this error but that's not the major problem here. The issue is that you should not be using EventEmitter in the services because it does not guarantee to remain Observable.

Here is a proper solution to your problem using Observables:

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

export class SettingsService {
    // Source variable should be private to prevent subscribing to it
    private sidebarColorUpdatedSource = new Subject<string>();
    // Expose an observable to allow subscribers listen to the updates
    sidebarColorUpdated$ = this.sidebarColorUpdatedSource.asObservable();

    // Expose a public method for updating the sidebar color
    updateSidebarColor(color: string): void {
        // Update the color

        // Notify subscribers
        this.sidebarColorUpdatedSource.next(color);
    }
}
```

<p>Component:</p>

<pre class="lang-js prettyprint-override"><code>private sidebarColorUpdated$: Subscription;

ngOnInit(): void {
    this.sidebarColorUpdated$ = this.settingsService.sidebarColorUpdated$.subscribe(color => {
        // Do whatever you need
    });
}

ngOnDestroy(): void {
    if (this.sidebarColorUpdated$)
        this.sidebarColorUpdated$.unsubscribe();
}
</code>```

When you need to update the sidebar color call SettingsService.updateSidebarColor(color: string) method and each subscriber will be notified of the change.

Title: ObjectUnsubscribedError after timeout

Body:
I am using an Event EventEmitter in a service component like this:

export class SettingsService {
    public sidebarColor = '#D80B0B';
    public sidebarColorUpdate: EventEmitter<string> = new >EventEmitter();

I then subscribe to it from other components like this :

this.settingsService.sidebarColorUpdate.subscribe((color: string) => {
    if (color === '#fff') {
        this.normalFontColor = 'rgba(0,0,0,.6)';
        this.dividerBgColor = 'rgba(0,0,0,.1)';
    } else {
        this.normalFontColor = 'rgba(255,255,255,.8)';
        this.dividerBgColor = 'rgba(255, 255, 255, 0.5)';
    }
 });

And then unsubscribe in the ngOnDestroy. This works great but the problem now arises when the session times out and the router defaults back to the login page. After login in again I get this error

message: "object unsubscribed" name: "ObjectUnsubscribedError"

Why is this happening ?

Body:
I can't tell why do you get this error but that's not the major problem here. The issue is that you should not be using EventEmitter in the services because it does not guarantee to remain Observable.

Here is a proper solution to your problem using Observables:

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

export class SettingsService {
    // Source variable should be private to prevent subscribing to it
    private sidebarColorUpdatedSource = new Subject<string>();
    // Expose an observable to allow subscribers listen to the updates
    sidebarColorUpdated$ = this.sidebarColorUpdatedSource.asObservable();

    // Expose a public method for updating the sidebar color
    updateSidebarColor(color: string): void {
        // Update the color

        // Notify subscribers
        this.sidebarColorUpdatedSource.next(color);
    }
}

Component:

private sidebarColorUpdated$: Subscription;

ngOnInit(): void {
    this.sidebarColorUpdated$ = this.settingsService.sidebarColorUpdated$.subscribe(color => {
        // Do whatever you need
    });
}

ngOnDestroy(): void {
    if (this.sidebarColorUpdated$)
        this.sidebarColorUpdated$.unsubscribe();
}

When you need to update the sidebar color call SettingsService.updateSidebarColor(color: string) method and each subscriber will be notified of the change.


问:
Maximize gmap in dialog primefaces
I want to display a dialog which has a gmap as element, it works fine when I set height and width, but what I need is show it as maximized full screen map. The Dialog is shown in fullscreen, but map is empty, only when I back to default size it is shown.

My code is

```<code><p:commandLink id="id" value="Modal" onclick="PF('dlg').show(); PF('dlg').toggleMaximize();"/>
<p:dialog appendTo="@(body)" id="dlg" widgetVar="dlg" maximizable="true" width="1920" height="1080">
    <p:gmap id="gmap" center="41.381542, 2.122893" zoom="15" type="HYBRID" style="width:100%;height:100%;">
    </p:gmap>
</p:dialog>
</code>```

How can I solve my problem?

答:
You can add following JavaScript on your page

```<code><script>
            function resizeElement(elementId,width,height){
                console.log("Resizing element " + elementId + " W/H="+ width + "/" + height);

                var element = document.getElementById(elementId);

                element.style.width=width+"px";
                element.style.height=height+"px"
            }

            function resizePfGmapInsideWrapperElement(wrapperElementId){
                var wrapperElement=document.getElementById(wrapperElementId);
                var width=wrapperElement.clientWidth-40;
                var height=wrapperElement.clientHeight-60;

                resizeElement("gmap",width,height);
            }

            function resizePfGmapInsideDialog(){
                resizePfGmapInsideWrapperElement("dlg");
            }
</script>
</code>```

and then add resizePfGmapInsideDialog() into p:commandLink onclick

```<code><p:commandLink id="id"
               value="Modal"
               onclick="PF('dlg').show(); PF('dlg').toggleMaximize(); resizePfGmapInsideDialog();"/>
</code>```

Actually whenever you call PF('dlg').toggleMaximize(); also call resizePfGmapInsideDialog() right after and p:gmap will automatically resize inside dialog's content area.

Title: Maximize gmap in dialog primefaces

Body:
I want to display a dialog which has a gmap as element, it works fine when I set height and width, but what I need is show it as maximized full screen map. The Dialog is shown in fullscreen, but map is empty, only when I back to default size it is shown.

My code is

How can I solve my problem?

Body:
You can add following JavaScript on your page

<script>
            function resizeElement(elementId,width,height){
                console.log("Resizing element " + elementId + " W/H="+ width + "/" + height);

                var element = document.getElementById(elementId);

                element.style.width=width+"px";
                element.style.height=height+"px"
            }

            function resizePfGmapInsideWrapperElement(wrapperElementId){
                var wrapperElement=document.getElementById(wrapperElementId);
                var width=wrapperElement.clientWidth-40;
                var height=wrapperElement.clientHeight-60;

                resizeElement("gmap",width,height);
            }

            function resizePfGmapInsideDialog(){
                resizePfGmapInsideWrapperElement("dlg");
            }
</script>

and then add resizePfGmapInsideDialog() into p:commandLink onclick

<p:commandLink id="id"
               value="Modal"
               onclick="PF('dlg').show(); PF('dlg').toggleMaximize(); resizePfGmapInsideDialog();"/>

Actually whenever you call PF('dlg').toggleMaximize(); also call resizePfGmapInsideDialog() right after and p:gmap will automatically resize inside dialog's content area.


问:
How to remove oldest folder(s) of a group of folders in a folder with several folder groups?
The folder D:\Backup contains following subfolders listed here with name (left) and last modification date (right) as displayed in Windows Explorer:

```<code>20171113.224424         15.11.2017 17:24
20171113.224421         16.11.2017 15:26
20171113.224412         16.11.2017 15:33
20171112.424424         16.11.2017 15:33
20171112.224424         16.11.2017 15:33
20171112.221424         16.11.2017 15:34
20171111.224428         16.11.2017 15:34
20171111.224427         16.11.2017 15:35
20171111.224424         16.11.2017 15:34
</code>```

I need a batch script to check if there are more than two folders with same date string with always 8 digits left to . in folder name like  20171113.224424, 20171113.224421 and 20171113.224412.

The batch file should keep the newest two folders with same date string and delete all other older folders with using the folder creation date instead of last modification date.

For the example above with creation date being equal the last modification date the folders to delete are:

```<code>20171113.224424
20171112.224424
20171111.224424
</code>```

When two folders have the same creation date, the one with lower number after the dot should be deleted if that is possible.

The remaining folders are:

```<code>20171113.224421
20171113.224412
20171112.424424
20171112.221424
20171111.224428
20171111.224427
</code>```

I tried a lot of codes, but I don't post them all here.

I have code which list all folders in directory, but can't find the method to group the folders with same first 8 letters:

```<code>@echo off
set back=%cd%
for /d %%i in (d:\backup\*) do (
    cd "%%i"
    echo current directory:
    cd
    pause
)
cd %back%
</code>```

I wrote code to skip last 10 lines if there a regular grouping and delete the folders that I don't need as described above:

```<code>@echo off
for /F "skip=10 delims=" %%I in ('dir "d:\backup\*" /AD /B /O-N 2^>nul') do rd /Q /S "d:\backup\%%I"
</code>```

答:
A batch file for this task would be:

```<code>@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "BackupFolder=D:\backup"
set "LastDate="
for /F "delims=." %%I in ('dir "%BackupFolder%\????????.*" /AD /B /ON 2^>nul') do (
    if not "!LastDate!" == "%%I" (
        for /F "skip=2 delims=" %%D in ('dir "%BackupFolder%\%%I.*" /AD /B /O-D-N /TC') do rd /Q /S "%BackupFolder%\%%D"
        set "LastDate=%%I"
    )
)
endlocal
</code>```

The first, outer FOR executes in a separate command process started with cmd /c in background the DIR command line specified in first parenthesis and captures everything output by DIR to handle STDOUT for processing it later line by line.

The used DIR command outputs

only directories matching wildcard pattern ????????.* because of /AD (attribute directory)

with only their names without path because of /B (bare format)

sorted by name because of /ON (ordered by name).

It is possible that the backup folder currently contains no folder matching this pattern. In this case DIR would output an error message to handle STDERR which would be confusing because of containing file instead of directory. This possible error message is redirected to device NUL to suppress it.

Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the DIR command line with using a separate command process started in background.

Outer FOR processes the captured lines with ignoring empty lines and lines starting with a semicolon. Such lines do not exist here, so no problem. Each (other) line is split up into two strings using . as delimiter. Only the first string left to first . of each line is assigned to loop variable I which is used in the command lines executed next.

It is important here to use command DIR to get a directory list processed by FOR not being modified during loop execution instead of using for /D which would read next directory name directly from file system on each iteration of the loop. The list of directories changes during loop execution. On using for /D it could happen that some directories are skipped because of directory list changes while processing the directories.

The IF condition makes a simple case-sensitive string comparison using delayed environment variable expansion to compare the date string of previous processed folder(s) with the current folder. Only on difference between date of last processed folder(s) and date of current folder the inner loop is executed. This IF condition is just for making the folder deletion process a little bit faster.

It is no problem here to use delayed environment environment variable expansion as no folder in backup folder contains an exclamation mark in folder name.

The second, inner FOR loop runs also command DIR to get a list of directories with the date string of current folder with just their names, but this time first reverse ordered by creation date and second reverse ordered by name in case of two or more folders have same creation date because of /O-D-N (ordered reverse by date and next reverse by name) and /TC (time: creation). Reverse date order means newest directory is output first and oldest is output last.

The inner FOR loop processes the captured lines output by DIR with skipping the first two lines which means ignoring the two newest folders. The other lines are processed without splitting the line up because of delims= (empty delimiter list) and therefore the complete folder name as output by DIR is assigned to loop variable D.

The command RD deletes the folder of which name is hold in loop variable D quietly because of /Q with all files and subfolders because of /S.

Then the date string of current folder is assigned to environment variable LastDate to skip all folders in directory list of outer FOR with same date string.

It would be also possible to use a single command line without usage of delayed environment variable expansion being a bit slower which would also work for folders with ! in name.

```<code>@for /F "delims=." %%I in ('dir "D:\backup\????????.*" /AD /B /ON 2^>nul') do @for /F "skip=2 delims=" %%D in ('dir "D:\backup\%%I.*" /AD /B /O-D-N /TC') do @rd /Q /S "D:\backup\%%D"
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

dir /?

echo /?

endlocal /?

for /?

if /?

rd /?

set /?

setlocal /?

Update:

Enhanced version logging the names of all files with full path before deletion of a backup directory.

```<code>@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "BackupFolder=D:\backup"
set "LastDate="
set "LogFile=%BackupFolder%\DeletedFiles.log"
for /F "delims=." %%I in ('dir "%BackupFolder%\????????.*" /AD /B /ON 2^>nul') do (
    if not "!LastDate!" == "%%I" (
        for /F "skip=2 delims=" %%D in ('dir "%BackupFolder%\%%I.*" /AD /B /O-D-N /TC') do (
            dir "%BackupFolder%\%%D" /A-D /B /ON /S >>"%LogFile%" 2>nul
            rd /Q /S "%BackupFolder%\%%D"
        )
        set "LastDate=%%I"
    )
)
endlocal
</code>```

Single command line version:

```<code>@for /F "delims=." %%I in ('dir "D:\backup\????????.*" /AD /B /ON 2^>nul') do @for /F "skip=2 delims=" %%D in ('dir "D:\backup\%%I.*" /AD /B /O-D-N /TC') do @dir "D:\backup\%%D" /A-D /B /ON /S >>"D:\backup\DeletedFiles.log" 2>nul & rd /Q /S "D:\backup\%%D"
</code>```

Body:
The folder D:\Backup contains following subfolders listed here with name (left) and last modification date (right) as displayed in Windows Explorer:

20171113.224424         15.11.2017 17:24
20171113.224421         16.11.2017 15:26
20171113.224412         16.11.2017 15:33
20171112.424424         16.11.2017 15:33
20171112.224424         16.11.2017 15:33
20171112.221424         16.11.2017 15:34
20171111.224428         16.11.2017 15:34
20171111.224427         16.11.2017 15:35
20171111.224424         16.11.2017 15:34

I need a batch script to check if there are more than two folders with same date string with always 8 digits left to . in folder name like  20171113.224424, 20171113.224421 and 20171113.224412.

The batch file should keep the newest two folders with same date string and delete all other older folders with using the folder creation date instead of last modification date.

For the example above with creation date being equal the last modification date the folders to delete are:

20171113.224424
20171112.224424
20171111.224424

When two folders have the same creation date, the one with lower number after the dot should be deleted if that is possible.

The remaining folders are:

20171113.224421
20171113.224412
20171112.424424
20171112.221424
20171111.224428
20171111.224427

I tried a lot of codes, but I don't post them all here.

I have code which list all folders in directory, but can't find the method to group the folders with same first 8 letters:

@echo off
set back=%cd%
for /d %%i in (d:\backup\*) do (
    cd "%%i"
    echo current directory:
    cd
    pause
)
cd %back%

I wrote code to skip last 10 lines if there a regular grouping and delete the folders that I don't need as described above:

@echo off
for /F "skip=10 delims=" %%I in ('dir "d:\backup\*" /AD /B /O-N 2^>nul') do rd /Q /S "d:\backup\%%I"

Body:
A batch file for this task would be:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "BackupFolder=D:\backup"
set "LastDate="
for /F "delims=." %%I in ('dir "%BackupFolder%\????????.*" /AD /B /ON 2^>nul') do (
    if not "!LastDate!" == "%%I" (
        for /F "skip=2 delims=" %%D in ('dir "%BackupFolder%\%%I.*" /AD /B /O-D-N /TC') do rd /Q /S "%BackupFolder%\%%D"
        set "LastDate=%%I"
    )
)
endlocal

The first, outer FOR executes in a separate command process started with cmd /c in background the DIR command line specified in first parenthesis and captures everything output by DIR to handle STDOUT for processing it later line by line.

The used DIR command outputs

only directories matching wildcard pattern ????????.* because of /AD (attribute directory)

with only their names without path because of /B (bare format)

sorted by name because of /ON (ordered by name).

It is possible that the backup folder currently contains no folder matching this pattern. In this case DIR would output an error message to handle STDERR which would be confusing because of containing file instead of directory. This possible error message is redirected to device NUL to suppress it.

Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the DIR command line with using a separate command process started in background.

Outer FOR processes the captured lines with ignoring empty lines and lines starting with a semicolon. Such lines do not exist here, so no problem. Each (other) line is split up into two strings using . as delimiter. Only the first string left to first . of each line is assigned to loop variable I which is used in the command lines executed next.

It is important here to use command DIR to get a directory list processed by FOR not being modified during loop execution instead of using for /D which would read next directory name directly from file system on each iteration of the loop. The list of directories changes during loop execution. On using for /D it could happen that some directories are skipped because of directory list changes while processing the directories.

The IF condition makes a simple case-sensitive string comparison using delayed environment variable expansion to compare the date string of previous processed folder(s) with the current folder. Only on difference between date of last processed folder(s) and date of current folder the inner loop is executed. This IF condition is just for making the folder deletion process a little bit faster.

It is no problem here to use delayed environment environment variable expansion as no folder in backup folder contains an exclamation mark in folder name.

The second, inner FOR loop runs also command DIR to get a list of directories with the date string of current folder with just their names, but this time first reverse ordered by creation date and second reverse ordered by name in case of two or more folders have same creation date because of /O-D-N (ordered reverse by date and next reverse by name) and /TC (time: creation). Reverse date order means newest directory is output first and oldest is output last.

The inner FOR loop processes the captured lines output by DIR with skipping the first two lines which means ignoring the two newest folders. The other lines are processed without splitting the line up because of delims= (empty delimiter list) and therefore the complete folder name as output by DIR is assigned to loop variable D.

The command RD deletes the folder of which name is hold in loop variable D quietly because of /Q with all files and subfolders because of /S.

Then the date string of current folder is assigned to environment variable LastDate to skip all folders in directory list of outer FOR with same date string.

It would be also possible to use a single command line without usage of delayed environment variable expansion being a bit slower which would also work for folders with ! in name.

@for /F "delims=." %%I in ('dir "D:\backup\????????.*" /AD /B /ON 2^>nul') do @for /F "skip=2 delims=" %%D in ('dir "D:\backup\%%I.*" /AD /B /O-D-N /TC') do @rd /Q /S "D:\backup\%%D"

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

dir /?

echo /?

endlocal /?

for /?

if /?

rd /?

set /?

setlocal /?

Update:

Enhanced version logging the names of all files with full path before deletion of a backup directory.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "BackupFolder=D:\backup"
set "LastDate="
set "LogFile=%BackupFolder%\DeletedFiles.log"
for /F "delims=." %%I in ('dir "%BackupFolder%\????????.*" /AD /B /ON 2^>nul') do (
    if not "!LastDate!" == "%%I" (
        for /F "skip=2 delims=" %%D in ('dir "%BackupFolder%\%%I.*" /AD /B /O-D-N /TC') do (
            dir "%BackupFolder%\%%D" /A-D /B /ON /S >>"%LogFile%" 2>nul
            rd /Q /S "%BackupFolder%\%%D"
        )
        set "LastDate=%%I"
    )
)
endlocal

Single command line version:

@for /F "delims=." %%I in ('dir "D:\backup\????????.*" /AD /B /ON 2^>nul') do @for /F "skip=2 delims=" %%D in ('dir "D:\backup\%%I.*" /AD /B /O-D-N /TC') do @dir "D:\backup\%%D" /A-D /B /ON /S >>"D:\backup\DeletedFiles.log" 2>nul & rd /Q /S "D:\backup\%%D"

ContentLicense: CC BY-SA 4.0


问:
Class that calculates the total weekly wage
Want to create a class that calculated the weekly wage with the over hours, but it outputs something strange: -1.07374e+08. Any help?</p>

```<code>#include <iostream>
using namespace std;

class Wage {
public:
Wage(int hW, int h) {
    hWage = hW;
    hours = h;
}
void setWage() {
    if (hours <= 40) {
        tWage = hours * tWage;
    } else {
        tWage = hours * hWage + (hours - 40) * (hWage * 1.5);
    }
}
float getWage() {
    return tWage;
}

private:
float tWage;
float hWage;
float hours;
};

int main() {

Wage w(10, 8);
cout << w.getWage() << endl;

return 0;
}
</code>```

答: You never called w.setWage() before calling w.getWage().

Body:
Want to create a class that calculated the weekly wage with the over hours, but it outputs something strange: -1.07374e+08. Any help?

#include <iostream>
using namespace std;

class Wage {
public:
Wage(int hW, int h) {
    hWage = hW;
    hours = h;
}
void setWage() {
    if (hours <= 40) {
        tWage = hours * tWage;
    } else {
        tWage = hours * hWage + (hours - 40) * (hWage * 1.5);
    }
}
float getWage() {
    return tWage;
}

private:
float tWage;
float hWage;
float hours;
};

int main() {

Wage w(10, 8);
cout << w.getWage() << endl;

return 0;
}


问:
Copy links from image src as a text
I have a list where each li has some image inside and I'm trying to copy each img src= as plain text to .someDiv

HTML

```<code><ul class="someList">
  <li><a href=""><img src="/linktopicture1.jpg" class="someImage"></a></li>
  <li><a href=""><img src="/linktopicture2.jpg" class="someImage"></a></li>
  <li><a href=""><img src="/linktopicture3.jpg" class="someImage"></a></li>
</ul>

<div class="someDiv">
  <!-- those source links should be written here like this:
  /linktopicture1.jpg
  /linktopicture2.jpg
  /linktopicture3.jpg
  -->
</div>
</code>```

I've tried something like this, but it's not right:

jQuery

```<code>$(document).ready(function() {
  $('.someList li').each(function() {
     var $this = $(this);

     // Get src attribute from img
     var url = $this.find('.someImage').first().attr('src');

     // Set href attribute on a
     $this.find('.someDiv').first().attr(url);
  });
});
</code>```

答:
Problem is in statement

```<code> $this.find('.someDiv').first().attr(url);
</code>```

.someDiv is not child of current element i.e. this thus above code will not work.

instead use

```<code>$('.someDiv').append(url);
</code>```

$(document).ready(function() {
  $('.someList li').each(function() {
    var $this = $(this);
    var url = $this.find('.someImage').attr('src');
    //Set anchor href
    $this.find('a').attr('href', url);
    $('.someDiv').append(url);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="someList">
  <li>
    <img src="/linktopicture1.jpg" class="someImage">
  </li>
  <li>
    <img src="/linktopicture2.jpg" class="someImage">
  </li>
  <li>
    <img src="/linktopicture3.jpg" class="someImage">
  </li>
</ul>

<div class="someDiv">
</div></code>```

Title: Copy links from image src as a text

Body:
I have a list where each li has some image inside and I'm trying to copy each img src= as plain text to .someDiv

HTML

I've tried something like this, but it's not right:

jQuery

$(document).ready(function() {
  $('.someList li').each(function() {
     var $this = $(this);

     // Get src attribute from img
     var url = $this.find('.someImage').first().attr('src');

     // Set href attribute on a
     $this.find('.someDiv').first().attr(url);
  });
});

Body:
Problem is in statement

 $this.find('.someDiv').first().attr(url);

.someDiv is not child of current element i.e. this thus above code will not work.

instead use

$('.someDiv').append(url);

$(document).ready(function() {
  $('.someList li').each(function() {
    var $this = $(this);
    var url = $this.find('.someImage').attr('src');
    //Set anchor href
    $this.find('a').attr('href', url);
    $('.someDiv').append(url);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="someList">
  <li>
    <a href=""><img src="/linktopicture1.jpg" class="someImage"></a>
  </li>
  <li>
    <a href=""><img src="/linktopicture2.jpg" class="someImage"></a>
  </li>
  <li>
    <a href=""><img src="/linktopicture3.jpg" class="someImage"></a>
  </li>
</ul>

<div class="someDiv">
</div>


问:
Cloud Function writing to Firebase Realtime Database times out
I can see a new entry is added as soon as I get the URL, but the request hangs and times out. Why?

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.add = functions.https.onRequest((request, response)=>
{
    var ref = admin.database().ref("jobs");
    var childRef = ref.push();
    childRef.set
    (
        {
            title: "test",
            pay: 100
        }
    );
})
</code>```

The code is based on the following example. https://firebase.google.com/docs/database/admin/save-data

Result

```<code>{"error":{"code":500,"status":"INTERNAL","message":"function execution attempt timed out"}}
</code>```

答:
Cloud Functions triggered by HTTP requests need to be terminated by ending them with a send(), redirect(), or end(), otherwise they will continue running and reach the timeout.

From the terminate HTTP functions section of the documentation on HTTP triggers:

Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system. See also Sync, Async and Promises.

Therefore, in your example, you can end the request by sending a response:

```<code>exports.add = functions.https.onRequest((request, response)=>
{
    var ref = admin.database().ref("jobs");
    var childRef = ref.push();
    childRef.set
    (
        {
            title: "test",
            pay: 100
        }
    );
    response.status(200).send("OK!");
})
</code>```

Body:
I can see a new entry is added as soon as I get the URL, but the request hangs and times out. Why?

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.add = functions.https.onRequest((request, response)=>
{
    var ref = admin.database().ref("jobs");
    var childRef = ref.push();
    childRef.set
    (
        {
            title: "test",
            pay: 100
        }
    );
})

The code is based on the following example. https://firebase.google.com/docs/database/admin/save-data

Result

{"error":{"code":500,"status":"INTERNAL","message":"function execution attempt timed out"}}

Body:
Cloud Functions triggered by HTTP requests need to be terminated by ending them with a send(), redirect(), or end(), otherwise they will continue running and reach the timeout.

From the terminate HTTP functions section of the documentation on HTTP triggers:

Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system. See also Sync, Async and Promises.

Therefore, in your example, you can end the request by sending a response:

exports.add = functions.https.onRequest((request, response)=>
{
    var ref = admin.database().ref("jobs");
    var childRef = ref.push();
    childRef.set
    (
        {
            title: "test",
            pay: 100
        }
    );
    response.status(200).send("OK!");
})


问:
Drawbacks of using /LARGEADDRESSAWARE for 32-bit Windows executables?
We need to link one of our executables with this flag as it uses lots of memory.

But why give one EXE file special treatment. Why not standardize on /LARGEADDRESSAWARE?

So the question is: Is there anything wrong with using /LARGEADDRESSAWARE even if you don't need it. Why not use it as standard for all EXE files?

答:
No, "legacy code" in this context (C/C++) is not exclusively code that plays ugly tricks with the MSB of pointers.

It also includes all the code that uses 'int' to store the difference between two pointer, or the length of a memory area, instead of using the correct type 'size_t' : 'int' being signed has 31 bits, and can not handle a value of more than 2 Gb.

A way to cure a good part of your code is to go over it and correct all of those innocuous "mixing signed and unsigned" warnings. It should do a good part of the job, at least if you haven't defined function where an argument of type int is actually a memory length.

Still that "legacy code" will apparently work correctly for a very long while, even if you correct nothing.

That's because it will break only when you'll allocate more than 2 Gb in one block. Or when you'll compare two unrelated pointers that are more than 2 Gb away from each other.

As comparing unrelated pointers is technically an undefined behaviour anyway, you won't encounter that much code that does it (but you can never be sure).

For the first case, very frequently even if in total you need more than 2Gb, your program actually never makes single allocations that are larger than that. In fact in Windows, even with LARGEADDRESSAWARE you won't be able by default to allocate that much given the way the memory is organized. You'd need to shuffle the system DLL around to get a continuous block of more than 2Gb

But Murphy's laws says that kind of code will breaks one day, it's just that it will happen very long after you've enable LARGEADDRESSAWARE without checking, and when nobody will remember this has been done.


答: w.tWage hasn't been initialised. You're asking for w.getWage(), but the function to calculate the value hasn't been called yet.

Title: Class that calculates the total weekly wage


问:
Renumber all records when one is updated
I am using Access 2010. I have a datasheet form called Projects with two fields, [Project Name] and [Priority]. I would like to be able to update the priority number for one of the records and have all other priority numbers update automatically. For example, Project Red is priority 1. Project Orange is Priority 2 and Project Blue is Priority 3. If I update Blue to number 1, I would like Red to update to 2 and Orange to update to 3. Is this possible?

Projects Form

答:
That is possible.

Use the AfterUpdate event of the textbox with Priority:

```<code>Private Sub Priority_AfterUpdate()

    Dim rst             As DAO.Recordset
    Dim lngId           As Long
    Dim lngPriorityNew  As Long
    Dim lngPriorityFix  As Long

    ' Save record.
    Me.Dirty = False

    ' Prepare form.
    DoCmd.Hourglass True
    Me.Repaint
    Me.Painting = False

    ' Current Id and priority.
    lngId = Me!Id.Value
    lngPriorityFix = Nz(Me!Priority.Value, 0)
    If lngPriorityFix <= 0 Then
        lngPriorityFix = 1
        Me!Priority.Value = lngPriorityFix
        Me.Dirty = False
    End If

    ' Rebuild priority list.
    Set rst = Me.RecordsetClone
    rst.MoveFirst
    While rst.EOF = False
        If rst!Id.Value <> lngId Then
            lngPriorityNew = lngPriorityNew + 1
            If lngPriorityNew = lngPriorityFix Then
                ' Move this record to next lower priority.
                lngPriorityNew = lngPriorityNew + 1
            End If
            If Nz(rst!Priority.Value, 0) = lngPriorityNew Then
                ' Priority hasn't changed for this record.
            Else
                ' Assign new priority.
                rst.Edit
                    rst!Priority.Value = lngPriorityNew
                rst.Update
            End If
        End If
        rst.MoveNext
    Wend

    ' Reorder form and relocate record.
    Me.Requery
    Set rst = Me.RecordsetClone
    rst.FindFirst "Id = " & lngId & ""
    Me.Bookmark = rst.Bookmark

    ' Present form.
    Me.Painting = True
    DoCmd.Hourglass False

    Set rst = Nothing

End Sub
</code>```

Body:
That is possible.

Use the AfterUpdate event of the textbox with Priority:

Private Sub Priority_AfterUpdate()

    Dim rst             As DAO.Recordset
    Dim lngId           As Long
    Dim lngPriorityNew  As Long
    Dim lngPriorityFix  As Long

    ' Save record.
    Me.Dirty = False

    ' Prepare form.
    DoCmd.Hourglass True
    Me.Repaint
    Me.Painting = False

    ' Current Id and priority.
    lngId = Me!Id.Value
    lngPriorityFix = Nz(Me!Priority.Value, 0)
    If lngPriorityFix <= 0 Then
        lngPriorityFix = 1
        Me!Priority.Value = lngPriorityFix
        Me.Dirty = False
    End If

    ' Rebuild priority list.
    Set rst = Me.RecordsetClone
    rst.MoveFirst
    While rst.EOF = False
        If rst!Id.Value <> lngId Then
            lngPriorityNew = lngPriorityNew + 1
            If lngPriorityNew = lngPriorityFix Then
                ' Move this record to next lower priority.
                lngPriorityNew = lngPriorityNew + 1
            End If
            If Nz(rst!Priority.Value, 0) = lngPriorityNew Then
                ' Priority hasn't changed for this record.
            Else
                ' Assign new priority.
                rst.Edit
                    rst!Priority.Value = lngPriorityNew
                rst.Update
            End If
        End If
        rst.MoveNext
    Wend

    ' Reorder form and relocate record.
    Me.Requery
    Set rst = Me.RecordsetClone
    rst.FindFirst "Id = " & lngId & ""
    Me.Bookmark = rst.Bookmark

    ' Present form.
    Me.Painting = True
    DoCmd.Hourglass False

    Set rst = Nothing

End Sub


问:
Prettify numbers to their closest number with zeros at the end in javascript
I have some chunks as following example:

```<code>// lowest and highest values of chunk arrays
[
    [0, 945710.3843175517],
    [945710.3843175517, 2268727.9557668166],
    [2268727.9557668166, 14965451.25314727],
    [14965451.25314727, 17890252.39415521],
    [17890252.39415521, 3501296406.880383]
]
</code>```

what I want to get from these chunks is something like this:

```<code>< 1.000.000
1.000.000 - 3.000.000
3.000.000 - 15.000.000
15.000.000 - 18.000.000
> 10.000.000
</code>```

I will use these new numbers as a legend of an informative map.

I use a function to achieve this goal named as roundClosestLegendNumber for each value.

All numbers are positive numbers and there is no maximum limitation.

```<code>roundClosestLegendNumber(5) \\ should give 10
roundClosestLegendNumber(94) \\ should give 100
roundClosestLegendNumber(125) \\ should give 200
roundClosestLegendNumber(945710.3843175517) \\ should give 1000000
roundClosestLegendNumber(14965451.25314727) \\ should give 15000000
roundClosestLegendNumber(17890252.39415521) \\ should give 18000000
// and so on
</code>```

答:
I changed the comparison for multiplier from 10 * to 100 * to get a precision of 2 digits before the series of 0s.

```<code>var roundClosestLegendNumber = function(number) {
    if(number < 10) {
        return number;
    }

    var multiplier = 10;
    while(number >= 100 * multiplier) {
        multiplier = 10 * multiplier;
    }

    count = 1;
    while(number > multiplier * count) {
        count++;
    }

    return multiplier * count;
}
</code>```

Body:
I have some chunks as following example:

// lowest and highest values of chunk arrays
[
    [0, 945710.3843175517],
    [945710.3843175517, 2268727.9557668166],
    [2268727.9557668166, 14965451.25314727],
    [14965451.25314727, 17890252.39415521],
    [17890252.39415521, 3501296406.880383]
]

what I want to get from these chunks is something like this:

< 1.000.000
1.000.000 - 3.000.000
3.000.000 - 15.000.000
15.000.000 - 18.000.000
> 10.000.000

I will use these new numbers as a legend of an informative map.

I use a function to achieve this goal named as roundClosestLegendNumber for each value.

All numbers are positive numbers and there is no maximum limitation.

roundClosestLegendNumber(5) \\ should give 10
roundClosestLegendNumber(94) \\ should give 100
roundClosestLegendNumber(125) \\ should give 200
roundClosestLegendNumber(945710.3843175517) \\ should give 1000000
roundClosestLegendNumber(14965451.25314727) \\ should give 15000000
roundClosestLegendNumber(17890252.39415521) \\ should give 18000000
// and so on

Body:
I changed the comparison for multiplier from 10 * to 100 * to get a precision of 2 digits before the series of 0s.

var roundClosestLegendNumber = function(number) {
    if(number < 10) {
        return number;
    }

    var multiplier = 10;
    while(number >= 100 * multiplier) {
        multiplier = 10 * multiplier;
    }

    count = 1;
    while(number > multiplier * count) {
        count++;
    }

    return multiplier * count;
}


问:
NSBundle.mainBundle().pathForResource returns nil
I am trying to write a simple IO wrapper for Swift.

To test this I have a file named "Test.txt" in my project root.

I have added this file to Build Phases within Build Bundle Resources, as suggested by everyone else who has had this problem.

I have implemented a very simple File class with one read function with the intent to output the contents of the file.

```<code>class File2{
    let resourceName: String
    let type: String
    let bundle = NSBundle.mainBundle()

    init(resourceName: String, type: String = "txt"){
        self.resourceName = resourceName
        self.type = type
        println(self.bundle)
    }

    func read(){
        let path = self.bundle.pathForResource("Test.txt", ofType: "txt") //Hard coded these in just to make sure Strings contained no whitespace
        println(path) //This returns nil...why?
        var error:NSError?
        //print(String(contentsOfFile:path!, encoding:NSUTF8StringEncoding, error: &error)!)
        //return String(contentsOfFile:path!, encoding:NSUTF8StringEncoding, error: &error)!
    }
}
</code>```

When I print the contents of the bundle I get a URI to a specific location on my filesystem, which I assume is the virtual location of the app in the simulator. Navigating to it reveals that it does indeed contain my "Test.txt" file.

Now all I want to do is get the path to that file.

I do this by calling: self.bundle.pathForResource("Test.txt", ofType: "txt")

This returns "nil"

Why? :)

答: Another reason for NSBundle.mainBundle().pathForResource returns nil is file is not properly added to the target. When you drag and drop the file in bundle, please make sure that "Add To Target" checkbox and "Copy items if needed" checkbox is selected.</p>

Body:
I am trying to write a simple IO wrapper for Swift.

To test this I have a file named "Test.txt" in my project root.

I have added this file to Build Phases within Build Bundle Resources, as suggested by everyone else who has had this problem.

I have implemented a very simple File class with one read function with the intent to output the contents of the file.

class File2{
    let resourceName: String
    let type: String
    let bundle = NSBundle.mainBundle()

    init(resourceName: String, type: String = "txt"){
        self.resourceName = resourceName
        self.type = type
        println(self.bundle)
    }

    func read(){
        let path = self.bundle.pathForResource("Test.txt", ofType: "txt") //Hard coded these in just to make sure Strings contained no whitespace
        println(path) //This returns nil...why?
        var error:NSError?
        //print(String(contentsOfFile:path!, encoding:NSUTF8StringEncoding, error: &error)!)
        //return String(contentsOfFile:path!, encoding:NSUTF8StringEncoding, error: &error)!
    }
}

When I print the contents of the bundle I get a URI to a specific location on my filesystem, which I assume is the virtual location of the app in the simulator. Navigating to it reveals that it does indeed contain my "Test.txt" file.

Now all I want to do is get the path to that file.

I do this by calling: self.bundle.pathForResource("Test.txt", ofType: "txt")

This returns "nil"

Why? :)


问:
Reading emoji from database
I'm working on a project with PHP/MYSQL. How do i store emojis in my database and read without alteration from PHP ?

My tables character set and collate are

CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci.

答: Actually I found the solution. Character set should be defined in database connection too.</p>

Title: Reading emoji from database


问:
Property 'autoTable' does not exist on type jsPDF
I am using angular2 and Node JS. I have installed jspdf and jspdf-autotable both modules using npm.
In angular-cli.json file, I have embedded the scripts:

```<code>"scripts": [
        "../node_modules/jspdf/dist/jspdf.min.js",
        "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
      ],
</code>```

In my component.ts file , I have imported these files as follows:

```<code> import * as jsPDF from 'jspdf';
 import * as autoTable from 'jspdf-autotable';
</code>```

I have also tried these lines to import jspdf-autotable

```<code>import { autoTable } from 'jspdf-autotable';
import 'jspdf-autotable';
</code>```

But nothing is working.

In function of component.ts file I am using sample code as follows:

```<code>var columns = ["ID", "Country", "Rank", "Capital"];
        var data = [
            [1, "Denmark", 7.526, "Copenhagen"],
            [2, "Switzerland",  7.509, "Bern"],
            [3, "Iceland", 7.501, "Reykjavík"],
            [4, "Norway", 7.498, "Oslo"],
            [5, "Finland", 7.413, "Helsinki"]
        ];
        var doc = new jsPDF();
        doc.autoTable(columns, data);
        doc.output("dataurlnewwindow");
</code>```

But now when I run the node command to start app then during compilation I am getting error as:

Property 'autoTable' does not exist on type 'jsPDF'.

Can any one please suggest?

答:
I got the answer:

No need to import jspdf or jspdf-autotable in component.ts file.

component.ts:

```<code>import { Component, Input, OnInit, Inject } from '@angular/core';
declare let jsPDF;
</code>```

In my case

```<code>var doc = new jsPDF('l', 'mm', [305, 250]);

var options1 = {
   padding: 50
};

doc.addHTML($('#riskdate_heading'),0,10,options1 ,() => {

   doc.addHTML($('#risktitle'),0,30,options1, () => {

     var res = doc.autoTableHtmlToJson(document.getElementById("riskTable"));

                var header = function(data) {
                    doc.setFontSize(18);
                    doc.setTextColor(40);
                    doc.setFontStyle('normal');
                };

                var riskoptions = {
                                    tableWidth: 'auto',
                                    addPageContent: header,
                                    margin: {  top: 10, horizontal: 7 },
                                    startY:  50,
                                    columnStyles: {0: {columnWidth: 'wrap'}}
                                };

                doc.autoTable(res.columns, res.data, riskoptions);

                doc.save("table.pdf");
        });
    });
</code>```

Body:
I am using angular2 and Node JS. I have installed jspdf and jspdf-autotable both modules using npm.
In angular-cli.json file, I have embedded the scripts:

"scripts": [
        "../node_modules/jspdf/dist/jspdf.min.js",
        "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
      ],

In my component.ts file , I have imported these files as follows:

 import * as jsPDF from 'jspdf';
 import * as autoTable from 'jspdf-autotable';

I have also tried these lines to import jspdf-autotable

import { autoTable } from 'jspdf-autotable';
import 'jspdf-autotable';

But nothing is working.

In function of component.ts file I am using sample code as follows:

var columns = ["ID", "Country", "Rank", "Capital"];
        var data = [
            [1, "Denmark", 7.526, "Copenhagen"],
            [2, "Switzerland",  7.509, "Bern"],
            [3, "Iceland", 7.501, "Reykjavík"],
            [4, "Norway", 7.498, "Oslo"],
            [5, "Finland", 7.413, "Helsinki"]
        ];
        var doc = new jsPDF();
        doc.autoTable(columns, data);
        doc.output("dataurlnewwindow");

But now when I run the node command to start app then during compilation I am getting error as:

Property 'autoTable' does not exist on type 'jsPDF'.

Can any one please suggest?

Body:
I got the answer:

No need to import jspdf or jspdf-autotable in component.ts file.

component.ts:

import { Component, Input, OnInit, Inject } from '@angular/core';
declare let jsPDF;

In my case

var doc = new jsPDF('l', 'mm', [305, 250]);

var options1 = {
   padding: 50
};

doc.addHTML($('#riskdate_heading'),0,10,options1 ,() => {

   doc.addHTML($('#risktitle'),0,30,options1, () => {

     var res = doc.autoTableHtmlToJson(document.getElementById("riskTable"));

                var header = function(data) {
                    doc.setFontSize(18);
                    doc.setTextColor(40);
                    doc.setFontStyle('normal');
                };

                var riskoptions = {
                                    tableWidth: 'auto',
                                    addPageContent: header,
                                    margin: {  top: 10, horizontal: 7 },
                                    startY:  50,
                                    columnStyles: {0: {columnWidth: 'wrap'}}
                                };

                doc.autoTable(res.columns, res.data, riskoptions);

                doc.save("table.pdf");
        });
    });


问:
Unable to open content: Custom Content Provider
I have two app, from another app I want to get all images,
suppose there is StickerProvider and MainActivity different app

StickerProvider is ContentProvider, MainActivity has ContentResolver

StickerProvider App has Asset Folder

Asset----> Stickers  ----------> a.png, b.png

```<code>public class StickerProvider extends ContentProvider {

    private final static String LOG_TAG = StickerProvider.class.getName();

    private static final String[] COLUMNS = {
            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        /**
         * Source: {@link FileProvider#query(Uri, String[], String, String[], String)} .
         */
        if (projection == null) {
            projection = COLUMNS;
        }

        String[] images = new String[0];
        try {
            images = getContext().getAssets().list("stickers");

            ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

            final MatrixCursor cursor = new MatrixCursor(new String[]{"path"}, 1);
            for (int i = 0; i < listImages.size(); i++) {
                cursor.addRow(new String[]{listImages.get(i)});
            }

            return cursor;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getType(Uri uri) {
        /**
         * Source: {@link FileProvider#getType(Uri)} .
         */
        final String file_name = uri.getLastPathSegment();
        final int lastDot = file_name.lastIndexOf('.');
        if (lastDot >= 0) {
            final String extension = file_name.substring(lastDot + 1);
            final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (mime != null) {
                return mime;
            }
        }

        return "image/png";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }

}
</code>```

It's menifest file is

```<code> <provider
            android:name="com.example.StickerProvider"
            android:authorities="com.example"
            android:exported="true"
            android:grantUriPermissions="true"
            android:label="StickerProvider" />
</code>```

Another app is MainActivity ------> From this I want to fetch all images of above apps

```<code>public class MainActivity extends AppCompatActivity {

    int i=0;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView ivOne = (ImageView)findViewById(R.id.ivOne);
        ImageView ivTwo = (ImageView)findViewById(R.id.ivTwo);

        try {
            ContentResolver resolver = getContentResolver();

            Cursor cursor =
                    resolver.query(Uri.parse("content://com.example/stickers"),
                            null,
                            null,
                            null,
                            null);
            if (cursor.moveToFirst()) {
                do {
                    String word = cursor.getString(0);
                    if(i==0){
                        ivOne.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }else if(i==1){
                        ivTwo.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }
                    // do something meaningful
                    Log.d(TAG, "onCreate: "+word);
                } while (cursor.moveToNext());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

When ever I start MainActivity App I am getting below exception

```<code>Unable to open content: content://com.example/a.png
             java.io.FileNotFoundException: No files supported by provider at content://com.example/a.png
                 at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:144)
                 at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                 at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1149)
                 at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:986)
                 at android.content.ContentResolver.openInputStream(ContentResolver.java:706)
                 at android.widget.ImageView.getDrawableFromUri(ImageView.java:900)
                 at android.widget.ImageView.resolveUri(ImageView.java:871)
                 at android.widget.ImageView.setImageURI(ImageView.java:490)
                 at android.support.v7.widget.AppCompatImageView.setImageURI(AppCompatImageView.java:124)
                 at com.pixr.photo.collage.MainActivity.onCreate(MainActivity.java:36)
                 at android.app.Activity.performCreate(Activity.java:6684)
                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2652)
                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
                 at android.app.ActivityThread.-wrap12(ActivityThread.java)
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
                 at android.os.Handler.dispatchMessage(Handler.java:102)
                 at android.os.Looper.loop(Looper.java:154)
                 at android.app.ActivityThread.main(ActivityThread.java:6236)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
</code>```

答: ic_launcher is related with app icon. There is no app icon. Check your icon in your drawable directory.</p>

Body:
I have two app, from another app I want to get all images,
suppose there is StickerProvider and MainActivity different app

StickerProvider is ContentProvider, MainActivity has ContentResolver

StickerProvider App has Asset Folder

Asset----> Stickers  ----------> a.png, b.png

public class StickerProvider extends ContentProvider {

    private final static String LOG_TAG = StickerProvider.class.getName();

    private static final String[] COLUMNS = {
            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        /**
         * Source: {@link FileProvider#query(Uri, String[], String, String[], String)} .
         */
        if (projection == null) {
            projection = COLUMNS;
        }

        String[] images = new String[0];
        try {
            images = getContext().getAssets().list("stickers");

            ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

            final MatrixCursor cursor = new MatrixCursor(new String[]{"path"}, 1);
            for (int i = 0; i < listImages.size(); i++) {
                cursor.addRow(new String[]{listImages.get(i)});
            }

            return cursor;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getType(Uri uri) {
        /**
         * Source: {@link FileProvider#getType(Uri)} .
         */
        final String file_name = uri.getLastPathSegment();
        final int lastDot = file_name.lastIndexOf('.');
        if (lastDot >= 0) {
            final String extension = file_name.substring(lastDot + 1);
            final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (mime != null) {
                return mime;
            }
        }

        return "image/png";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }

}

It's menifest file is

 <provider
            android:name="com.example.StickerProvider"
            android:authorities="com.example"
            android:exported="true"
            android:grantUriPermissions="true"
            android:label="StickerProvider" />

Another app is MainActivity ------> From this I want to fetch all images of above apps

public class MainActivity extends AppCompatActivity {

    int i=0;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView ivOne = (ImageView)findViewById(R.id.ivOne);
        ImageView ivTwo = (ImageView)findViewById(R.id.ivTwo);

        try {
            ContentResolver resolver = getContentResolver();

            Cursor cursor =
                    resolver.query(Uri.parse("content://com.example/stickers"),
                            null,
                            null,
                            null,
                            null);
            if (cursor.moveToFirst()) {
                do {
                    String word = cursor.getString(0);
                    if(i==0){
                        ivOne.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }else if(i==1){
                        ivTwo.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }
                    // do something meaningful
                    Log.d(TAG, "onCreate: "+word);
                } while (cursor.moveToNext());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

When ever I start MainActivity App I am getting below exception

Unable to open content: content://com.example/a.png
             java.io.FileNotFoundException: No files supported by provider at content://com.example/a.png
                 at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:144)
                 at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                 at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1149)
                 at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:986)
                 at android.content.ContentResolver.openInputStream(ContentResolver.java:706)
                 at android.widget.ImageView.getDrawableFromUri(ImageView.java:900)
                 at android.widget.ImageView.resolveUri(ImageView.java:871)
                 at android.widget.ImageView.setImageURI(ImageView.java:490)
                 at android.support.v7.widget.AppCompatImageView.setImageURI(AppCompatImageView.java:124)
                 at com.pixr.photo.collage.MainActivity.onCreate(MainActivity.java:36)
                 at android.app.Activity.performCreate(Activity.java:6684)
                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2652)
                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
                 at android.app.ActivityThread.-wrap12(ActivityThread.java)
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
                 at android.os.Handler.dispatchMessage(Handler.java:102)
                 at android.os.Looper.loop(Looper.java:154)
                 at android.app.ActivityThread.main(ActivityThread.java:6236)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)


问:
Unreleased Resource: Streams
Hi freinds i am getting a warning in the fortify report for the following code:

```<code> if (null != serverSocket) {

     OutputStream socketOutPutStream = serverSocket
       .getOutputStream();
     if (null != socketOutPutStream) {

      oos = new ObjectOutputStream(socketOutPutStream);
      if (null != oos) {
       int c;
       log.info("i am in Step 3 ooss " + oos);
       while ((c = mergedIS.read()) != -1) {
        oos.writeByte(c);
       }
      }
      log.info("i am in Step 4 ");

     }

    }
</code>```

in the catch block i have mentioned :

```<code>catch (UnknownHostException e) {
    //catch exception Vibhas added
    log.info("UnknownHostException occured");

   } catch (IOException e) {
    //catch exception Vibhas added
    log.info("IOException occured");

   } catch (Exception e) {
    //catch exception
    //log.info("error occured in copyFile in utils-->"+e.getMessage()+"file name is-->"+destiFileName);
   }finally{

    if (null != oos){

     oos.flush();
     oos.close();

      }
      catch (Exception e) {
     //catch exception
      }

    }
</code>```

Warning which i am getting in the fortify report is:

```<code>Abstract: The function copyFile() in ODCUtil.java sometimes fails to release a system resource
allocated by getOutputStream() on line 61.
Sink: ODCUtil.java:64 oos = new ObjectOutputStream(socketOutPutStream)()
62 if (null != socketOutPutStream) {
63
64 oos = new ObjectOutputStream(socketOutPutStream);
65 if (null != oos) {
66 int c;
</code>```

Complete Code:

```<code>public boolean copyFile(InputStream is, String destiFileName) {
    boolean flag = false;
    {
        InputStream mergedIS = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        ByteArrayInputStream str = null;
        try {

            //Step 1 : first get the input stream of file content and file name
            // then merge into one input stream
            log.info("i am in Step 1 ");
            log.info("destiFileName got-->" + destiFileName);
            log.info("is  got in coptFile function -->" + is);
            destiFileName = "@" + destiFileName + "@";
            log.info("destiFileName sending to server-->" + destiFileName);
            str = new ByteArrayInputStream(destiFileName.getBytes());
            log.info("The ByteArrayInputStream we got is  "
                    + str.toString());
            mergedIS = new SequenceInputStream(str, is);

            //Step 2 : Make a connection to server ie DB server
            log.info("i am in Step 2 ");
            String serverIP = "172.17.119.67";
            int serverPort = 1522;
            Socket serverSocket = new Socket(serverIP, serverPort);

            //Step 3 : We have to write the merged inputstream to outputstream of server, ie socket of server
            log.info("i am in Step 3 ");

            //added by vibhas to resolve Unreleased resource

            if (null != serverSocket) {

                OutputStream socketOutPutStream = serverSocket
                        .getOutputStream();
                if (null != socketOutPutStream) {

                    oos = new ObjectOutputStream(socketOutPutStream);
                    if (null != oos) {
                        int c;
                        log.info("i am in Step 3 ooss " + oos);
                        while ((c = mergedIS.read()) != -1) {
                            oos.writeByte(c);
                            socketOutPutStream.close();
                        }
                    }
                    log.info("i am in Step 4 ");

                }

            }

            //Step 4 : We have to get an acknowledgment from server that , server has copied the file properly
            //this is the same .

            if (true) {
                log.info("i am in Step 4 11");
                flag = true;
            }
        } catch (UnknownHostException e) {
            //catch exception Vibhas added
            log.info("UnknownHostException occured");

        } catch (IOException e) {
            //catch exception Vibhas added
            log.info("IOException occured");

        } catch (Exception e) {
            //catch exception
            //log.info("error occured in copyFile in utils-->"+e.getMessage()+"file name is-->"+destiFileName);
        } finally {
            try {
                if (null != str) {
                    str.close();
                }
                if (null != ois) {
                    ois.close();
                }
                if (null != mergedIS) {
                    mergedIS.close();
                }
                if (null != oos) {
                    oos.flush();
                    oos.close();
                }
            } catch (Exception e) {
                //catch exception
            }
        }
    }
    log.info("finally returned flag-->" + flag);
    return flag;
}
</code>```

答:
Not a nice try/catch structure. For one thing, ask yourself:
What would happen if str.close(); (at the beginning of your finally block) throws an exception?

Better see here: Java io ugly try-finally block

BTW: this is ugly; new will never return null.

```<code>  oos = new ObjectOutputStream(socketOutPutStream);
  if (null != oos) {
</code>```

BTW2: Are you sure you need an ObjectOutputStream? many people use that to write plain bytes, but that's not the idea (it's for serializing objects), and the original OutputStream would be enough for that.

ContentLicense: CC BY-SA 2.5

Title: Unreleased Resource: Streams

Body:
Hi freinds i am getting a warning in the fortify report for the following code:

 if (null != serverSocket) {

     OutputStream socketOutPutStream = serverSocket
       .getOutputStream();
     if (null != socketOutPutStream) {

      oos = new ObjectOutputStream(socketOutPutStream);
      if (null != oos) {
       int c;
       log.info("i am in Step 3 ooss " + oos);
       while ((c = mergedIS.read()) != -1) {
        oos.writeByte(c);
       }
      }
      log.info("i am in Step 4 ");

     }

    }

in the catch block i have mentioned :

catch (UnknownHostException e) {
    //catch exception Vibhas added
    log.info("UnknownHostException occured");

   } catch (IOException e) {
    //catch exception Vibhas added
    log.info("IOException occured");

   } catch (Exception e) {
    //catch exception
    //log.info("error occured in copyFile in utils-->"+e.getMessage()+"file name is-->"+destiFileName);
   }finally{

    if (null != oos){

     oos.flush();
     oos.close();

      }
      catch (Exception e) {
     //catch exception
      }

    }

Warning which i am getting in the fortify report is:

Abstract: The function copyFile() in ODCUtil.java sometimes fails to release a system resource
allocated by getOutputStream() on line 61.
Sink: ODCUtil.java:64 oos = new ObjectOutputStream(socketOutPutStream)()
62 if (null != socketOutPutStream) {
63
64 oos = new ObjectOutputStream(socketOutPutStream);
65 if (null != oos) {
66 int c;

Complete Code:

public boolean copyFile(InputStream is, String destiFileName) {
    boolean flag = false;
    {
        InputStream mergedIS = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        ByteArrayInputStream str = null;
        try {

            //Step 1 : first get the input stream of file content and file name
            // then merge into one input stream
            log.info("i am in Step 1 ");
            log.info("destiFileName got-->" + destiFileName);
            log.info("is  got in coptFile function -->" + is);
            destiFileName = "@" + destiFileName + "@";
            log.info("destiFileName sending to server-->" + destiFileName);
            str = new ByteArrayInputStream(destiFileName.getBytes());
            log.info("The ByteArrayInputStream we got is  "
                    + str.toString());
            mergedIS = new SequenceInputStream(str, is);

            //Step 2 : Make a connection to server ie DB server
            log.info("i am in Step 2 ");
            String serverIP = "172.17.119.67";
            int serverPort = 1522;
            Socket serverSocket = new Socket(serverIP, serverPort);

            //Step 3 : We have to write the merged inputstream to outputstream of server, ie socket of server
            log.info("i am in Step 3 ");

            //added by vibhas to resolve Unreleased resource

            if (null != serverSocket) {

                OutputStream socketOutPutStream = serverSocket
                        .getOutputStream();
                if (null != socketOutPutStream) {

                    oos = new ObjectOutputStream(socketOutPutStream);
                    if (null != oos) {
                        int c;
                        log.info("i am in Step 3 ooss " + oos);
                        while ((c = mergedIS.read()) != -1) {
                            oos.writeByte(c);
                            socketOutPutStream.close();
                        }
                    }
                    log.info("i am in Step 4 ");

                }

            }

            //Step 4 : We have to get an acknowledgment from server that , server has copied the file properly
            //this is the same .

            if (true) {
                log.info("i am in Step 4 11");
                flag = true;
            }
        } catch (UnknownHostException e) {
            //catch exception Vibhas added
            log.info("UnknownHostException occured");

        } catch (IOException e) {
            //catch exception Vibhas added
            log.info("IOException occured");

        } catch (Exception e) {
            //catch exception
            //log.info("error occured in copyFile in utils-->"+e.getMessage()+"file name is-->"+destiFileName);
        } finally {
            try {
                if (null != str) {
                    str.close();
                }
                if (null != ois) {
                    ois.close();
                }
                if (null != mergedIS) {
                    mergedIS.close();
                }
                if (null != oos) {
                    oos.flush();
                    oos.close();
                }
            } catch (Exception e) {
                //catch exception
            }
        }
    }
    log.info("finally returned flag-->" + flag);
    return flag;
}

Body:
Not a nice try/catch structure. For one thing, ask yourself:
What would happen if str.close(); (at the beginning of your finally block) throws an exception?

Better see here: Java io ugly try-finally block

BTW: this is ugly; new will never return null.

  oos = new ObjectOutputStream(socketOutPutStream);
  if (null != oos) {

BTW2: Are you sure you need an ObjectOutputStream? many people use that to write plain bytes, but that's not the idea (it's for serializing objects), and the original OutputStream would be enough for that.


问:
Save query string in cookie
On every request to my page i want to store the query string value in cookie. I mean when:

```<code>$_GET['id'] = 28 to get 28.
</code>```

Next time when:

```<code>$_GET['id'] is 36.
</code>```

I want to get 36 and add it to 28. How can I achieve that?

答:
```<code>$value=$_COOKIE['TestCookie'];
setcookie("TestCookie", $value+$_GET['value'], time()+(10 * 365 * 24 * 60 * 60));
</code>```

This will solve your issue. I set the expiration time of the cookie to be huge you can modify it.

Title: Save query string in cookie

Body:
On every request to my page i want to store the query string value in cookie. I mean when:

$_GET['id'] = 28 to get 28.

Next time when:

$_GET['id'] is 36.

I want to get 36 and add it to 28. How can I achieve that?

Body:
$value=$_COOKIE['TestCookie'];
setcookie("TestCookie", $value+$_GET['value'], time()+(10 * 365 * 24 * 60 * 60));

This will solve your issue. I set the expiration time of the cookie to be huge you can modify it.


问:
Remember-me doesn't work
I succeded to implement remember-me using spring boot security and store data in my table persistent_logins(username,series,token,last_used) and find it in coockies in my browser. my problem is when i delete the Jsessionid from my browser and refresh it the browser redirect to login page and don't still in the same page:

this is my SecurityConfigWeb.java:

```<code> @Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/sentEmail").permitAll();
    http.authorizeRequests().antMatchers("/contactUs").permitAll();
    http.authorizeRequests().antMatchers("/reset").permitAll();

    http.authorizeRequests().antMatchers(Constants.PATTERN1).permitAll();
    http.authorizeRequests().antMatchers(Constants.PATHPATTERN2).permitAll();
    http.authorizeRequests().antMatchers(Constants.PATHPATTERN3).permitAll().and().rememberMe().rememberMeServices(rememberMeServices());
    http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(Constants.URL_PATH).successHandler(this.authSuccess).failureHandler(this.authFailure).permitAll();
    http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(this.logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();

    http.csrf().disable();}
@Bean
public BCrypt bCryptPasswordEncoder() {
    return new BCrypt();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);

}

@Bean
public AbstractRememberMeServices rememberMeServices() {
    PersistentTokenBasedRememberMeServices rememberMeServices =
        new PersistentTokenBasedRememberMeServices("AppKey",userDetailsService(),persistentTokenRepository());
    rememberMeServices.setParameter("rememberMe");
    rememberMeServices.setAlwaysRemember(true);
    rememberMeServices.setCookieName("javasampleapproach-remember-me");
    rememberMeServices.setTokenValiditySeconds(24 * 60 * 60);
    return rememberMeServices;
}

@Bean
public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(dataSource);
    return tokenRepository;}
</code>```

and this is my login.html for remember-me:

```<code><div class="checkboxDiv">
                        <input type="checkbox" name="remember-me" value="true"> <label class="check" for="checkbox">Stay Logged In</label>
                    </div>
</code>```

Any help. Thanks in advance

答:
The problem is that you configured your security in several statements instead of making use of the fluent api.

```<code>http.authorizeRequests().antMatchers(Constants.PATHPATTERN3).permitAll().and().rememberMe().rememberMeServices(rememberMeServices());
</code>```

With this line you activated the 'remeber me' functionality but only for Constants.PATHPATTERN3. So if you want to activate remember me for all your endpoints your security configuration should be something like this.

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

   http.authorizeRequests()
    .antMatchers("/sentEmail", "/contactUs", "/reset", Constants.PATTERN1,Constants.PATHPATTERN2, Constants.PATHPATTERN3).permitAll()
    .anyRequest().authenticated()
    .and()
      .logout()
        .logoutSuccessHandler(this.logoutSuccess).permitAll()
    .and()
      .formLogin()
        .loginPage(Constants.URL_PATH)
        .successHandler(this.authSuccess)
        .failureHandler(this.authFailure).permitAll()
    .and()
      .rememberMe()
        .tokenRepository(persistentTokenRepository())
        .key("AppKey")
        .alwaysRemember(true)
        .rememberMeParameter("rememberMe")
        .rememberMeCookieName("javasampleapproach-remember-me")
        .tokenValiditySeconds(24 * 60 * 60)
    .and()
      csfr().disable();
}

@Bean
public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(dataSource);
    return tokenRepository;
}
</code>```

This way you configure everything in one go.

Title: Remember-me doesn't work

Body:
I succeded to implement remember-me using spring boot security and store data in my table persistent_logins(username,series,token,last_used) and find it in coockies in my browser. my problem is when i delete the Jsessionid from my browser and refresh it the browser redirect to login page and don't still in the same page:

this is my SecurityConfigWeb.java:

 @Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/sentEmail").permitAll();
    http.authorizeRequests().antMatchers("/contactUs").permitAll();
    http.authorizeRequests().antMatchers("/reset").permitAll();

    http.authorizeRequests().antMatchers(Constants.PATTERN1).permitAll();
    http.authorizeRequests().antMatchers(Constants.PATHPATTERN2).permitAll();
    http.authorizeRequests().antMatchers(Constants.PATHPATTERN3).permitAll().and().rememberMe().rememberMeServices(rememberMeServices());
    http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(Constants.URL_PATH).successHandler(this.authSuccess).failureHandler(this.authFailure).permitAll();
    http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(this.logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();

    http.csrf().disable();}
@Bean
public BCrypt bCryptPasswordEncoder() {
    return new BCrypt();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);

}

@Bean
public AbstractRememberMeServices rememberMeServices() {
    PersistentTokenBasedRememberMeServices rememberMeServices =
        new PersistentTokenBasedRememberMeServices("AppKey",userDetailsService(),persistentTokenRepository());
    rememberMeServices.setParameter("rememberMe");
    rememberMeServices.setAlwaysRemember(true);
    rememberMeServices.setCookieName("javasampleapproach-remember-me");
    rememberMeServices.setTokenValiditySeconds(24 * 60 * 60);
    return rememberMeServices;
}

@Bean
public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(dataSource);
    return tokenRepository;}

and this is my login.html for remember-me:

                        <input type="checkbox" name="remember-me" value="true"> Stay Logged In

Any help. Thanks in advance

Body:
The problem is that you configured your security in several statements instead of making use of the fluent api.

http.authorizeRequests().antMatchers(Constants.PATHPATTERN3).permitAll().and().rememberMe().rememberMeServices(rememberMeServices());

With this line you activated the 'remeber me' functionality but only for Constants.PATHPATTERN3. So if you want to activate remember me for all your endpoints your security configuration should be something like this.

@Override
protected void configure(HttpSecurity http) throws Exception {

   http.authorizeRequests()
    .antMatchers("/sentEmail", "/contactUs", "/reset", Constants.PATTERN1,Constants.PATHPATTERN2, Constants.PATHPATTERN3).permitAll()
    .anyRequest().authenticated()
    .and()
      .logout()
        .logoutSuccessHandler(this.logoutSuccess).permitAll()
    .and()
      .formLogin()
        .loginPage(Constants.URL_PATH)
        .successHandler(this.authSuccess)
        .failureHandler(this.authFailure).permitAll()
    .and()
      .rememberMe()
        .tokenRepository(persistentTokenRepository())
        .key("AppKey")
        .alwaysRemember(true)
        .rememberMeParameter("rememberMe")
        .rememberMeCookieName("javasampleapproach-remember-me")
        .tokenValiditySeconds(24 * 60 * 60)
    .and()
      csfr().disable();
}

@Bean
public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(dataSource);
    return tokenRepository;
}

This way you configure everything in one go.


问:
Java EE EIS Tier
I've been reading up on Java EE architecture, and have seen (in the Oracle docs at least) several references to a so-called EIS (enterprise information systems) tier which comprises the 3rd (data) tier of the Java EE architecture.

I understand that in a 3-tier system the database usually is the 3rd tier. Some times legacy systems are also placed on this tier because they also interact directly with the same database as the business middleware (2nd tier) and for one reason or another, they don't belong anywhere else.

My question is: what code (if any) belongs on the 3rd "EIS" tier? ORM code such as Hibernate classes and DAOs?

On the 2nd tier you have both systems and compiled Java running. For instance you might have a Tomcat server running a bunch of WARs that you wrote. I'm not "getting" the anology in the 3rd tier, where you have an RDBMS and (I guess?!?!) some code to interact with that RDBMS.

In sum, I guess I'm wondering what the standard/best practices are behind deploying code in the EIS tier, and what those deployments look like. Thanks in advance!

答:
The EIS tier is a conceptional tier that is included as a jar file inside an application.

It mainly consists of resource adapters that are often provided by the corresponding EIS manufacturers.

Your java beans can use these adapters to access data and services of an EIS.

That's why you typically don't deploy something into the EIS tier.

The tier is "just there" whenever you use an EIS resource adapter.

Same concept as with the data access layer (-> orm framworks):

You don't write it.

You don't put anything in it.

You simply use it.

Title: Java EE EIS Tier