问:
combine 8 tables into 1
I've got 8 diffrent tables that looks like this

```<code> date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:30   15    0    6    X
3-4-2017 13:45   12    0    2    X

 date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    Y
</code>```

I want to visualize in Power BI on a map the ID states wher it should be maped. But for this visualisation my data should look like this.

```<code>date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    X
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    X
3-4-2017 13:45   12    0    2    Y
</code>```

I have tested this on a small part but have to be able to do this on 3 to 4 years. I'd rather do this in Excel or BI itself but R is a option.

答:
In R, an efficient way to bind multiple data frames sharing same columns, is dplyr::bind_rows(). For instance for 3 tables:

```<code>bind_table <- bind_rows(table1, table2, table3)
</code>```

Title: combine 8 tables into 1

Body:
I've got 8 diffrent tables that looks like this

 date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:30   15    0    6    X
3-4-2017 13:45   12    0    2    X

 date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    Y

I want to visualize in Power BI on a map the ID states wher it should be maped. But for this visualisation my data should look like this.

date/time        v    t    o    ID
3-4-2017 13:15   10    1    8    X
3-4-2017 13:15   10    1    8    Y
3-4-2017 13:30   15    0    6    X
3-4-2017 13:30   15    0    6    Y
3-4-2017 13:45   12    0    2    X
3-4-2017 13:45   12    0    2    Y

I have tested this on a small part but have to be able to do this on 3 to 4 years. I'd rather do this in Excel or BI itself but R is a option.

Body:
In R, an efficient way to bind multiple data frames sharing same columns, is dplyr::bind_rows(). For instance for 3 tables:

bind_table <- bind_rows(table1, table2, table3)


来源: stackexchange

问:
Webpage source not completely read by HTTPClient
I am able to download smaller JSON responses with the following code just fine:

    public String getHTTPData() {

        HttpURLConnection httpURLConnection = null;

        InputStream inputStream = null;

        try {

            httpURLConnection = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            StringBuffer stringBuffer = new StringBuffer();
            inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;

            while ((line = bufferedReader.readLine()) != null) {

                stringBuffer.append(line + "\n");
            }

            inputStream.close();

            httpURLConnection.disconnect();

        } catch (Throwable t) {

            t.printStackTrace();

        } finally {

            try {

                inputStream.close();

                httpURLConnection.disconnect();

            } catch (Throwable t) {

                t.printStackTrace();
            }
        }

        return null;
    }
```

but when I couldn't find a certain API (Chinese dictionary API), I thought I might as well parse the HTML source code for the data I need. But I only seem to get the first 100 lines of the source code. I must be missing something very simple like a 'maxLength' HTTP parameter or a timeout. Didn't find anything in SO, also tried the code suggested by Google here and ran into the same issue. I'm not sure how to further debug this, I see that the inputstream dries up and returns '-1' (tried different maxLength chunks in 'readStream' and got smaller blocks but still dried up in the end), so I assume it's the URLConnection not delivering. Or is it maybe my inputstream code that's faulty ? btw, this is an https URL, but since I do get some initial data, I don't think it's a protocol issue (hope I summarized this somewhat intelligently ...)

答:
It's a good practice to run your code in a thread and not on the main thread.
Also please add this to your request:

```<code>httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
</code>```

Then check the response code :

```<code>if (responseCode == HttpURLConnection.HTTP_OK) {
}
</code>```

Do not forget to add the Internet permission to your manifest file:

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am able to download smaller JSON responses with the following code just fine:

    public String getHTTPData() {

        HttpURLConnection httpURLConnection = null;

        InputStream inputStream = null;

        try {

            httpURLConnection = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            StringBuffer stringBuffer = new StringBuffer();
            inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;

            while ((line = bufferedReader.readLine()) != null) {

                stringBuffer.append(line + "\n");
            }

            inputStream.close();

            httpURLConnection.disconnect();

        } catch (Throwable t) {

            t.printStackTrace();

        } finally {

            try {

                inputStream.close();

                httpURLConnection.disconnect();

            } catch (Throwable t) {

                t.printStackTrace();
            }
        }

        return null;
    }

but when I couldn't find a certain API (Chinese dictionary API), I thought I might as well parse the HTML source code for the data I need. But I only seem to get the first 100 lines of the source code. I must be missing something very simple like a 'maxLength' HTTP parameter or a timeout. Didn't find anything in SO, also tried the code suggested by Google here and ran into the same issue. I'm not sure how to further debug this, I see that the inputstream dries up and returns '-1' (tried different maxLength chunks in 'readStream' and got smaller blocks but still dried up in the end), so I assume it's the URLConnection not delivering. Or is it maybe my inputstream code that's faulty ? btw, this is an https URL, but since I do get some initial data, I don't think it's a protocol issue (hope I summarized this somewhat intelligently ...)

Body:
It's a good practice to run your code in a thread and not on the main thread.
Also please add this to your request:

httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);

Then check the response code :

if (responseCode == HttpURLConnection.HTTP_OK) {
}

Do not forget to add the Internet permission to your manifest file:

<uses-permission android:name="android.permission.INTERNET" />


问:
How to change URL in core PHP
How to change URL in core PHP? Please let me know how to do this

http://localhost/files/rajfireworks/product_details?pro_id=2
```

<p>to</p>

<pre class="lang-none prettyprint-override"><code>http://localhost/files/rajfireworks/product_details/productname
</code>```

答:
This can help:

```<code><?php
if(!empty($_GET['pro_id'])) {
  header("Location: /files/rajfireworks/product_details/productname");
}
?>
</code>```

Depends on product_id number - you can extend your conditions.

Title: How to change URL in core PHP

Body:
How to change URL in core PHP? Please let me know how to do this

http://localhost/files/rajfireworks/product_details?pro_id=2

to

http://localhost/files/rajfireworks/product_details/productname

Body:
This can help:

<?php
if(!empty($_GET['pro_id'])) {
  header("Location: /files/rajfireworks/product_details/productname");
}
?>

Depends on product_id number - you can extend your conditions.


问:
iPhone application crash on launch
We are receiving a crash log from iTunes connect that is a little strange.

We were preivously having problems with our app taking to long to return from ApplicationDidFinishLaunching. This was caused by doing a too much work inside of applicationDidFinishLaunching and we exceeded the 20 second time out on slower devices.

To fix this we moved all of our setup code out of ApplicationDidFinishLaunching and moved it into a special secondaryLoadingController. On top of that we moved the setup code inside of that controller to a separate thread.

However, we are still seeing crash logs that say our app failed to launch in time even though the crash log shows a call to [UIApplication _reportAppLaunchFinished]. To me, this indicates that the app has finished launching and we should be free to take as long as we want to run our setup code.  Below is the crash log.

Thanks for any help you can offer.

```<code>Incident Identifier: 429360D5-6B02-49BE-9A0F-164DC521BE36
Hardware Model:      iPod2,1
Process:         XYZ [357]
Path:            /var/mobile/Applications/D5038F26-CC5B-48E5-824E-090163B5C0C4/XYZ.app/XYZ
Identifier:      XYZ
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-09-28 13:35:25.138 -0700
OS Version:      iPhone OS 4.0 (8A293)
Report Version:  104

Exception Type:  00000020
Exception Codes: 0x8badf00d
Highlighted Thread:  0

Application Specific Information:
com.xyz.xyz failed to launch in time
elapsed total CPU time (seconds): 20.180 (user 15.910, system 4.270), 100% CPU
elapsed application CPU time (seconds): 10.960, 54% CPU

Thread 0:
0   libobjc.A.dylib                   0x3523a50c objc_msgSend + 44
1   CoreFoundation                    0x363bf568 -[__NSArrayM addObject:]
2   XYZ                        0x0000a152 -[Database fetchDrinks:] + 290
3   XYZ                        0x0000677c -[Database getAllDrinks] + 136
4   XYZ                        0x0003a164 -[SecondaryLoadingViewController viewDidLoad] + 208
5   UIKit                             0x323e582c -[UIViewController view]
6   UIKit                             0x323f9628 -[UIViewController viewControllerForRotation]
7   UIKit                             0x323f9574 -[UIViewController _visibleView]
8   UIKit                             0x323f94fc -[UIViewController rotatingContentViewForWindow:]
9   UIKit                             0x3249a514 -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:]
10  UIKit                             0x32499314 -[UIWindow _setRotatableClient:toOrientation:duration:force:]
11  UIKit                             0x32497d78 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]
12  UIKit                             0x32497534 -[UIViewController presentModalViewController:withTransition:]
13  UIKit                             0x324977fc -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
14  UIKit                             0x324977c0 -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
15  UIKit                             0x32496e00 -[UIViewController presentModalViewController:withTransition:]
16  UIKit                             0x3249699c -[UIViewController presentModalViewController:animated:]
17  XYZ                        0x000044a2 -[HomeViewController viewDidLoad] + 82
18  UIKit                             0x323e582c -[UIViewController view]
19  UIKit                             0x323fd68c -[UIViewController contentScrollView]
20  UIKit                             0x323fd4ac -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:]
21  UIKit                             0x323fd358 -[UINavigationController _layoutViewController:]
22  UIKit                             0x323fccb8 -[UINavigationController _startTransition:fromViewController:toViewController:]
23  UIKit                             0x323fca1c -[UINavigationController _startDeferredTransitionIfNeeded]
24  UIKit                             0x323fc90c -[UINavigationController viewWillLayoutSubviews]
25  UIKit                             0x323fc43c -[UILayoutContainerView layoutSubviews]
26  UIKit                             0x32370ab0 -[UIView(CALayerDelegate) _layoutSublayersOfLayer:]
27  CoreFoundation                    0x363c85ba -[NSObject(NSObject) performSelector:withObject:]
28  QuartzCore                        0x30c8c61c 0x30c82000 + 42524
29  QuartzCore                        0x30c8c2a4 0x30c82000 + 41636
30  QuartzCore                        0x30c8bbb0 0x30c82000 + 39856
31  QuartzCore                        0x30c8b7d8 0x30c82000 + 38872
32  QuartzCore                        0x30c8b684 0x30c82000 + 38532
33  UIKit                             0x323d99d4 -[UIApplication _reportAppLaunchFinished]
34  UIKit                             0x3251d77c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
35  UIKit                             0x323d87b8 -[UIApplication handleEvent:withNewEvent:]
36  UIKit                             0x323d7eb4 -[UIApplication sendEvent:]
37  UIKit                             0x323d77e8 _UIApplicationHandleEvent
38  GraphicsServices                  0x33c4dedc PurpleEventCallback
39  CoreFoundation                    0x364142ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
40  CoreFoundation                    0x364161d6 __CFRunLoopDoSource1
41  CoreFoundation                    0x3641718e __CFRunLoopRun
42  CoreFoundation                    0x363be0bc CFRunLoopRunSpecific
43  CoreFoundation                    0x363bdfca CFRunLoopRunInMode
44  UIKit                             0x32363b18 -[UIApplication _run]
45  UIKit                             0x32361fb8 UIApplicationMain
46  XYZ                        0x00002b20 main + 36
47  XYZ                        0x00002af0 start + 32
</code>```

UPDATE
I am attempting to run the time consuming import code (only happens on an application update) on a separate thread. I am even updating the GUI using an AlertView with an embedded progress bar so the user knows something is still happening. During our testing process this works fine. Below is the thread code that seems to not be working. The crash log seems to indicate that all work is being done on the main thread.

```<code>    if ([database appDidUpdate] == YES) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    dbImportThread = [[NSThread alloc] initWithTarget:self selector:@selector(import) object:nil];
    [dbImportThread start];
    [pool release];

- (void)import {
 //do importing work and update the gui with the progress
}
</code>```

答: seems everything is performing on the main thread... (am I right?) If this is the case it may stuck your UI. Did you consider to load your database information on another thread and update your GUI as you get the data? second, you can measure the performance of each chunk of code in time-cosuming relation and see what exactly takes it so much time to load. </p>

ContentLicense: CC BY-SA 2.5

Title: iPhone application crash on launch

Body:
We are receiving a crash log from iTunes connect that is a little strange.

We were preivously having problems with our app taking to long to return from ApplicationDidFinishLaunching. This was caused by doing a too much work inside of applicationDidFinishLaunching and we exceeded the 20 second time out on slower devices.

To fix this we moved all of our setup code out of ApplicationDidFinishLaunching and moved it into a special secondaryLoadingController. On top of that we moved the setup code inside of that controller to a separate thread.

However, we are still seeing crash logs that say our app failed to launch in time even though the crash log shows a call to [UIApplication _reportAppLaunchFinished]. To me, this indicates that the app has finished launching and we should be free to take as long as we want to run our setup code.  Below is the crash log.

Thanks for any help you can offer.

Incident Identifier: 429360D5-6B02-49BE-9A0F-164DC521BE36
Hardware Model:      iPod2,1
Process:         XYZ [357]
Path:            /var/mobile/Applications/D5038F26-CC5B-48E5-824E-090163B5C0C4/XYZ.app/XYZ
Identifier:      XYZ
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-09-28 13:35:25.138 -0700
OS Version:      iPhone OS 4.0 (8A293)
Report Version:  104

Exception Type:  00000020
Exception Codes: 0x8badf00d
Highlighted Thread:  0

Application Specific Information:
com.xyz.xyz failed to launch in time
elapsed total CPU time (seconds): 20.180 (user 15.910, system 4.270), 100% CPU
elapsed application CPU time (seconds): 10.960, 54% CPU

Thread 0:
0   libobjc.A.dylib                   0x3523a50c objc_msgSend + 44
1   CoreFoundation                    0x363bf568 -[__NSArrayM addObject:]
2   XYZ                        0x0000a152 -[Database fetchDrinks:] + 290
3   XYZ                        0x0000677c -[Database getAllDrinks] + 136
4   XYZ                        0x0003a164 -[SecondaryLoadingViewController viewDidLoad] + 208
5   UIKit                             0x323e582c -[UIViewController view]
6   UIKit                             0x323f9628 -[UIViewController viewControllerForRotation]
7   UIKit                             0x323f9574 -[UIViewController _visibleView]
8   UIKit                             0x323f94fc -[UIViewController rotatingContentViewForWindow:]
9   UIKit                             0x3249a514 -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:]
10  UIKit                             0x32499314 -[UIWindow _setRotatableClient:toOrientation:duration:force:]
11  UIKit                             0x32497d78 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]
12  UIKit                             0x32497534 -[UIViewController presentModalViewController:withTransition:]
13  UIKit                             0x324977fc -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
14  UIKit                             0x324977c0 -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
15  UIKit                             0x32496e00 -[UIViewController presentModalViewController:withTransition:]
16  UIKit                             0x3249699c -[UIViewController presentModalViewController:animated:]
17  XYZ                        0x000044a2 -[HomeViewController viewDidLoad] + 82
18  UIKit                             0x323e582c -[UIViewController view]
19  UIKit                             0x323fd68c -[UIViewController contentScrollView]
20  UIKit                             0x323fd4ac -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:]
21  UIKit                             0x323fd358 -[UINavigationController _layoutViewController:]
22  UIKit                             0x323fccb8 -[UINavigationController _startTransition:fromViewController:toViewController:]
23  UIKit                             0x323fca1c -[UINavigationController _startDeferredTransitionIfNeeded]
24  UIKit                             0x323fc90c -[UINavigationController viewWillLayoutSubviews]
25  UIKit                             0x323fc43c -[UILayoutContainerView layoutSubviews]
26  UIKit                             0x32370ab0 -[UIView(CALayerDelegate) _layoutSublayersOfLayer:]
27  CoreFoundation                    0x363c85ba -[NSObject(NSObject) performSelector:withObject:]
28  QuartzCore                        0x30c8c61c 0x30c82000 + 42524
29  QuartzCore                        0x30c8c2a4 0x30c82000 + 41636
30  QuartzCore                        0x30c8bbb0 0x30c82000 + 39856
31  QuartzCore                        0x30c8b7d8 0x30c82000 + 38872
32  QuartzCore                        0x30c8b684 0x30c82000 + 38532
33  UIKit                             0x323d99d4 -[UIApplication _reportAppLaunchFinished]
34  UIKit                             0x3251d77c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
35  UIKit                             0x323d87b8 -[UIApplication handleEvent:withNewEvent:]
36  UIKit                             0x323d7eb4 -[UIApplication sendEvent:]
37  UIKit                             0x323d77e8 _UIApplicationHandleEvent
38  GraphicsServices                  0x33c4dedc PurpleEventCallback
39  CoreFoundation                    0x364142ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
40  CoreFoundation                    0x364161d6 __CFRunLoopDoSource1
41  CoreFoundation                    0x3641718e __CFRunLoopRun
42  CoreFoundation                    0x363be0bc CFRunLoopRunSpecific
43  CoreFoundation                    0x363bdfca CFRunLoopRunInMode
44  UIKit                             0x32363b18 -[UIApplication _run]
45  UIKit                             0x32361fb8 UIApplicationMain
46  XYZ                        0x00002b20 main + 36
47  XYZ                        0x00002af0 start + 32

UPDATE
I am attempting to run the time consuming import code (only happens on an application update) on a separate thread. I am even updating the GUI using an AlertView with an embedded progress bar so the user knows something is still happening. During our testing process this works fine. Below is the thread code that seems to not be working. The crash log seems to indicate that all work is being done on the main thread.

    if ([database appDidUpdate] == YES) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    dbImportThread = [[NSThread alloc] initWithTarget:self selector:@selector(import) object:nil];
    [dbImportThread start];
    [pool release];

- (void)import {
 //do importing work and update the gui with the progress
}


问:
Aligning Text / Icon Within Button
I've tried many different things on the web and from SO and again can't seem to get this to work. First time I've been changing / styling my buttons and they're driving me mad! So I have a left floated button on the same line as my right floated button now. I'd like to see if I can have the icon to the left of the text on the left button and the right of the text on the right button. Like this:

<- Last Page //////////////////////////////////////////////// Next Page ->

```<code><span align="right">
<ul class="actions">
<li id="leftbutton"><a href="tfn.html" class="button special icon fa-arrow-left">TFN</a></li>
<li id="rightbutton"><a href="medical-indemnity-and-insurance.html" class="button special icon fa-arrow-right">Indemnity & Insurance</a></li>
</ul>
</span>
</code>```

Fiddle

For some reason on the above fiddle it doesn't seem to be showing the font awesome arrows?

Thank you so much!

S.

答:
Just insert te font-awsome icons whit the  element:

```<code><span align="right">
  <ul class="actions">
     <li id="leftbutton"><a href="tfn.html" class="button special icon"><i class="fa fa-arrow-left" aria-hidden="true"></i> TFN</a></li>
     <li id="rightbutton"><a href="medical-indemnity-and-insurance.html" class="button special icon ">Indemnity & Insurance <i class="fa fa-arrow-right" aria-hidden="true"></i></a></li>
  </ul>
</span>
</code>```

Here is an updated fiddle: https://jsfiddle.net/n6bpvdf5/1/

Title: Aligning Text / Icon Within Button

Body:
I've tried many different things on the web and from SO and again can't seem to get this to work. First time I've been changing / styling my buttons and they're driving me mad! So I have a left floated button on the same line as my right floated button now. I'd like to see if I can have the icon to the left of the text on the left button and the right of the text on the right button. Like this:

<- Last Page //////////////////////////////////////////////// Next Page ->

TFN

Indemnity & Insurance

Fiddle

For some reason on the above fiddle it doesn't seem to be showing the font awesome arrows?

Thank you so much!

S.

Body:
Just insert te font-awsome icons whit the <i> element:

<span align="right">
  <ul class="actions">
     <li id="leftbutton"><a href="tfn.html" class="button special icon"><i class="fa fa-arrow-left" aria-hidden="true"></i> TFN</a></li>
     <li id="rightbutton"><a href="medical-indemnity-and-insurance.html" class="button special icon ">Indemnity & Insurance <i class="fa fa-arrow-right" aria-hidden="true"></i></a></li>
  </ul>
</span>

Here is an updated fiddle: https://jsfiddle.net/n6bpvdf5/1/


问:
How to avoid overflow in realloc?
One can safely allocate x elements of size y in C by using calloc(x, y) and calloc() will take care of the multiplication x*y.

However realloc() for example only takes the new size as parameter and I was wondering how I could safely realloc x*y bytes using realloc().

What if x*y doesn't fit in size_t? How does calloc() handle this?

答:
If x * y overflows size_t, realloc will try to allocate that value which was overflown:

```<code>bytes = (x * y) % 2^(sizeof(size_t) * 8)
</code>```

So realloc will "see" bytes amount of bytes. It does not take care of anything.

Title: How to avoid overflow in realloc?

Body:
If x * y overflows size_t, realloc will try to allocate that value which was overflown:

bytes = (x * y) % 2^(sizeof(size_t) * 8)

So realloc will "see" bytes amount of bytes. It does not take care of anything.


问:
Query to retrive rows with words starting and ending with same character in sql server
I need to write a SQL Server query to filter the rows with sentences containing first and last character of the sentence being same like

Thanks in advance.

答:
like this ?

```<code>select *
from   yourTable c
where  substring(c.yourColumn, 1, 1) = substring(c.yourColumn, len(c.yourColumn), 1)
</code>```

If your sql server is case sensitive (not by default) you need to put the substrings inside lower() functions.

Body:
like this ?

select *
from   yourTable c
where  substring(c.yourColumn, 1, 1) = substring(c.yourColumn, len(c.yourColumn), 1)

If your sql server is case sensitive (not by default) you need to put the substrings inside lower() functions.


问:
monitor and increase android performance of android applications
can anyone advice me some tools that can help me monitor the performance of my application ?

and tips that also can help me increasing the memory and gui usage of my application ?

some users complain that the application is too slow and I can not reproduce this issue on my device.

答:
Read official guideline about Android Monitor Overview.

Android Monitor helps you to profile the performance of your apps so
  you can optimize, debug, and improve them.

Android Monitor provides a Memory Monitor so you can more easily monitor app performance and memory usage to find deallocated objects, locate memory leaks, and track the amount of memory the connected device is using. The Memory Monitor reports how your app allocates memory and helps you to visualize the memory your app uses.

Visit Also Best Practices for Performance.


问:
How to get ActionParameters in OnResultExecuted action filter
I want action parameters in the above action filter method. please help me

```<code>Public Overrides Sub OnResultExecuted(filterContext As ResultExecutedContext)
   Dim actionParameter = filterContext.ActionParameters(parameterName)
 End Sub

 var params={};
 params.Comments=getvaluebyid("TxtComment");
 $.ajax({
         type: "POST",
         url: '/ControllerName/ActionName',
         async: true,
         data: $.toJSON(params),
         dataType: "json",
         contentType: 'application/json; charset=utf-8',
</code>```

答:
You can get Action parameters by doing this:

```<code>    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
       var controllerActionDescriptor = filterContext.ActionDescriptor as System.Web.Mvc.ReflectedActionDescriptor;
       ParameterDescriptor[]pdes= controllerActionDescriptor.GetParameters();
       foreach (var item in pdes)
       {
           var parameterName = item.ParameterName;
           var parameterType=item.ParameterType;
       }
    }
</code>```

For getting values, you can do this:

```<code>HttpContext.Current.Request.QueryString["Id"]// where "Id" is the key, you can use index here too.
</code>```

Hope it helps!

Body:
I want action parameters in the above action filter method. please help me

Public Overrides Sub OnResultExecuted(filterContext As ResultExecutedContext)
   Dim actionParameter = filterContext.ActionParameters(parameterName)
 End Sub

 var params={};
 params.Comments=getvaluebyid("TxtComment");
 $.ajax({
         type: "POST",
         url: '/ControllerName/ActionName',
         async: true,
         data: $.toJSON(params),
         dataType: "json",
         contentType: 'application/json; charset=utf-8',

Body:
You can get Action parameters by doing this:

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
       var controllerActionDescriptor = filterContext.ActionDescriptor as System.Web.Mvc.ReflectedActionDescriptor;
       ParameterDescriptor[]pdes= controllerActionDescriptor.GetParameters();
       foreach (var item in pdes)
       {
           var parameterName = item.ParameterName;
           var parameterType=item.ParameterType;
       }
    }

For getting values, you can do this:

HttpContext.Current.Request.QueryString["Id"]// where "Id" is the key, you can use index here too.

Hope it helps!


问:
c# compare byte arrays
I'm trying to compare 2 byte array using pointers.
I treat the byte arrays as int pointer to run things faster(compare 4 bytes together).

```<code>    public static bool DoBuffersEqual(byte[] first, byte[] second)
    {
        unsafe
        {
            fixed (byte* pfirst = first, psecond = second)
            {
                int* intfirst = (int*)pfirst;
                int* intsecond = (int*)psecond;

                for (int i = 0; i < first.Length / 4; i++)
                {
                    if ((intfirst + i) != (intsecond + i))
                        return false;
                }
            }
        }
        return true;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        byte[] arr1 = new byte[4000];
        byte[] arr2 = new byte[4000];
        for (int i = 0; i < arr1.Length; i++)
        {
            arr1[i] = 100;
            arr2[i] = 100;
        }
        bool res = DoBuffersEqual(arr1, arr2);
        Console.WriteLine(res);
    }
</code>```

For some reason i'm getting  False result after calling this function...

Does anybody have any idea what's wrong here?

Thanks in advance!

答:
As other comments have already stated, the problem is that you are comparing pointers, not values. The correct code should be:

```<code>if (*(intfirst + i) != *(intsecond + i))
</code>```

But I'd like to point out a deeper issues in your code.

If the input byte arrays have lengths that don't align with 4
(first.Length % 4 != 0) you will get false positives because you'll
be essentially swallowing all misaligned items:

```<code>{1, 2, 3, 4, 5}
{1, 2, 3, 4, 7}
</code>```

Will return true when they are obviously not the same.

You should be checking, before anything else, that both
arrays have the same length and bailing out fast if they don't. You'll
run into all kind of issues otherwise.

```<code>{1, 2, 3, 0}
{1, 2, 3}
</code>```

Will also return true when it shoudn't.

Title: c# compare byte arrays

Body:
I'm trying to compare 2 byte array using pointers.
I treat the byte arrays as int pointer to run things faster(compare 4 bytes together).

    public static bool DoBuffersEqual(byte[] first, byte[] second)
    {
        unsafe
        {
            fixed (byte* pfirst = first, psecond = second)
            {
                int* intfirst = (int*)pfirst;
                int* intsecond = (int*)psecond;

                for (int i = 0; i < first.Length / 4; i++)
                {
                    if ((intfirst + i) != (intsecond + i))
                        return false;
                }
            }
        }
        return true;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        byte[] arr1 = new byte[4000];
        byte[] arr2 = new byte[4000];
        for (int i = 0; i < arr1.Length; i++)
        {
            arr1[i] = 100;
            arr2[i] = 100;
        }
        bool res = DoBuffersEqual(arr1, arr2);
        Console.WriteLine(res);
    }

For some reason i'm getting  False result after calling this function...

Does anybody have any idea what's wrong here?

Thanks in advance!

Body:
As other comments have already stated, the problem is that you are comparing pointers, not values. The correct code should be:

if (*(intfirst + i) != *(intsecond + i))

But I'd like to point out a deeper issues in your code.

If the input byte arrays have lengths that don't align with 4
(first.Length % 4 != 0) you will get false positives because you'll
be essentially swallowing all misaligned items:

{1, 2, 3, 4, 5}
{1, 2, 3, 4, 7}

Will return true when they are obviously not the same.

You should be checking, before anything else, that both
arrays have the same length and bailing out fast if they don't. You'll
run into all kind of issues otherwise.

{1, 2, 3, 0}
{1, 2, 3}

Will also return true when it shoudn't.


问:
Android Studio libGDX does not display errors messages when external phone is plug in
Whenever my app throw the runtime error and using external phone plug in  (Huawei Honor 7) Ive go the error looks like this

E/Surface: getSlotFromBufferLocked: unknown buffer: 0x557d1334f0

Then when I tested it on emulator Ive got normal stack trace error. In core Android develpoment everything work fine, the error are displayed correctly .

答:
This is a bug in marshmallow and issue resolved in Android 6.0.1

Error is printed whenever switch between applications (doesn't matter which) or exit out of them, and when activities are destroyed.

You can track this issue here


问:
Enable pointer-events when click on an iframe embedded map
I have a map in an iframe tag and works pretty fine. All that I want is when click on frame the pointer-events enable again and interact (zoom, click on markers etc)

```<code><iframe id="map" src="map.html"></iframe>
</code>```

In my css file I have the following style

```<code>#map {
        margin-left:0px;
        width:107%;
        pointer-events: none;
    }
</code>```

The pointer events works and I can't interact with the map.
The thing I want is when click on map the pointer-events becomes 'auto'

I have tried this code of javascript and nothing happens. Any ideas?

```<code><script>
   $(document).ready(function() {
      $('#map').css('pointer-events', 'none');

      $('#map').click(function() {
        $(this).css('pointer-events', 'auto');
      });
   });
</script>
</code>```

Thanks in advance

答:
you cannot get click event of an element which have "pointer-event:none". what you should do is just add that  inside a div.

for example,

```<code><div class="map-wrapper"><iframe id="map"></iframe></div>
</code>```

then, call your script as

```<code>    <script>
       $(document).ready(function() {
          $('#map').css('pointer-events', 'none');
          $('.map-wrapper').click(function() {
            $(this).find('#map').css('pointer-events', 'auto'); // just $('#map') also fine
          });
          $('.map-wrapper').mouseleave(function() {
            $(this).find('#map').css('pointer-events', 'none'); // making it not clickable when it's not in focus
          });

       });
    </script>
</code>```

hope this helps!

Body:
I have a map in an iframe tag and works pretty fine. All that I want is when click on frame the pointer-events enable again and interact (zoom, click on markers etc)

In my css file I have the following style

#map {
        margin-left:0px;
        width:107%;
        pointer-events: none;
    }

The pointer events works and I can't interact with the map.
The thing I want is when click on map the pointer-events becomes 'auto'

I have tried this code of javascript and nothing happens. Any ideas?

Thanks in advance

Body:
you cannot get click event of an element which have "pointer-event:none". what you should do is just add that  inside a div.

for example,

<div class="map-wrapper"><iframe id="map"></iframe></div>

then, call your script as

    <script>
       $(document).ready(function() {
          $('#map').css('pointer-events', 'none');
          $('.map-wrapper').click(function() {
            $(this).find('#map').css('pointer-events', 'auto'); // just $('#map') also fine
          });
          $('.map-wrapper').mouseleave(function() {
            $(this).find('#map').css('pointer-events', 'none'); // making it not clickable when it's not in focus
          });

       });
    </script>

hope this helps!


问:
Using regex to find sentence between tags in string?
I need to get the sentence between tags like
Hello world!
 using regex .

Attribute of tags may differ like
Hello world!

I have code like this

```<code>var result = elements.match(/<p>(.*?)<\/p>/g).map(function(val1){
    return val1.replace(/<\/?p>/g,'');
});
</code>```

答:
I hope the below regex works for you. Let me know if it does.

```<code>    var result = elements.match(/<p(.*?)<\/p>/g).map(function (val1) {
    return val1.replace(/<\/?p.*?>/g, '');
    });
</code>```

.*? -> Matches all the characters(attribute properties) within the tag element.

If there are multiple tags in your element block, this will return you the array of texts. You could access them using their index

Body:
I need to get the sentence between tags like
Hello world!
 using regex .

Attribute of tags may differ like
Hello world!

I have code like this

var result = elements.match(/
(.*?)<\/p>/g).map(function(val1){
    return val1.replace(/<\/?p>/g,'');
});

Body:
I hope the below regex works for you. Let me know if it does.

    var result = elements.match(/<p(.*?)<\/p>/g).map(function (val1) {
    return val1.replace(/<\/?p.*?>/g, '');
    });

.*? -> Matches all the characters(attribute properties) within the tag element.

If there are multiple tags in your element block, this will return you the array of texts. You could access them using their index


问:
Pickling cv2.Knearest objects not working
I have been  trying to save a cv2.knearest trained model to file .For the code below (python 2)

```<code>import numpy as np
import cv2
from sklearn.datasets import load_digits
import pickle
from sklearn.externals import joblib
samples = np.float32(np.loadtxt('feature_vector_pixels.data'))
responses = np.float32(np.loadtxt('samples_pixels.data'))
model = cv2.KNearest()
model.train(samples, responses)
# save the model to disk
filename = 'init_model.sav'
pickle.dump(model, open(filename, 'wb'))
</code>```

I get

```<code>Traceback (most recent call last):
File "picklemake.py", line 14, in <module>
pickle.dump(model, open(filename, 'wb'))
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 1376, in  dump
Pickler(file, protocol).dump(obj)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 306, in save
rv = reduce(self.proto)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle KNearest objects
</code>```

Are there any alternatives to save this model to file.

Also
On using model.save, I get OpenCV Error: The function/feature is not implemented () in CvStatModel::write, file ..\..\..\modules\ml\src\inner_functions.cpp

答:
Knearest extends CvStatModel. The latter has two overloads of the save(...) method that do exactly what you need.

I don't exactly know why, but a rule of thumb is that if you're using the python wrapper over C(++) library, its classes usually won't be pickle'able.

Body:
I have been  trying to save a cv2.knearest trained model to file .For the code below (python 2)

import numpy as np
import cv2
from sklearn.datasets import load_digits
import pickle
from sklearn.externals import joblib
samples = np.float32(np.loadtxt('feature_vector_pixels.data'))
responses = np.float32(np.loadtxt('samples_pixels.data'))
model = cv2.KNearest()
model.train(samples, responses)
# save the model to disk
filename = 'init_model.sav'
pickle.dump(model, open(filename, 'wb'))

I get

Traceback (most recent call last):
File "picklemake.py", line 14, in <module>
pickle.dump(model, open(filename, 'wb'))
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 1376, in  dump
Pickler(file, protocol).dump(obj)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 306, in save
rv = reduce(self.proto)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle KNearest objects

Are there any alternatives to save this model to file.

Also
On using model.save, I get OpenCV Error: The function/feature is not implemented () in CvStatModel::write, file ..\..\..\modules\ml\src\inner_functions.cpp

ContentLicense: CC BY-SA 4.0


问:
Catch all path in flask app
I writing an app in Angular + Flask hosted on heroku. I've been looking to use html5mode to use myapp.co/register for oauth. The problem with html5mode is that server needs to rewrite url if someone refreshes the page or clicks the link that is not root. I tried to use this snippet to catch them all, but it doesn't work.

```<code>@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(path):
  print path
  return make_response(open(app.static_folder + "index.html").read())
</code>```

output 404

```<code> * Restarting with reloader
127.0.0.1 - - [23/Jan/2014 13:41:48] "GET /ass HTTP/1.1" 404 -
</code>```

App got root that servers index.html and /api/v1/ that is RESTful api

答:
You need to use something more than you have:

```<code>@app.route("/", defaults={"path": ""})
@app.route("/<string:path>") <--- this is missing
@app.route("/<path:path>")
def index(path):
  print path
  return make_response(open(app.static_folder + "index.html").read())
</code>```

So:

```<code>@app.route("/<string:path>")
</code>```

is missing. It catches string variables (not path), so in your case just ass from your example, when you try to hit http://localhost:5000/ass.

Title: Catch all path in flask app

Body:
I writing an app in Angular + Flask hosted on heroku. I've been looking to use html5mode to use myapp.co/register for oauth. The problem with html5mode is that server needs to rewrite url if someone refreshes the page or clicks the link that is not root. I tried to use this snippet to catch them all, but it doesn't work.

@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(path):
  print path
  return make_response(open(app.static_folder + "index.html").read())

output 404

 * Restarting with reloader
127.0.0.1 - - [23/Jan/2014 13:41:48] "GET /ass HTTP/1.1" 404 -

App got root that servers index.html and /api/v1/ that is RESTful api

Body:
You need to use something more than you have:

@app.route("/", defaults={"path": ""})
@app.route("/<string:path>") <--- this is missing
@app.route("/<path:path>")
def index(path):
  print path
  return make_response(open(app.static_folder + "index.html").read())

So:

@app.route("/<string:path>")

is missing. It catches string variables (not path), so in your case just ass from your example, when you try to hit http://localhost:5000/ass.


问:
BlackBerry InputStream to String conversion
How do I convert an InputStream to a String on a BlackBerry?</p>

答:
Jonathan's approach assumes your bytes represent a String in default BlackBerry encoding (ISO-8859-1). However most modern apps are multy-languaged, so the best encoding to support is UTF-8. To respect a set encoding you may use smth like this:</p>

```<code>/**
 * Constructs a String using the data read from the passed InputStream.
 * Data is read using a 1024-chars buffer. Each char is created using the passed
 * encoding from one or more bytes.
 *
 * <p>If passed encoding is null, then the default BlackBerry encoding (ISO-8859-1) is used.</p>
 *
 * BlackBerry platform supports the following character encodings:
 * <ul>
 * <li>"ISO-8859-1"</li>
 * <li>"UTF-8"</li>
 * <li>"UTF-16BE"</li>
 * <li>"UTF-16LE"</li>
 * <li>"US-ASCII"</li>
 * </ul>
 *
 * @param in - InputStream to read data from.
 * @param encoding - String representing the desired character encoding, can be null.
 * @return String created using the char data read from the passed InputStream.
 * @throws IOException if an I/O error occurs.
 * @throws UnsupportedEncodingException if encoding is not supported.
 */
public static String getStringFromStream(InputStream in, String encoding) throws IOException {
    InputStreamReader reader;
    if (encoding == null) {
        reader = new InputStreamReader(in);
    } else {
        reader = new InputStreamReader(in, encoding);
    }

    StringBuffer sb = new StringBuffer();

    final char[] buf = new char[1024];
    int len;
    while ((len = reader.read(buf)) > 0) {
        sb.append(buf, 0, len);
    }

    return sb.toString();
}
</code>```

Body:
Jonathan's approach assumes your bytes represent a String in default BlackBerry encoding (ISO-8859-1). However most modern apps are multy-languaged, so the best encoding to support is UTF-8. To respect a set encoding you may use smth like this:

/**
 * Constructs a String using the data read from the passed InputStream.
 * Data is read using a 1024-chars buffer. Each char is created using the passed
 * encoding from one or more bytes.
 *
 * <p>If passed encoding is null, then the default BlackBerry encoding (ISO-8859-1) is used.</p>
 *
 * BlackBerry platform supports the following character encodings:
 * <ul>
 * <li>"ISO-8859-1"</li>
 * <li>"UTF-8"</li>
 * <li>"UTF-16BE"</li>
 * <li>"UTF-16LE"</li>
 * <li>"US-ASCII"</li>
 * </ul>
 *
 * @param in - InputStream to read data from.
 * @param encoding - String representing the desired character encoding, can be null.
 * @return String created using the char data read from the passed InputStream.
 * @throws IOException if an I/O error occurs.
 * @throws UnsupportedEncodingException if encoding is not supported.
 */
public static String getStringFromStream(InputStream in, String encoding) throws IOException {
    InputStreamReader reader;
    if (encoding == null) {
        reader = new InputStreamReader(in);
    } else {
        reader = new InputStreamReader(in, encoding);
    }

    StringBuffer sb = new StringBuffer();

    final char[] buf = new char[1024];
    int len;
    while ((len = reader.read(buf)) > 0) {
        sb.append(buf, 0, len);
    }

    return sb.toString();
}


问:
Filesystems content of docker container on host
I've read quite a lot about how docker works using cgroups and namespaces. If that's correct the host should be able to see all the processes and filesystem tree that is used by the docker container. However I seem to be unable to figure it out.

Could someone show it with docker v1.12.6 and a running "nginx" container?

Optional: Is it possible to still access the files of already exited containers the same way?

PS, GraphDriver looks like this:

```<code>"GraphDriver" : {
  "Name" : "aufs",
  "Data" : null
},
</code>```

答: You can copy files from docker using docker cp command then you can access it.That will be simplest way to access files from exited container,too.</p>

Body:
I've read quite a lot about how docker works using cgroups and namespaces. If that's correct the host should be able to see all the processes and filesystem tree that is used by the docker container. However I seem to be unable to figure it out.

Could someone show it with docker v1.12.6 and a running "nginx" container?

Optional: Is it possible to still access the files of already exited containers the same way?

PS, GraphDriver looks like this:

"GraphDriver" : {
  "Name" : "aufs",
  "Data" : null
},


答:
I would do this as:

```<code>select t.*
from t
where left(col, 1) = right(col, 1);
</code>```

By default, SQL Server comparisons are case-insensitive.  If you are using a case-sensitive collation, you might want:

```<code>select t.*
from t
where lower(left(col, 1)) = lower(right(col, 1));
</code>```

Title: Query to retrive rows with words starting and ending with same character in sql server

Body:
I need to write a SQL Server query to filter the rows with sentences containing first and last character of the sentence being same like

Thanks in advance.

Body:
I would do this as:

select t.*
from t
where left(col, 1) = right(col, 1);

By default, SQL Server comparisons are case-insensitive.  If you are using a case-sensitive collation, you might want:

select t.*
from t
where lower(left(col, 1)) = lower(right(col, 1));


问:
Cannot add/remove/toggle element class inside Vue directive?
This works: https://jsfiddle.net/hxyv40ra

However, when I place this code inside of a vue directive the button event is triggered and the console shows the class is removed but nothing visually changes?

Here's an example: https://jsfiddle.net/hLga2jxq

Directive code is also below (to appease stackoverflow's rules).

styles

```<code>.hide {
  display: none;
}
</code>```

html

```<code><div id="app">
  <button v-hide-for="'uniqueID'">toggle to show?</button>
  <div class="hide" hide-name="uniqueID">
    Hello! :D
  </div>
</div>
</code>```

js

```<code>Vue.directive('hide-for', {
    bind(button, b, vnode, oldVnode) {
        console.log(b);
        var elsToToggle = document.querySelectorAll(`[hide-name="${b.value}"]`);
        console.log(button, b.value, `[hide-name="${b.value}"]`, elsToToggle);

        button.addEventListener('click', (b) => {
            console.log(button, " clicked");
            elsToToggle.forEach((el) => {
                console.log(el);
                el.classList.toggle('hide');
            })
        }, false)
    }
});

var app = new Vue({
  name: "test",
  el: '#app',
  data: {}
})
</code>```

答:
So I tried this from another angle and also made the 'hide-name' attribute a directive as well, then on click I emitted the 'uniqueID' which 'hide-name' directive picked up.

I'm still not sure why Vue is not visually updating the browser but I'm guessing it must have something to do with the 'virtual-dom'.

demo: https://jsfiddle.net/hLga2jxq/3/

```<code>Vue.directive('hide-for', {
    bind(el, b, vnode) {
        el.addEventListener('click', (event) => vnode.context.$emit(b.value, event) );
    }
});

Vue.directive('hide-name', {
    bind(el, b, vnode, oldVnode) {
        vnode.context.$on(b.value, function(){
            let hasHideClassAttr = el.getAttribute('hide-class');
            if(hasHideClassAttr) hasHideClassAttr.split(' ').forEach((c) => el.classList.toggle(c) );
            else el.classList.toggle('hide');
        });
    }
});
</code>```

Body:
This works: https://jsfiddle.net/hxyv40ra

However, when I place this code inside of a vue directive the button event is triggered and the console shows the class is removed but nothing visually changes?

Here's an example: https://jsfiddle.net/hLga2jxq

Directive code is also below (to appease stackoverflow's rules).

styles

.hide {
  display: none;
}

html

  <button v-hide-for="'uniqueID'">toggle to show?</button>

    Hello! :D

js

Vue.directive('hide-for', {
    bind(button, b, vnode, oldVnode) {
        console.log(b);
        var elsToToggle = document.querySelectorAll(`[hide-name="${b.value}"]`);
        console.log(button, b.value, `[hide-name="${b.value}"]`, elsToToggle);

        button.addEventListener('click', (b) => {
            console.log(button, " clicked");
            elsToToggle.forEach((el) => {
                console.log(el);
                el.classList.toggle('hide');
            })
        }, false)
    }
});

var app = new Vue({
  name: "test",
  el: '#app',
  data: {}
})

Body:
So I tried this from another angle and also made the 'hide-name' attribute a directive as well, then on click I emitted the 'uniqueID' which 'hide-name' directive picked up.

I'm still not sure why Vue is not visually updating the browser but I'm guessing it must have something to do with the 'virtual-dom'.

demo: https://jsfiddle.net/hLga2jxq/3/

Vue.directive('hide-for', {
    bind(el, b, vnode) {
        el.addEventListener('click', (event) => vnode.context.$emit(b.value, event) );
    }
});

Vue.directive('hide-name', {
    bind(el, b, vnode, oldVnode) {
        vnode.context.$on(b.value, function(){
            let hasHideClassAttr = el.getAttribute('hide-class');
            if(hasHideClassAttr) hasHideClassAttr.split(' ').forEach((c) => el.classList.toggle(c) );
            else el.classList.toggle('hide');
        });
    }
});


问:
Cx_Oracle - How to specify a query with a double ordered output
I'm working on a Cx_Oracle 11g database: I'm wondering if it's possible have two innested different types of order by in output from a table. I mean, suppose the columns are name , timestamp and value and I need output looks like:

```<code>nameA - timestamp1 - value
nameA - timestamp2 - value
nameA - timestamp3 - value
nameB - timestamp1 - value
nameB - timestamp2 - value
nameB - timestamp3 - value
</code>```

Where the principal order is by name, and timestamp is ordered for every different name. How can I do?

答:
From the Oracle documentation:

You can specify multiple expressions in the order_by_clause. Oracle Database first sorts rows based on their values for the first expression. Rows with the same value for the first expression are then sorted based on their values for the second expression, and so on

So in your case just doing:

```<code>order by name, timestamp
</code>```

in your query will do what you describe.

Body:
I'm working on a Cx_Oracle 11g database: I'm wondering if it's possible have two innested different types of order by in output from a table. I mean, suppose the columns are name , timestamp and value and I need output looks like:

nameA - timestamp1 - value
nameA - timestamp2 - value
nameA - timestamp3 - value
nameB - timestamp1 - value
nameB - timestamp2 - value
nameB - timestamp3 - value

Where the principal order is by name, and timestamp is ordered for every different name. How can I do?

Body:
From the Oracle documentation:

You can specify multiple expressions in the order_by_clause. Oracle Database first sorts rows based on their values for the first expression. Rows with the same value for the first expression are then sorted based on their values for the second expression, and so on

So in your case just doing:

order by name, timestamp

in your query will do what you describe.


问:
How to use next and previous button to display some images in each

How to use a next and a previous button to show some images in every
-element?

答:
You can accomplish that by using .prev() and .next() functions of jQuery. Code snippet is shown below -

$(document).ready(function(){

      var selected = $(".selected");
      selected.css( "background-color", "red" );

    $("#prev").on("click", function(){
    var selected = $(".selected");
      if(selected.prev().length){
      selected.prev().css( "background-color", "red" );
      selected.prev().addClass("selected");
      selected.removeClass("selected");
      selected.css("background-color", "");
      }
      else{
       $(".item:last").addClass('selected');
       $(".item:last").css( "background-color", "red" );
       selected.removeClass("selected");
       selected.css("background-color", "");
      }
    });

     $("#next").on("click", function(){
    var selected = $(".selected");
    if(selected.next().length){
      selected.next().css( "background-color", "red" );
      selected.next().addClass("selected");
      selected.removeClass("selected");
      selected.css("background-color", "");
      }
      else{
       $(".item:first").addClass('selected');
       $(".item:first").css( "background-color", "red" );
       selected.removeClass("selected");
       selected.css("background-color", "");
      }
    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 10px 15px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}</code>```

list item 1

list item 2

list item 3

list item 4

list item 5

<button id="prev" class="button">Previous</button>
<button id="next" class="button">Next</button>```

Title: How to use next and previous button to display some images in each <ul>

Body:
You can accomplish that by using .prev() and .next() functions of jQuery. Code snippet is shown below -

$(document).ready(function(){

      var selected = $(".selected");
      selected.css( "background-color", "red" );

    $("#prev").on("click", function(){
    var selected = $(".selected");
      if(selected.prev().length){
      selected.prev().css( "background-color", "red" );
      selected.prev().addClass("selected");
      selected.removeClass("selected");
      selected.css("background-color", "");
      }
      else{
       $(".item:last").addClass('selected');
       $(".item:last").css( "background-color", "red" );
       selected.removeClass("selected");
       selected.css("background-color", "");
      }
    });

     $("#next").on("click", function(){
    var selected = $(".selected");
    if(selected.next().length){
      selected.next().css( "background-color", "red" );
      selected.next().addClass("selected");
      selected.removeClass("selected");
      selected.css("background-color", "");
      }
      else{
       $(".item:first").addClass('selected');
       $(".item:first").css( "background-color", "red" );
       selected.removeClass("selected");
       selected.css("background-color", "");
      }
    });

});

body {
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 10px 15px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="item">list item 1</li>
  <li class="item">list item 2</li>
  <li class="item selected">list item 3</li>
  <li class="item">list item 4</li>
  <li class="item">list item 5</li>
</ul>
<button id="prev" class="button">Previous</button>
<button id="next" class="button">Next</button>


问:
RecyclerView ?android:attr/selectableItemBackground does not work on items
I have this items.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:focusable="true"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:layout_height="wrap_content">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:id="@+id/colorPreview" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textAppearance="@android:style/TextAppearance.Large"
    android:textColor="@android:color/white"
    android:id="@+id/colorName" />

</RelativeLayout>
</code>```

When I use it separately, the selectableItemBackground animates when I click the view. But when I use it for the items in a RecyclerView, the effect on click does not happen anymore. How can I fix this?

PS: this is the listener on the RecyclerView, if it is relevant:

```<code> public ColorListOnItemTouchListener(Context context, OnItemClickListener clickListener) {
    mClickListener = clickListener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
                if(childView != null && mClickListener != null) {
                    mClickListener.onItemLongPress(childView, index);
                }
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if(childView != null && mClickListener != null) {
                mClickListener.onItemClick(childView, index);
            }
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    });
}
</code>```

Thank you!

Edit:

```<code> public class ColorsCursorAdapter extends RecyclerView.Adapter<ColorsCursorAdapter.ViewHolder> {

    private static final int layout = R.layout.color_item;
    private Cursor mCursor;

    public ColorsCursorAdapter(Cursor c) {
        super();
        this.mCursor = c;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
        TextView name = (TextView) v.findViewById(R.id.colorName);
        ImageView image = (ImageView) v.findViewById(R.id.colorPreview);
        return new ViewHolder(v, name, image);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        mCursor.moveToPosition(position);
        int color = mCursor.getInt(mCursor.getColumnIndex(ColorItem.COLUMN_COLOR));
        holder.colorName.setText(Utils.getColorString(color));
        holder.colorPreview.setImageDrawable(new ColorDrawable(color));
    }

    @Override
    public int getItemCount() {
        if(mCursor != null) {
            return mCursor.getCount();
        }
        return 0;
    }

    public void swapCursor(Cursor c) {
        mCursor = c;
        notifyDataSetChanged();
    }

    public Cursor getCursor() {
        return mCursor;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView colorName;
        public ImageView colorPreview;

        public ViewHolder(View root, TextView colorName, ImageView colorPreview) {
            super(root);
            root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //
                }
            });
            this.colorName = colorName;
            this.colorPreview = colorPreview;
        }
    }
}
</code>```

And the adapter is created with:

```<code>colorList.setLayoutManager(new LinearLayoutManager(this));
    adapter = new ColorsCursorAdapter(null);
    colorList.setAdapter(adapter);
</code>```

答: In my case the problem was caused by DividerItemDecoration. As soon as I got rid of that, it started to work. I suggest to put a line at the end of xml file for each item in RecyclerView, it's much easier to customize and you won't run into these kinds of problems.

Body:
I have this items.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:focusable="true"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:layout_height="wrap_content">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:id="@+id/colorPreview" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textAppearance="@android:style/TextAppearance.Large"
    android:textColor="@android:color/white"
    android:id="@+id/colorName" />

</RelativeLayout>

When I use it separately, the selectableItemBackground animates when I click the view. But when I use it for the items in a RecyclerView, the effect on click does not happen anymore. How can I fix this?

PS: this is the listener on the RecyclerView, if it is relevant:

 public ColorListOnItemTouchListener(Context context, OnItemClickListener clickListener) {
    mClickListener = clickListener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
                if(childView != null && mClickListener != null) {
                    mClickListener.onItemLongPress(childView, index);
                }
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if(childView != null && mClickListener != null) {
                mClickListener.onItemClick(childView, index);
            }
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    });
}

Thank you!

Edit:

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

    private static final int layout = R.layout.color_item;
    private Cursor mCursor;

    public ColorsCursorAdapter(Cursor c) {
        super();
        this.mCursor = c;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
        TextView name = (TextView) v.findViewById(R.id.colorName);
        ImageView image = (ImageView) v.findViewById(R.id.colorPreview);
        return new ViewHolder(v, name, image);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        mCursor.moveToPosition(position);
        int color = mCursor.getInt(mCursor.getColumnIndex(ColorItem.COLUMN_COLOR));
        holder.colorName.setText(Utils.getColorString(color));
        holder.colorPreview.setImageDrawable(new ColorDrawable(color));
    }

    @Override
    public int getItemCount() {
        if(mCursor != null) {
            return mCursor.getCount();
        }
        return 0;
    }

    public void swapCursor(Cursor c) {
        mCursor = c;
        notifyDataSetChanged();
    }

    public Cursor getCursor() {
        return mCursor;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView colorName;
        public ImageView colorPreview;

        public ViewHolder(View root, TextView colorName, ImageView colorPreview) {
            super(root);
            root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //
                }
            });
            this.colorName = colorName;
            this.colorPreview = colorPreview;
        }
    }
}

And the adapter is created with:

colorList.setLayoutManager(new LinearLayoutManager(this));
    adapter = new ColorsCursorAdapter(null);
    colorList.setAdapter(adapter);


问:
Problems when sending XML data from HTTP Java client to a servlet with HttpURLConnection
I have standalone java client sending xml data to http servlet using httpURLconnection class.but data appearing in non printable character format.

For simulation i have been trying to send simple string but still it was appearing in non printable format.

I have written the following client code to communicate with servlet,

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class HttpClient implements IClient {

    private static IClient client = null;

    private HttpURLConnection httpConn = null;

    private OutputStream output = null;

    private InputStream input = null;

    private OutputStreamWriter out = null;

    private HttpClient() {
    }

    public static IClient getHttpClient() {
        if (client == null) {
            client = new HttpClient();
        }
        return client;
    }

    @Override
    public void connect(String urlString) throws IOException {
        URL url = new URL(urlString);
        httpConn = (HttpURLConnection) url.openConnection();
        initConnection();
        httpConn.connect();
        output = httpConn.getOutputStream();
        input = httpConn.getInputStream();
        System.out.println("Connection Response:" + httpConn.getResponseCode());
    }

    @Override
    public void sendFile(File file) throws IOException {
        // BufferedOutputStream bos = new BufferedOutputStream(output);
        // InputStream fis = new FileInputStream(file);
        // int bytesRead = 0;
        // byte[] buffer = new byte[8192];
        // while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
        // bos.write(buffer, 0, bytesRead);
        // System.out.println("write:"+buffer);
        // }
        // bos.close();
        // fis.close();

        OutputStreamWriter out = new OutputStreamWriter(output, "UTF-16");
        out.write("test me");
    }

    @Override
    public boolean isConnected() {
        return httpConn != null ? true : false;
    }

    @Override
    public void close() {
        httpConn.disconnect();
    }

    private void initConnection() throws ProtocolException {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setUseCaches(false);
        httpConn.setRequestProperty("Content-Type",
                "text/xml; charset=\"UTF-16\"");
        httpConn.setRequestProperty("Connection", "Keep-Alive");

    }

    private static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);
        System.out.println("\nDEBUG: FileInputStream is " + file);

        // Get the size of the file
        long length = file.length();
        System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

        /*
         * You cannot create an array using a long type. It needs to be an int
         * type. Before converting to an int type, check to ensure that file is
         * not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length)
                && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {

            offset += numRead;

        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }

        return bytes;

    }

}
</code>```

and servlet code is given below,

```<code>import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XMLServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=========inside doPost=========");
//      BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
//      OutputStream fos = new FileOutputStream("test.xml");
//      int bytesRead = 0;
//      byte[] buffer = new byte[8192];
//      while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//          System.out.println("read:"+buffer);
//          fos.write(buffer, 0, bytesRead);
//      }
//      fos.close();
//      bis.close();
//

        req.setCharacterEncoding("UTF-16");
        InputStreamReader isr = new InputStreamReader(req.getInputStream(),"UTF-16");
        char[] data = new char[10];
        isr.read(data);
        System.out.println(data);
        for (char c : data) {
            System.out.println(c);
        }
    }

}
</code>```

Please any help me to get out of this problem.

答:
There are two major ways to upload a file on to server using http methods:

Upload a file using PUT method. This allow you to put one file at a time on to server. PUT method is easy to implement but you cannot upload a file from a html form (e.g. uploading form in your web browser) using PUT method.

Upload files using POST method. This is more complicated but most web site uses this to upload files on to server. You can do multiple file uploading per request. This is what I am going to talk about.

Note: GET is not used for file uploading unless you encode it somehow.

Uploading files using URLConnection is not straight forwards and requires you to prepare your data in "multipart form". Of course, you shouldn't do it yourself. There are a number of libraries to deal with this for you, e.g. HttpClient. If you really want to use URLConnection, I shall refer to previous question on "How to use java.net.URLConnection to fire and handle HTTP requests"

Below is the code for uploading your file using HttpClient. It is simplified from HttpClient example code.

```<code>import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class MultipartFileUploadApp {

    public static void main(String[] args) {
        String targetURL = "http://localhost:8080/yourserver/upload";
        File targetFile = new File("/path/to/your/file.txt");

        PostMethod filePost = new PostMethod(targetURL);

        filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

        try {

            System.out.println("Uploading " + targetFile.getName() + " to " + targetURL);

            // add more parts you want to upload multiple files.
            Part[] parts = {new FilePart(targetFile.getName(), targetFile)};

            filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

            int status = client.executeMethod(filePost);

            if (status == HttpStatus.SC_OK) {
                System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
            } else {
                System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
            }
        } catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            filePost.releaseConnection();
        }

    }
}
</code>```

For the server side, you have to parse multipart form request. Of course, there exists libraries to do that for you. Here is the snipplet I am using

```<code>import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CommonsFileUploadServlet extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "c:\\tmp\\files";
    private File destinationDir;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        //String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(DESTINATION_DIR_PATH);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("text/plain");
        out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
        out.println();

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            /*
             * Parse the request
             */
            List items = uploadHandler.parseRequest(request);
            out.println("Count : " + items.size());
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                /*
                 * Handle Form Fields.
                 */
                if (item.isFormField()) {
                    out.println("Field = " + item.getFieldName() + ", Value = " + item.getString());
                } else {
                    //Handle Uploaded files.
                    out.println("Field Name = " + item.getFieldName()
                            + ", File Name = " + item.getName()
                            + ", Content type = " + item.getContentType()
                            + ", File Size = " + item.getSize());
                    /*
                     * Write file to the ultimate location.
                     */
                    File file = new File(destinationDir, item.getName());
                    item.write(file);
                }
            }
            out.close();
        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }

    }
}
</code>```

Body:
I have standalone java client sending xml data to http servlet using httpURLconnection class.but data appearing in non printable character format.

For simulation i have been trying to send simple string but still it was appearing in non printable format.

I have written the following client code to communicate with servlet,

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class HttpClient implements IClient {

    private static IClient client = null;

    private HttpURLConnection httpConn = null;

    private OutputStream output = null;

    private InputStream input = null;

    private OutputStreamWriter out = null;

    private HttpClient() {
    }

    public static IClient getHttpClient() {
        if (client == null) {
            client = new HttpClient();
        }
        return client;
    }

    @Override
    public void connect(String urlString) throws IOException {
        URL url = new URL(urlString);
        httpConn = (HttpURLConnection) url.openConnection();
        initConnection();
        httpConn.connect();
        output = httpConn.getOutputStream();
        input = httpConn.getInputStream();
        System.out.println("Connection Response:" + httpConn.getResponseCode());
    }

    @Override
    public void sendFile(File file) throws IOException {
        // BufferedOutputStream bos = new BufferedOutputStream(output);
        // InputStream fis = new FileInputStream(file);
        // int bytesRead = 0;
        // byte[] buffer = new byte[8192];
        // while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
        // bos.write(buffer, 0, bytesRead);
        // System.out.println("write:"+buffer);
        // }
        // bos.close();
        // fis.close();

        OutputStreamWriter out = new OutputStreamWriter(output, "UTF-16");
        out.write("test me");
    }

    @Override
    public boolean isConnected() {
        return httpConn != null ? true : false;
    }

    @Override
    public void close() {
        httpConn.disconnect();
    }

    private void initConnection() throws ProtocolException {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setUseCaches(false);
        httpConn.setRequestProperty("Content-Type",
                "text/xml; charset=\"UTF-16\"");
        httpConn.setRequestProperty("Connection", "Keep-Alive");

    }

    private static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);
        System.out.println("\nDEBUG: FileInputStream is " + file);

        // Get the size of the file
        long length = file.length();
        System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

        /*
         * You cannot create an array using a long type. It needs to be an int
         * type. Before converting to an int type, check to ensure that file is
         * not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length)
                && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {

            offset += numRead;

        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }

        return bytes;

    }

}

and servlet code is given below,

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XMLServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=========inside doPost=========");
//      BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
//      OutputStream fos = new FileOutputStream("test.xml");
//      int bytesRead = 0;
//      byte[] buffer = new byte[8192];
//      while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//          System.out.println("read:"+buffer);
//          fos.write(buffer, 0, bytesRead);
//      }
//      fos.close();
//      bis.close();
//

        req.setCharacterEncoding("UTF-16");
        InputStreamReader isr = new InputStreamReader(req.getInputStream(),"UTF-16");
        char[] data = new char[10];
        isr.read(data);
        System.out.println(data);
        for (char c : data) {
            System.out.println(c);
        }
    }

}

Please any help me to get out of this problem.

Body:
There are two major ways to upload a file on to server using http methods:

Upload a file using PUT method. This allow you to put one file at a time on to server. PUT method is easy to implement but you cannot upload a file from a html form (e.g. uploading form in your web browser) using PUT method.

Upload files using POST method. This is more complicated but most web site uses this to upload files on to server. You can do multiple file uploading per request. This is what I am going to talk about.

Note: GET is not used for file uploading unless you encode it somehow.

Uploading files using URLConnection is not straight forwards and requires you to prepare your data in "multipart form". Of course, you shouldn't do it yourself. There are a number of libraries to deal with this for you, e.g. HttpClient. If you really want to use URLConnection, I shall refer to previous question on "How to use java.net.URLConnection to fire and handle HTTP requests"

Below is the code for uploading your file using HttpClient. It is simplified from HttpClient example code.

import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class MultipartFileUploadApp {

    public static void main(String[] args) {
        String targetURL = "http://localhost:8080/yourserver/upload";
        File targetFile = new File("/path/to/your/file.txt");

        PostMethod filePost = new PostMethod(targetURL);

        filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

        try {

            System.out.println("Uploading " + targetFile.getName() + " to " + targetURL);

            // add more parts you want to upload multiple files.
            Part[] parts = {new FilePart(targetFile.getName(), targetFile)};

            filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

            int status = client.executeMethod(filePost);

            if (status == HttpStatus.SC_OK) {
                System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
            } else {
                System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
            }
        } catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            filePost.releaseConnection();
        }

    }
}

For the server side, you have to parse multipart form request. Of course, there exists libraries to do that for you. Here is the snipplet I am using

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CommonsFileUploadServlet extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "c:\\tmp\\files";
    private File destinationDir;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        //String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(DESTINATION_DIR_PATH);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("text/plain");
        out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
        out.println();

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            /*
             * Parse the request
             */
            List items = uploadHandler.parseRequest(request);
            out.println("Count : " + items.size());
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                /*
                 * Handle Form Fields.
                 */
                if (item.isFormField()) {
                    out.println("Field = " + item.getFieldName() + ", Value = " + item.getString());
                } else {
                    //Handle Uploaded files.
                    out.println("Field Name = " + item.getFieldName()
                            + ", File Name = " + item.getName()
                            + ", Content type = " + item.getContentType()
                            + ", File Size = " + item.getSize());
                    /*
                     * Write file to the ultimate location.
                     */
                    File file = new File(destinationDir, item.getName());
                    item.write(file);
                }
            }
            out.close();
        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }

    }
}


问:
Form Validation in Rest Webservice
I started building my first REST webservice in Java using Spring and JPA.

Now I'm trying to create sign-up service. I have no problem with sending a request containing all Entity fields what looks:

```<code>@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Entity
@Table(name = "users")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Enumerated(EnumType.STRING)
private Gender gender;

@Column(name = "email")
private String email;

@Column(name = "login")
private String login;

@Column(name = "password")
private String password;

@Column(name = "registration_date")
@CreatedDate
private LocalDateTime registrationDate;

@OneToMany(mappedBy = "bookOwner", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Book> bookList = new ArrayList<>();
}
</code>```

But what to do in situation I want my registration form having only login, password and email fields and filling the rest user details would be optional - after confirmation of registration?

I consider using ModelMapper and creating separate classes for every form, but is there any better approach?

答:
I solved problem by my own using mentioned ModelMapper. I paste my code. Can be useful if someone's interested. Didn't make tests, but my DB looks fine and no exceptions are thrown. </p>

```<code> public class DTOMapper {
        private static final ModelMapper MAPPER = new ModelMapper();

        private DTOMapper(){}

        public static <S, T> T map(S source, Class<T> targetClass){
            return MAPPER.map(source, targetClass);
        }
    }

@Service
@Transactional
public class SignUpService {

    private final UserRepository userRepository;

    @Autowired
    public SignUpService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User registerUser(SignUpForm form){
        if(userRepository.findByLogin(form.getLogin())!=null){
            throw new LoginAlreadyUsedException(form.getLogin());
        }

        if(userRepository.findByEmail(form.getEmail())!=null){
            throw new EmailAlreadyUsedException(form.getEmail());
        }

        User user = DTOMapper.map(form, User.class);

        User saved = userRepository.save(user);

        return DTOMapper.map(saved, User.class);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class SignUpForm implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotEmpty
    @Size(min = 5)
    private String login;

    @NotEmpty
    @Size(min = 7)
    private String password;

    //todo email validation
    @NotEmpty
    private String email;
}

@RestController
public class SignUpController {
    private static final Logger log = LoggerFactory.getLogger(SignUpController.class);

    @Autowired
    private SignUpService signUpService;

    @PostMapping(value = "/signup")
    public ResponseEntity<?> addUser(@RequestBody @Valid SignUpForm form, BindingResult errors){

        if(errors.hasErrors()){
            throw new InvalidRequestException(errors);
        }

        signUpService.registerUser(form);
        return new ResponseEntity<>(form, HttpStatus.CREATED);
    }
}
</code>```

Title: Form Validation in Rest Webservice

Body:
I started building my first REST webservice in Java using Spring and JPA.

Now I'm trying to create sign-up service. I have no problem with sending a request containing all Entity fields what looks:

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Entity
@Table(name = "users")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Enumerated(EnumType.STRING)
private Gender gender;

@Column(name = "email")
private String email;

@Column(name = "login")
private String login;

@Column(name = "password")
private String password;

@Column(name = "registration_date")
@CreatedDate
private LocalDateTime registrationDate;

@OneToMany(mappedBy = "bookOwner", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Book> bookList = new ArrayList<>();
}

But what to do in situation I want my registration form having only login, password and email fields and filling the rest user details would be optional - after confirmation of registration?

I consider using ModelMapper and creating separate classes for every form, but is there any better approach?

Body:
I solved problem by my own using mentioned ModelMapper. I paste my code. Can be useful if someone's interested. Didn't make tests, but my DB looks fine and no exceptions are thrown.

 public class DTOMapper {
        private static final ModelMapper MAPPER = new ModelMapper();

        private DTOMapper(){}

        public static <S, T> T map(S source, Class<T> targetClass){
            return MAPPER.map(source, targetClass);
        }
    }

@Service
@Transactional
public class SignUpService {

    private final UserRepository userRepository;

    @Autowired
    public SignUpService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User registerUser(SignUpForm form){
        if(userRepository.findByLogin(form.getLogin())!=null){
            throw new LoginAlreadyUsedException(form.getLogin());
        }

        if(userRepository.findByEmail(form.getEmail())!=null){
            throw new EmailAlreadyUsedException(form.getEmail());
        }

        User user = DTOMapper.map(form, User.class);

        User saved = userRepository.save(user);

        return DTOMapper.map(saved, User.class);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class SignUpForm implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotEmpty
    @Size(min = 5)
    private String login;

    @NotEmpty
    @Size(min = 7)
    private String password;

    //todo email validation
    @NotEmpty
    private String email;
}

@RestController
public class SignUpController {
    private static final Logger log = LoggerFactory.getLogger(SignUpController.class);

    @Autowired
    private SignUpService signUpService;

    @PostMapping(value = "/signup")
    public ResponseEntity<?> addUser(@RequestBody @Valid SignUpForm form, BindingResult errors){

        if(errors.hasErrors()){
            throw new InvalidRequestException(errors);
        }

        signUpService.registerUser(form);
        return new ResponseEntity<>(form, HttpStatus.CREATED);
    }
}