问:
GPS isProviderEnabled always return false
I've got this code

```<code> lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
 boolean isGPS = lm.isProviderEnabled (LocationManager.GPS_PROVIDER);
</code>```

and it always return false, even when GPS is enabled. GPS is working correctly but I'm using this boolean value to show pop-up "No GPS enabled". In this situation pop-up is showing up every time

I checked similar questions but it doesn't help me.

Yes, i have permission in my manifest

I'm using this code in onResume method

Thanks for help.

答:
If you are checking for the location is opened or not whatever it is using GPS or not, so you have to pay attention to the following as it was my case, in device location settings the locating method was set to BatterySaving mode, in which the device uses only WiFi mobile networks to estimate location:

Therefore, the GPS is not even used in update location, and so the location icon will not appear in the status bar in addition to the location provider will be stated as Network not GPS.

so, to solve that issue you have to check whether the provider contains gps or contains network:

```<code>private boolean checkIfLocationOpened() {
    String provider = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (provider.contains("gps") || provider.contains("network"))
        return true;
    }
    // otherwise return false
    return false;
}
</code>```

and if you want to do it using the LocationManager:

```<code>private boolean checkIfLocationOpened() {
    final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return true;
    }
    // otherwise return false
    return false;
}
</code>```

Body:
I've got this code

 lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
 boolean isGPS = lm.isProviderEnabled (LocationManager.GPS_PROVIDER);

and it always return false, even when GPS is enabled. GPS is working correctly but I'm using this boolean value to show pop-up "No GPS enabled". In this situation pop-up is showing up every time

I checked similar questions but it doesn't help me.

Yes, i have permission in my manifest

I'm using this code in onResume method

Thanks for help.

Body:
If you are checking for the location is opened or not whatever it is using GPS or not, so you have to pay attention to the following as it was my case, in device location settings the locating method was set to BatterySaving mode, in which the device uses only WiFi mobile networks to estimate location:

Therefore, the GPS is not even used in update location, and so the location icon will not appear in the status bar in addition to the location provider will be stated as Network not GPS.

so, to solve that issue you have to check whether the provider contains gps or contains network:

private boolean checkIfLocationOpened() {
    String provider = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (provider.contains("gps") || provider.contains("network"))
        return true;
    }
    // otherwise return false
    return false;
}

and if you want to do it using the LocationManager:

private boolean checkIfLocationOpened() {
    final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return true;
    }
    // otherwise return false
    return false;
}


来源: stackexchange

问:
Nothing to show in android xml preview design in android studio
nothing is showing in android xml preview when i use BottomBar library

The image indicates my problem

Android studio 2.2.3

答:
I had a similar problem. (Rendering problem on preview)

So, I tried many methods.

Android Studio > File > Invalidate Caches and Restart.

Remove ".android" file in Home Directory. And restart.

and etc...

But all of the solutions are not resolved.

So, I just uninstall Android Studio and re-download, reinstall.

Finally, I've solved this problem.

ContentLicense: CC BY-SA 3.0


问:
python flask restfull receive image
Hi I am having trouble receiving a file on my flask server from my python client I am saving the screenshot in memory but am unable to receive it on the  server end. I appreciate any help I can get I am lost with what my requests.post has to be.

Server Code:

```<code>@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    file.save(os.path.join(app.config['upload_folder'], filename))
</code>```

Client Code:

```<code>content_type = 'image/jpeg'
headers = {'content-type': content_type}

from PIL import ImageGrab
from StringIO import StringIO
screen = ImageGrab.grab()
img = stringIO()
screen.save(img, 'JPEG')
img.seek(0)
fd = open('screen.jpg', 'wb')
fd.write(img.getvalue())
fd.close()
fin = open('screen.jpg', 'wb')
files = {'file': fin}
requests.post('http://localhost/upload', files=files)
</code>```

答:
file to upload should be in format ('filename', fileobj, 'content_type'), so change

```<code>files={'file': ('test.jpg', content_type)}
</code>```

to

```<code>files={'file': ('test.jpg', img, content_type)}
</code>```

doc ref:

files -- (optional) Dictionary of 'name': file-like-objects (or
  {'name': file-tuple}) for multipart encoding upload. file-tuple can be
  a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj,
  'content_type') or a 4-tuple ('filename', fileobj, 'content_type',
  custom_headers), where 'content-type' is a string defining the content
  type of the given file and custom_headers a dict-like object
  containing additional headers to add for the file.

Title: python flask restfull receive image

Body:
Hi I am having trouble receiving a file on my flask server from my python client I am saving the screenshot in memory but am unable to receive it on the  server end. I appreciate any help I can get I am lost with what my requests.post has to be.

Server Code:

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    file.save(os.path.join(app.config['upload_folder'], filename))

Client Code:

content_type = 'image/jpeg'
headers = {'content-type': content_type}

from PIL import ImageGrab
from StringIO import StringIO
screen = ImageGrab.grab()
img = stringIO()
screen.save(img, 'JPEG')
img.seek(0)
fd = open('screen.jpg', 'wb')
fd.write(img.getvalue())
fd.close()
fin = open('screen.jpg', 'wb')
files = {'file': fin}
requests.post('http://localhost/upload', files=files)

Body:
file to upload should be in format ('filename', fileobj, 'content_type'), so change

files={'file': ('test.jpg', content_type)}

to

files={'file': ('test.jpg', img, content_type)}

doc ref:

files -- (optional) Dictionary of 'name': file-like-objects (or
  {'name': file-tuple}) for multipart encoding upload. file-tuple can be
  a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj,
  'content_type') or a 4-tuple ('filename', fileobj, 'content_type',
  custom_headers), where 'content-type' is a string defining the content
  type of the given file and custom_headers a dict-like object
  containing additional headers to add for the file.


问:
WebAssembly calling JavaScript methods from wasm i.e. within C++ code
I was playing with WebAssembly and so far and I was able to manage emscripten compile my test C++ project to wasm file
em++ provides me 2 files i.e.

mainTest.js  mainTest.wasm

When I load mainTest.js in my html page then I get a JavaScript object called
"Module".

I did found how to call C++/wasm methods from javascript i.e. something like:

```<code>var myTestInteger = Module._callMyTestMethod();
</code>```

and read strings from the
Module.wasmMemory.buffer
, but I do NOT understand how to call JavaScript from C++ code.

i.e. I would like to be able to do something like that:

```<code>#ifdef __cplusplus
extern "C" {
#endif
extern void testExternJSMethod();

int main()
{
    cout << " Hello From my Test1 !" << endl;

    testExternJSMethod();
    return 0;
}
int EMSCRIPTEN_KEEPALIVE callMyTestMethod(){
    return 26;
}
#ifdef __cplusplus
}
#endif
</code>```

and the my js method testExternMethod that I am loading in another js file called utils.js

```<code>function testExternMethod() {
  console.log("Hello from testExternMethod!" + )
}
</code>```

Here I would like to call the JavaScript testExternJSMethod from C++.

When I run the page in Firefox get "-1" in the debugger console.

So what I am missing in this case? Unfortunately The Mozilla documentation is giving only examples in those S-expressions instead of C++.

What am I missing in example? In C++ I have defined the method with the extern keyword i.e.

```<code>extern void testExternJSMethod();
</code>```

but I get the feeling that that is not all I have to do.

I believe that I should somehow link that JavaScript method to the Module somehow but I do not know how.
Module.asm gives me the exports. Which method call should give me the imports? since I believe that this _testExternJSMethod() should be in some imports method I can not figure out how to get to it.

答:
Have you tried looking at the Emscripten documentation? It has a whole section on interacting with code that details how to expose C / C++ functions to JavaScript and call JavaScript functions from C / C++.

Emscripten provides two main approaches for calling JavaScript from C/C++: running the script using emscripten_run_script() or writing “inline JavaScript”.

It is worth noting that the Mozilla documentation details plain WebAssembly, whereas Emscripten adds a lot more framework and tooling around WebAssembly in order to make it easier to port large C / C++ codebases.

ContentLicense: CC BY-SA 4.0

Body:
I was playing with WebAssembly and so far and I was able to manage emscripten compile my test C++ project to wasm file
em++ provides me 2 files i.e.

mainTest.js  mainTest.wasm

When I load mainTest.js in my html page then I get a JavaScript object called
"Module".

I did found how to call C++/wasm methods from javascript i.e. something like:

var myTestInteger = Module._callMyTestMethod();

and read strings from the
Module.wasmMemory.buffer
, but I do NOT understand how to call JavaScript from C++ code.

i.e. I would like to be able to do something like that:

#ifdef __cplusplus
extern "C" {
#endif
extern void testExternJSMethod();

int main()
{
    cout << " Hello From my Test1 !" << endl;

    testExternJSMethod();
    return 0;
}
int EMSCRIPTEN_KEEPALIVE callMyTestMethod(){
    return 26;
}
#ifdef __cplusplus
}
#endif

and the my js method testExternMethod that I am loading in another js file called utils.js

function testExternMethod() {
  console.log("Hello from testExternMethod!" + )
}

Here I would like to call the JavaScript testExternJSMethod from C++.

When I run the page in Firefox get "-1" in the debugger console.

So what I am missing in this case? Unfortunately The Mozilla documentation is giving only examples in those S-expressions instead of C++.

What am I missing in example? In C++ I have defined the method with the extern keyword i.e.

extern void testExternJSMethod();

but I get the feeling that that is not all I have to do.

I believe that I should somehow link that JavaScript method to the Module somehow but I do not know how.
Module.asm gives me the exports. Which method call should give me the imports? since I believe that this _testExternJSMethod() should be in some imports method I can not figure out how to get to it.


问:
percentage on y lab in a faceted ggplot barchart?
doing facets in ggplot I would often like the percentage to be used instead of counts.

e.g.

```<code>test1 <- sample(letters[1:2], 100, replace=T)
test2 <- sample(letters[3:8], 100, replace=T)
test <- data.frame(cbind(test1,test2))
ggplot(test, aes(test2))+geom_bar()+facet_grid(~test1)
</code>```

This is very easy but if N is different in facet A compared to facet B, it would be better I think, to compare percentages, in such a way that the each facet sums to 100%.

how would you achieve this?

Hope my question makes sense.

Sincerely.

答:
Try this:

```<code># first make a dataframe with frequencies
df <- as.data.frame(with(test, table(test1,test2)))
# or with count() from plyr package as Hadley suggested
df <- count(test, vars=c('test1', 'test2'))
# next: compute percentages per group
df <- ddply(df, .(test1), transform, p = Freq/sum(Freq))
# and plot
ggplot(df, aes(test2, p))+geom_bar()+facet_grid(~test1)
</code>```

You could also add + scale_y_continuous(formatter = "percent") to the plot for ggplot2 version 0.8.9, or + scale_y_continuous(labels = percent_format()) for version 0.9.0.

ContentLicense: CC BY-SA 2.5

Body:
doing facets in ggplot I would often like the percentage to be used instead of counts.

e.g.

test1 <- sample(letters[1:2], 100, replace=T)
test2 <- sample(letters[3:8], 100, replace=T)
test <- data.frame(cbind(test1,test2))
ggplot(test, aes(test2))+geom_bar()+facet_grid(~test1)

This is very easy but if N is different in facet A compared to facet B, it would be better I think, to compare percentages, in such a way that the each facet sums to 100%.

how would you achieve this?

Hope my question makes sense.

Sincerely.

Body:
Try this:

# first make a dataframe with frequencies
df <- as.data.frame(with(test, table(test1,test2)))
# or with count() from plyr package as Hadley suggested
df <- count(test, vars=c('test1', 'test2'))
# next: compute percentages per group
df <- ddply(df, .(test1), transform, p = Freq/sum(Freq))
# and plot
ggplot(df, aes(test2, p))+geom_bar()+facet_grid(~test1)

You could also add + scale_y_continuous(formatter = "percent") to the plot for ggplot2 version 0.8.9, or + scale_y_continuous(labels = percent_format()) for version 0.9.0.


问:
convert date and time from onetimezone to anothertimezone in php
```<code> $fromTz=">America/chicago"; //Time zone for UM6
 $toTz="America/Adak" ;//Time Zone for UM4
 $date = new DateTime($time, new DateTimeZone($fromTz));
 echo "<br>America/chicago Time ".$date->format('Y-m-d H:i:s');
 $date->setTimezone(new DateTimeZone($toTz));
 $time= $date->format('Y-m-d H:i:s');
 echo "<br>Time For $toTz ".$time;
</code>```

I have convert the date and time from onetimezone to another timezone in php.

I want to convert UM6 To UM4,UM5,UM7,UM8

but i don'nt know the value of UM5,UM7 and UM8
like UM4="America/Adak"

So what the value for UM5,UM7 and UM8

答:
Use this code </p>

```<code>$dateTime="2017-11-02T00:00:00.000Z";
date_default_timezone_set('America/chicago');
$timeZoneFrom="America/chicago";
$date = new DateTime($dateTime, new DateTimeZone($timeZoneFrom));
$time_zoneTo="America/Adak";
$date= $date->setTimezone(new DateTimeZone($time_zoneTo));
print_r($date);
or echo $date->format("Y-m-d H:i:s"); `
</code>```

Body:
 $fromTz=">America/chicago"; //Time zone for UM6
 $toTz="America/Adak" ;//Time Zone for UM4
 $date = new DateTime($time, new DateTimeZone($fromTz));
 echo "
America/chicago Time ".$date->format('Y-m-d H:i:s');
 $date->setTimezone(new DateTimeZone($toTz));
 $time= $date->format('Y-m-d H:i:s');
 echo "
Time For $toTz ".$time;

I have convert the date and time from onetimezone to another timezone in php.

I want to convert UM6 To UM4,UM5,UM7,UM8

but i don'nt know the value of UM5,UM7 and UM8
like UM4="America/Adak"

So what the value for UM5,UM7 and UM8

Body:
Use this code

$dateTime="2017-11-02T00:00:00.000Z";
date_default_timezone_set('America/chicago');
$timeZoneFrom="America/chicago";
$date = new DateTime($dateTime, new DateTimeZone($timeZoneFrom));
$time_zoneTo="America/Adak";
$date= $date->setTimezone(new DateTimeZone($time_zoneTo));
print_r($date);
or echo $date->format("Y-m-d H:i:s"); `


问:
declare variable inside or outside a loop, does it make big difference?
for example

```<code>int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}
</code>```

and

```<code>while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}
</code>```

Does it make big difference in terms of performance?

答: Computational complexity and I/O operations are most valuable things that you must considered as performance bottleneck in the programs. There is no performance difference between these two codes. Moreover, compilers do some optimization on codes and it is not unexpected if this two codes run as the same(i.e compiler convert second code to first automatically).</p>

Body:
for example

int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}

and

while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}

Does it make big difference in terms of performance?


问:
I am not able launch JNLP applications using "Java Web Start"?
Up until recently, I was able to launch/open JNLP files in Firefox using Java web start.

Don't know what happened all of a sudden JNLP files stopped launching, a splash screen appears saying Java Starting... and then nothing happens. Even the Java Console in the browser and javacpl.cpl applet doesn't open.

Tried all possibilities: removed all older version and installed the latest JRE (java version "1.6.0_17"), still it doesn't work.

Done some googling for this problem, people suggested to start javaws.exe with -viewer option but same behavior (a splash screen appears saying "Java Starting..." and then disappears)

The problem is that I don't know any place (logs etc.) to look for to see what is causing the problem.

I am using WinXP SP3, and some of the screenshots below shows further info about my system.
I can provide any other detail if required but please help me solve this problem.

答:
This can also be due to environment variable CATALINA_HOME in your system. In our organization there were several cases where JNLP applications just refused to start without logging anything and emptying CATALINA_HOME solved the issue.

I had the environment variable set in the command prompt and it didn't appear in GUI. I'm not sure if setx command or register removal commands did the trick. Restart seems to be necessary after removing the variable.


问:
Differentiation between rectangle and square in image using opencv2 python
I'm learning how to recognize shapes that're within image provided. I'm able to recognize shape by number of edges present to the geometrical body. But now I'm wondering is there any way to differentiate between square and rectangle within image?
Here's my code. Currently I'm just drawing contours to the geometrical figures.

```<code>import cv2

raw_image = cv2.imread('test1.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)

bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)

edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) >= 3)):
        contour_list.append(contour)

cv2.drawContours(raw_image, contour_list,  -1, (0,0,0), 2)
cv2.imshow('Objects Detected',raw_image)
cv2.waitKey(0)
</code>```

答:
It is a square if its width and height are same. Otherwise its a rectangle.

```<code>for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) == 4)):
        (x, y, w, h) = cv2.boundingRect(approx)
        if  ((float(w)/h)==1):
            cv2.putText(raw_image, "square", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, 0, 2)
        else:
            cv2.putText(raw_image, "rectangle", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, 0, 2)

        contour_list.append(contour)
</code>```

This change only detects squares and rectangles. Make necessary changes in the for loop to detect circles. You can work with len(approx) to make that distinction.

Body:
I'm learning how to recognize shapes that're within image provided. I'm able to recognize shape by number of edges present to the geometrical body. But now I'm wondering is there any way to differentiate between square and rectangle within image?
Here's my code. Currently I'm just drawing contours to the geometrical figures.

import cv2

raw_image = cv2.imread('test1.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)

bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)

edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) >= 3)):
        contour_list.append(contour)

cv2.drawContours(raw_image, contour_list,  -1, (0,0,0), 2)
cv2.imshow('Objects Detected',raw_image)
cv2.waitKey(0)

Body:
It is a square if its width and height are same. Otherwise its a rectangle.

for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) == 4)):
        (x, y, w, h) = cv2.boundingRect(approx)
        if  ((float(w)/h)==1):
            cv2.putText(raw_image, "square", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, 0, 2)
        else:
            cv2.putText(raw_image, "rectangle", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, 0, 2)

        contour_list.append(contour)

This change only detects squares and rectangles. Make necessary changes in the for loop to detect circles. You can work with len(approx) to make that distinction.


问:
How to use * or ? character in batch file during update of a text file using repl.bat?
```<code>@echo off & setlocal
set "search=jre1.8.0_?"
set "replace=jre1.8.0_156"
set "textfile=C:\Program Files\ABC\_ABC_installation\Uninstall_ABC.lax"
set "newfile=C:\Program Files\ABC\_ABC_installation\Uninstall_ABC1.lax"
pause;
call repl.bat "%search%" "%replace%" L < "%textfile%" >"%newfile%"
pause;
del "%textfile%"
rename "%newfile%" "%textfile%"
pause;
</code>```

The batch file should match anything like jre1.8.0_121 or jre1.8.0_152.

So I want to replace jre1.8.0_? with jre1.8.0_156, but neither ? nor * works on replace.

The replace works fine on removing this wildcard character.

答:
Deprecated repl.bat as well as JREPL.BAT use JScript which offers regular expression support.

In ECMAScript/JavaScript/JScript/Perl regular expression syntax \d+ or [0-9]+ matches 1 or more digits, i.e. a positive integer number.

So the command line to use in the batch file is one of those 2 lines on using jrepl.bat:

```<code>call jrepl.bat "jre1\.8\.0_\d+" "jre1.8.0_156" /F "%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.lax" /O -
call jrepl.bat "jre1\.8\.0_[0-9]+" "jre1.8.0_156" /F "%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.lax" /O -
</code>```

Or use one of those two lines on still using repl.bat.

```<code>set "search=jre1\.8\.0_\d+"
set "search=jre1\.8\.0_[0-9]+"
</code>```

The . has a special meaning in a regular expression search string. It means by default any character except newline characters (according to Unicode standard). To get . interpreted as literal character, it must be escaped with a backslash.

The option L must be removed on usage of repl.bat as the search string is not anymore a string to find literally, but a regular expression string.

The batch code using deprecated repl.bat can't work as long as input and output file have same name. And even on using for output file a different name, the posted batch code does not work because command rename  requires that the new file name is specified without path.

The command move can be used to replace input file by modified output file.

The entire batch code really working using deprecated repl.bat.

```<code>@echo off & setlocal
set "search=jre1\.8\.0_\d+"
set "replace=jre1.8.0_156"
set "textfile=%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.lax"
set "newfile=%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.tmp"
call repl.bat "%search%" "%replace%" <"%textfile%" >"%newfile%"
move /Y "%newfile%" "%textfile%"
</code>```

Hint: Do not use a semicolon after command pause. There is absolute no need for a semicolon. The semicolon after pause just tests the error correction handling of Windows command interpreter.

Body:
@echo off & setlocal
set "search=jre1.8.0_?"
set "replace=jre1.8.0_156"
set "textfile=C:\Program Files\ABC\_ABC_installation\Uninstall_ABC.lax"
set "newfile=C:\Program Files\ABC\_ABC_installation\Uninstall_ABC1.lax"
pause;
call repl.bat "%search%" "%replace%" L < "%textfile%" >"%newfile%"
pause;
del "%textfile%"
rename "%newfile%" "%textfile%"
pause;

The batch file should match anything like jre1.8.0_121 or jre1.8.0_152.

So I want to replace jre1.8.0_? with jre1.8.0_156, but neither ? nor * works on replace.

The replace works fine on removing this wildcard character.

Body:
Deprecated repl.bat as well as JREPL.BAT use JScript which offers regular expression support.

In ECMAScript/JavaScript/JScript/Perl regular expression syntax \d+ or [0-9]+ matches 1 or more digits, i.e. a positive integer number.

So the command line to use in the batch file is one of those 2 lines on using jrepl.bat:

call jrepl.bat "jre1\.8\.0_\d+" "jre1.8.0_156" /F "%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.lax" /O -
call jrepl.bat "jre1\.8\.0_[0-9]+" "jre1.8.0_156" /F "%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.lax" /O -

Or use one of those two lines on still using repl.bat.

set "search=jre1\.8\.0_\d+"
set "search=jre1\.8\.0_[0-9]+"

The . has a special meaning in a regular expression search string. It means by default any character except newline characters (according to Unicode standard). To get . interpreted as literal character, it must be escaped with a backslash.

The option L must be removed on usage of repl.bat as the search string is not anymore a string to find literally, but a regular expression string.

The batch code using deprecated repl.bat can't work as long as input and output file have same name. And even on using for output file a different name, the posted batch code does not work because command rename  requires that the new file name is specified without path.

The command move can be used to replace input file by modified output file.

The entire batch code really working using deprecated repl.bat.

@echo off & setlocal
set "search=jre1\.8\.0_\d+"
set "replace=jre1.8.0_156"
set "textfile=%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.lax"
set "newfile=%ProgramFiles%\ABC\_ABC_installation\Uninstall_ABC.tmp"
call repl.bat "%search%" "%replace%" <"%textfile%" >"%newfile%"
move /Y "%newfile%" "%textfile%"

Hint: Do not use a semicolon after command pause. There is absolute no need for a semicolon. The semicolon after pause just tests the error correction handling of Windows command interpreter.


问:
How to best display large number of items in program
I currently have a 952 large collection of items. I am displaying about 500+ of them as polygons, and this is causing some noticeable, but manageable lag in my application. What is the most lightweight control / element that I can use to display these items at one time?</p>

答:
DrawingVisuals provide a more lightweight approach for rendering objects than Paths:

http://msdn.microsoft.com/en-us/library/ms742254.aspx

The downside of this approach is that they do not provide events such as mouse enter / leave, you must perform hit testing manually. However, this might be OK for your needs.

There is an even more lightweight approach where you add items to the visual layer directly, you can see an example on this page:

http://msdn.microsoft.com/en-us/library/ms748373.aspx

My advice would be to try DrawingVisuals first.


问:
python selenium - selecting option from dropdown
I am attempting to use the below code to use selenium (python) to select an option from a dropdown on a webpage.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

path_to_chromedriver = 'C:/Users/User_1/chromedriver/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

url = 'https://lifeinsurance.rac.com.au/rac/get-a-quote?productid=51'
browser.get(url)

wait = WebDriverWait(browser, 10)

# residence listbox
drop_down = browser.find_element_by_xpath('//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')

browser.execute_script('arguments[0].style.display="inline";', drop_down)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')))

wait.until(EC.element_to_be_clickable((By.XPATH, r'//*[@id="ddResidentialStatusId__1_listbox"]/li[1]'))).click()
</code>```

There are occasions where it works (and an option from the dropdown is selected), but on other occasions an option from the dropdown is NOT selected (and no error raised either).

I would appreciate any feedback on how to consistently select an option from the dropdown noted in the code provided.

答:
First you can click on the select box which is always clickable

```<code>driver.find_element_by_xpath("//span[@class='k-input' and text()='Select residential status']").click()
</code>```

Then you can click on the desired item only when the list of residential status is visible (aria-hidden='false')

```<code>driver.find_element_by_xpath("//ul[@id='ddResidentialStatusId__1_listbox' and @aria-hidden='false']/li[@class='k-item' and text()='Other']").click()
</code>```

In order to work, this solution need to setup implict wait for your script

```<code>driver = webdriver.Chrome(executable_path = path_to_chromedriver)
driver.implicitly_wait(5)
</code>```

Edit: I do more tests and this solution doesn't works at each time. So I suggest you to add a small pause even it's preferable to avoid this. In this case I think it's not breakable as it's only used in order to allow the list box to be rendered completely.

```<code>driver.find_element_by_xpath("//span[@class='k-input' and text()='Select residential status']").click()
driver.find_element_by_xpath("//ul[@id='ddResidentialStatusId__1_listbox' and @aria-hidden='false']")
time.sleep(1)
driver.find_element_by_xpath("//ul[@id='ddResidentialStatusId__1_listbox' and @aria-hidden='false']/li[@class='k-item' and text()='Other']").click()
</code>```

Body:
I am attempting to use the below code to use selenium (python) to select an option from a dropdown on a webpage.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

path_to_chromedriver = 'C:/Users/User_1/chromedriver/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

url = 'https://lifeinsurance.rac.com.au/rac/get-a-quote?productid=51'
browser.get(url)

wait = WebDriverWait(browser, 10)

# residence listbox
drop_down = browser.find_element_by_xpath('//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')

browser.execute_script('arguments[0].style.display="inline";', drop_down)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')))

wait.until(EC.element_to_be_clickable((By.XPATH, r'//*[@id="ddResidentialStatusId__1_listbox"]/li[1]'))).click()

There are occasions where it works (and an option from the dropdown is selected), but on other occasions an option from the dropdown is NOT selected (and no error raised either).

I would appreciate any feedback on how to consistently select an option from the dropdown noted in the code provided.

Body:
First you can click on the select box which is always clickable

driver.find_element_by_xpath("//span[@class='k-input' and text()='Select residential status']").click()

Then you can click on the desired item only when the list of residential status is visible (aria-hidden='false')

driver.find_element_by_xpath("//ul[@id='ddResidentialStatusId__1_listbox' and @aria-hidden='false']/li[@class='k-item' and text()='Other']").click()

In order to work, this solution need to setup implict wait for your script

driver = webdriver.Chrome(executable_path = path_to_chromedriver)
driver.implicitly_wait(5)

Edit: I do more tests and this solution doesn't works at each time. So I suggest you to add a small pause even it's preferable to avoid this. In this case I think it's not breakable as it's only used in order to allow the list box to be rendered completely.

driver.find_element_by_xpath("//span[@class='k-input' and text()='Select residential status']").click()
driver.find_element_by_xpath("//ul[@id='ddResidentialStatusId__1_listbox' and @aria-hidden='false']")
time.sleep(1)
driver.find_element_by_xpath("//ul[@id='ddResidentialStatusId__1_listbox' and @aria-hidden='false']/li[@class='k-item' and text()='Other']").click()


问:
How to avoid page break inside table row for wkhtmltopdf
I am generating pdf report from html page with one table.

I am using wkhtmltopdf for the purpose.

when pdf is generated it breaks anywhere in tr tag.

I want to avoid it .

答:
I was facing the same issue add after a lot of trial n errors this css solved the issue</p>
```<code>tr {
    display: inline-table;
}
</code>```

Body:
I was facing the same issue add after a lot of trial n errors this css solved the issue

tr {
    display: inline-table;
}


问:
Node NPM Install Error typechecker@2.0.8 preinstall
When running npm install --only=production when deploying to EC2 CodeDeploy is failing with the following log.

```<code>[stdout]> typechecker@2.0.8 preinstall /home/ubuntu/node/node_modules/.staging/typechecker-58aa0eda
[stdout]> node ./cyclic.js
line 17: 20390 Killed                   npm install --only=production
npm ERR! Cannot read property 'pause' of undefined
</code>```

The only thing I changed was updating my NPM packages and updating Node. But also my rollbacks are now failing.

Any ideas how to fix this?

答: This issue was solved in NPM version 5.5.0 or something looks like. Here is the official NPM bug.</p>

Body:
When running npm install --only=production when deploying to EC2 CodeDeploy is failing with the following log.

[stdout]> typechecker@2.0.8 preinstall /home/ubuntu/node/node_modules/.staging/typechecker-58aa0eda
[stdout]> node ./cyclic.js
line 17: 20390 Killed                   npm install --only=production
npm ERR! Cannot read property 'pause' of undefined

The only thing I changed was updating my NPM packages and updating Node. But also my rollbacks are now failing.

Any ideas how to fix this?


问:
Why are CreationTime and CreatorUserId getting set on UpdateAsync?
I am calling UpdateAsync, but it's updating the CreationTime and CreatorUserId columns even if I'm not passing in these values. It should update only the required columns.

```<code>{
  "testCode": "string",
  "testName": "string",
  "testDesc": "string",
  "id": 1
}
</code>```

```<code>public async Task UpdateTest(TestDetailsDTO input)
{
    var classobj = ObjectMapper.Map<Test>(input);
    await UpdateAsync(classobj);
}
</code>```

```<code>public class TestDetailsDTO : FullAuditedEntityDto
{
    public string TestCode { get; set; }
    public string TestName { get; set; }
    public string TestDesc { get; set; }
}
</code>```

Parameter input gets CreationTime in UpdateTest service method.

```<code>public class Test : FullAuditedEntity
{
    public const int NVarcharLength20 = 20;
    public const int NVarcharLength30 = 30;
    public const int NVarcharLength50 = 50;

    [Required]
    [MaxLength(NVarcharLength20)]
    public virtual string TestCode { get; set; }

    [Required]
    [MaxLength(NVarcharLength30)]
    public virtual string TestName { get; set; }

    [MaxLength(NVarcharLength50)]
    public virtual string TestDesc { get; set; }
}
</code>```

答:
Current flow:

ObjectMapper.Map<Test>(input) creates a new Test object.

CreationTime and CreatorUserId are default(DateTime) and default(long?).

ABP sets those values.

Correct flow:

Get classobj from database.

Restore CreationTime and CreatorUserId.

Map input to classobj.

```<code>var classobj = repository.GetEntity(input.id); // 1
input.CreationTime = classobj.CreationTime;    // 2
input.CreatorUserId = classobj.CreatorUserId;  // 2
ObjectMapper.Map(input, classobj);             // 3
</code>```

Better design:

Don't inherit FullAuditedEntityDto for input → skip step 2.

It's working, any other way around? Because it's calling extra GetEntity method.

The other way is to attach. The trade-off is that you have to map explicitly, not ObjectMapper.Map.

```<code>// Create new stub with correct id and attach to context.
var classobj = new Test { Id = input.Id };
repository.As<EfRepositoryBase<MyDbContext, Test>>().Table.Attach(classobj);

// Now the entity is being tracked by EF, update required properties.
classobj.TestCode = input.TestCode;
classobj.TestName = input.TestName;
classobj.TestDesc = input.TestDesc;

// EF knows only to update the properties specified above.
_unitOfWorkManager.Current.SaveChanges();
</code>```

Body:
I am calling UpdateAsync, but it's updating the CreationTime and CreatorUserId columns even if I'm not passing in these values. It should update only the required columns.

{
  "testCode": "string",
  "testName": "string",
  "testDesc": "string",
  "id": 1
}

public async Task UpdateTest(TestDetailsDTO input)
{
    var classobj = ObjectMapper.Map<Test>(input);
    await UpdateAsync(classobj);
}

public class TestDetailsDTO : FullAuditedEntityDto
{
    public string TestCode { get; set; }
    public string TestName { get; set; }
    public string TestDesc { get; set; }
}

Parameter input gets CreationTime in UpdateTest service method.

public class Test : FullAuditedEntity
{
    public const int NVarcharLength20 = 20;
    public const int NVarcharLength30 = 30;
    public const int NVarcharLength50 = 50;

    [Required]
    [MaxLength(NVarcharLength20)]
    public virtual string TestCode { get; set; }

    [Required]
    [MaxLength(NVarcharLength30)]
    public virtual string TestName { get; set; }

    [MaxLength(NVarcharLength50)]
    public virtual string TestDesc { get; set; }
}

Body:
Current flow:

ObjectMapper.Map<Test>(input) creates a new Test object.

CreationTime and CreatorUserId are default(DateTime) and default(long?).

ABP sets those values.

Correct flow:

Get classobj from database.

Restore CreationTime and CreatorUserId.

Map input to classobj.

var classobj = repository.GetEntity(input.id); // 1
input.CreationTime = classobj.CreationTime;    // 2
input.CreatorUserId = classobj.CreatorUserId;  // 2
ObjectMapper.Map(input, classobj);             // 3

Better design:

Don't inherit FullAuditedEntityDto for input → skip step 2.

It's working, any other way around? Because it's calling extra GetEntity method.

The other way is to attach. The trade-off is that you have to map explicitly, not ObjectMapper.Map.

// Create new stub with correct id and attach to context.
var classobj = new Test { Id = input.Id };
repository.As<EfRepositoryBase<MyDbContext, Test>>().Table.Attach(classobj);

// Now the entity is being tracked by EF, update required properties.
classobj.TestCode = input.TestCode;
classobj.TestName = input.TestName;
classobj.TestDesc = input.TestDesc;

// EF knows only to update the properties specified above.
_unitOfWorkManager.Current.SaveChanges();


问:
Any reason NOT to use subdomain for development?
I was originally planning on using a local machine on our network as the development server.

Then I had the idea of using a subdomain.

So if the site was at www.example.com then the development could be done at dev.example.com.

If I did this, I would know that the entire software stack was configured exactly the same for development and production. Also development could use the same database as production removing the hassle of syncing the data. I could even use the same media (images, videos, etc.)

I have never heard of anyone else doing this, and with all these pros I am wondering why not?

What are the cons to this approach?

Update

OK, so its seems the major no no of this approach is using the same DB for dev and production. If you take that out of the equation, is it still a terrible idea?

答:
Using the production machine for development takes away your capacity to experiment. Trying out new modules/configurations can be very risky in a live environment. If I mess up our dev machine with an error in the apache conf, I will just slightly inconvenience my fellow devs. You will be shutting down the live server while people are trying to give you their money.

Not only that but you will be sharing resources with the live enviroment. You can forget about stress testing when the dev server also has to deal with actual customers. Any mistakes that can cause problems on the development server (infinite loop taking up the entire CPU, running out of HDD space, etc) suddenly become a real issue.


问:
how to read a specific line and print a specific position in this line using python
how to read specific lines from the text file, which contains several lines with the same character of "!". My goal is to find  the last line and print the position number four "[4]".

my file.txt:

```<code>     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0002   0.9879   0.8682   0.6437  -0.0000  -0.0000
.
.
.
.
!    T   E              =    -122.1058
.
.
.
!    T   E              =    -123.1050
.
.
.
!    T   E              =    -125.10584323
</code>```

my script (not working):

```<code>import sys, os
import datetime
import time as t

oTE_list = []
oTE = []

with open("file.txt","r") as f:
    text = f.readlines()
for line in text:
  if line[0] == '!':
    oTE_list.append(line[4])

# Change Lists To Number Format
for item in oTE_list:
  oTE.append(float(item))

for idx, item in enumerate(oTE_list):
    if idx == len(oTE_list) - 1:
        print(item)
number5 = (item)
</code>```

on the other hand, I managed with bash:

```<code>grep ! file.txt | awk 'END{print $5}'
</code>```

the result should be like this: -125.10584323

Thanks.

答:
This is even more simple considering its the line what you want to print

```<code>#!/usr/bin/python
#import re
with open("file1.txt") as f:
  lines = f.readlines()[-1]
  lastline = lines.split()[-1]
  print lastline
</code>```

Desired ouput from the run..

```<code>bash-4.1$ ./file1.py
-125.10584323
</code>```

In case you want all lines which are starting with "!" positionining
  into the last index value then you can use below ....

```<code>#!/usr/bin/python
import re
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1]
      print line
</code>```

Output value will be beow ..

```<code>bash-4.1$ ./file1_dup.py
-122.1058
-123.1050
-125.10584323
</code>```

Body:
how to read specific lines from the text file, which contains several lines with the same character of "!". My goal is to find  the last line and print the position number four "[4]".

my file.txt:

     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000
     1.0000   1.0000   1.0002   0.9879   0.8682   0.6437  -0.0000  -0.0000
.
.
.
.
!    T   E              =    -122.1058
.
.
.
!    T   E              =    -123.1050
.
.
.
!    T   E              =    -125.10584323

my script (not working):

import sys, os
import datetime
import time as t

oTE_list = []
oTE = []

with open("file.txt","r") as f:
    text = f.readlines()
for line in text:
  if line[0] == '!':
    oTE_list.append(line[4])

# Change Lists To Number Format
for item in oTE_list:
  oTE.append(float(item))

for idx, item in enumerate(oTE_list):
    if idx == len(oTE_list) - 1:
        print(item)
number5 = (item)

on the other hand, I managed with bash:

grep ! file.txt | awk 'END{print $5}'

the result should be like this: -125.10584323

Thanks.

Body:
This is even more simple considering its the line what you want to print

#!/usr/bin/python
#import re
with open("file1.txt") as f:
  lines = f.readlines()[-1]
  lastline = lines.split()[-1]
  print lastline

Desired ouput from the run..

bash-4.1$ ./file1.py
-125.10584323

In case you want all lines which are starting with "!" positionining
  into the last index value then you can use below ....

#!/usr/bin/python
import re
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1]
      print line

Output value will be beow ..

bash-4.1$ ./file1_dup.py
-122.1058
-123.1050
-125.10584323


问:
$broadcast vs.$stateProvider in angularJS
I am passing the response from about 5 $http  .get and .post methods from controllers to other controllers. I was planning on using broadcast to deliver those responses. However, it seems state.go might be the better route. (no pun intended :) . I already have a few states defined,  should I simply add other non url switching states for passing those parameters?
thanks </p>

答:
I would say that you should use Resolves in Angular Routes

```<code>//Example
$routeProvider
    .when("/chat", {
        templateUrl: "msgView.html",
        controller: "msgController",
        resolve: {
            messages: function($http){
                //return your $http.get calls data
        }
    }
});

//use resolve like this in controller
app.controller("msgController", function (messages) {
    $scope.messages = messages;
});
</code>```

You could also make this state an abstract or do the resolve work in your top most parent state or in the immediate parent state.

Example using ui-router

```<code>$stateProvider
  .state('chat', {
    url: '/chat',
    templateUrl: 'partials/chat.html',
    controller: 'msgController as vm',
    resolve: {
      messages: function($http){
                //return your $http.get calls data
        }
    }
  });
</code>```

By doing this you will ensure that your data is available before you init your view and controller. If your data is empty or partial then you can handle that according to the way you want in your controller like show "No data available" message or something.

This also ensures that if any error occurs in your resolve then the user will be redirected to the 404 page or any other page you specify in

```<code>$state.defaultErrorHandler((error: any) => {
                $state.transitionTo("404");
            });
</code>```

Body:
I would say that you should use Resolves in Angular Routes

//Example
$routeProvider
    .when("/chat", {
        templateUrl: "msgView.html",
        controller: "msgController",
        resolve: {
            messages: function($http){
                //return your $http.get calls data
        }
    }
});

//use resolve like this in controller
app.controller("msgController", function (messages) {
    $scope.messages = messages;
});

You could also make this state an abstract or do the resolve work in your top most parent state or in the immediate parent state.

Example using ui-router

$stateProvider
  .state('chat', {
    url: '/chat',
    templateUrl: 'partials/chat.html',
    controller: 'msgController as vm',
    resolve: {
      messages: function($http){
                //return your $http.get calls data
        }
    }
  });

By doing this you will ensure that your data is available before you init your view and controller. If your data is empty or partial then you can handle that according to the way you want in your controller like show "No data available" message or something.

This also ensures that if any error occurs in your resolve then the user will be redirected to the 404 page or any other page you specify in

$state.defaultErrorHandler((error: any) => {
                $state.transitionTo("404");
            });


问:
c++ vectors with ostream and istream
I've had this one booger of a code that I haven't been able to wrap my head around. The premise is to input a set of numbers: 3 4 5 6 7 and it will output: 4x^(3)+5x^(2)+6x^(1)+7x^(0) using istream and ostream. I'm using a vector for the numbers and the issue that I'm having is that the vector isn't filling properly.

For example if the vector is called vec1 the above input is giving out:

```<code>    `vec1[0]==4
    vec1[1]==5
    vec1[2]==6
    vec1[3]==4
    vec1[4]==4`
</code>```

but I want it to output:

```<code>    `vec1[0]==3
    vec1[1]==4
    vec1[2]==5
    vec1[3]==6
    vec1[4]==7`
</code>```

I wasn't able to find any tutorials of examples of using istream with a vector, so I was hoping someone could help me with the basics of using istream with a vector? Just a general example would be absolutely great!

PS: I'm new to c++, so I'm sorry if my use of terminology is wrong anywhere.

edit: (here's my istream code currently):

```<code>    istream& operator>>(istream& left, Polynomial& right) //input
    {
        int tsize, tmp;

        while (!(left >> tsize))
        {
            left.clear();
            left.ignore();
        }

        if (tsize < 0)
        {
            tsize *= -1;
        }

        vector<double>tmp1;
        for (int i = 0; i < tsize; i++)
        {
            tmp1.push_back(0);
        }

        right.setPolynomial(tmp1);

        for (int i = 0; i < tsize; i++)
        {
            while (!(left >> tmp))
            {
                left.clear();
                left.ignore();
            }

        right[i]=tmp;

        }
        //return a value
        return left;
    }
</code>```

`

```<code>    void Polynomial::setPolynomial(vector<double>vec1)
    {
        for (int i = 0; i < vec1.size(); i++)
            polynomial.push_back(vec1[i]);

    }
</code>```

答:
Ah, I understand. How about something like this:

```<code>#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

// A polynomial is represented as a single non-negative integer N representing
// the degree, followed by N+1 floating-point values for the coefficients in
// standard left to right order. For example:
//   3 4 5 6 7
// represents the polynomial
//   4x**3 + 5x**2 + 6x + 7

std::istream& operator >> ( std::istream& ins, Polynomial& p )
{
  // You could set p to something invalid/empty here
  // ...

  // Get the degree of the polynomial
  int degree;
  ins >> degree;
  if (degree < 0) ins.setstate( std::ios::failbit );
  if (!ins) return ins;

  // Get the polynomial's coefficients
  std::vector <double> coefficients( degree + 1 );
  std::copy_n(
    std::istream_iterator <double> ( ins ),
    degree + 1,
    coefficients.begin()
  );
  if (!ins) return ins;

  // Update p
  p.setPolynomial( coefficients );
  return ins;
}
</code>```

Proper naming of things helps, and make sure you loop through things properly. The input stream will properly log error if something is wrong, excepting only if the degree is negative, for which we need a special case.

I have used a few standard objects instead of a loop; you can use whichever you find more convenient: just remember that there are N+1 doubles following your first integer value.

Finally, remember to use your Polynomial's functions justly: if you can use a vector to set all the coefficients in a single pass, just do that.

(BTW, this code was just typed-in off the top of my head. Typos and stupid errors may have occurred.)

edit modified as per Caleth’s comment.

Title: c++ vectors with ostream and istream

Body:
I've had this one booger of a code that I haven't been able to wrap my head around. The premise is to input a set of numbers: 3 4 5 6 7 and it will output: 4x^(3)+5x^(2)+6x^(1)+7x^(0) using istream and ostream. I'm using a vector for the numbers and the issue that I'm having is that the vector isn't filling properly.

For example if the vector is called vec1 the above input is giving out:

    `vec1[0]==4
    vec1[1]==5
    vec1[2]==6
    vec1[3]==4
    vec1[4]==4`

but I want it to output:

    `vec1[0]==3
    vec1[1]==4
    vec1[2]==5
    vec1[3]==6
    vec1[4]==7`

I wasn't able to find any tutorials of examples of using istream with a vector, so I was hoping someone could help me with the basics of using istream with a vector? Just a general example would be absolutely great!

PS: I'm new to c++, so I'm sorry if my use of terminology is wrong anywhere.

edit: (here's my istream code currently):

    istream& operator>>(istream& left, Polynomial& right) //input
    {
        int tsize, tmp;

        while (!(left >> tsize))
        {
            left.clear();
            left.ignore();
        }

        if (tsize < 0)
        {
            tsize *= -1;
        }

        vector<double>tmp1;
        for (int i = 0; i < tsize; i++)
        {
            tmp1.push_back(0);
        }

        right.setPolynomial(tmp1);

        for (int i = 0; i < tsize; i++)
        {
            while (!(left >> tmp))
            {
                left.clear();
                left.ignore();
            }

        right[i]=tmp;

        }
        //return a value
        return left;
    }

`

    void Polynomial::setPolynomial(vector<double>vec1)
    {
        for (int i = 0; i < vec1.size(); i++)
            polynomial.push_back(vec1[i]);

    }

Body:
Ah, I understand. How about something like this:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

// A polynomial is represented as a single non-negative integer N representing
// the degree, followed by N+1 floating-point values for the coefficients in
// standard left to right order. For example:
//   3 4 5 6 7
// represents the polynomial
//   4x**3 + 5x**2 + 6x + 7

std::istream& operator >> ( std::istream& ins, Polynomial& p )
{
  // You could set p to something invalid/empty here
  // ...

  // Get the degree of the polynomial
  int degree;
  ins >> degree;
  if (degree < 0) ins.setstate( std::ios::failbit );
  if (!ins) return ins;

  // Get the polynomial's coefficients
  std::vector <double> coefficients( degree + 1 );
  std::copy_n(
    std::istream_iterator <double> ( ins ),
    degree + 1,
    coefficients.begin()
  );
  if (!ins) return ins;

  // Update p
  p.setPolynomial( coefficients );
  return ins;
}

Proper naming of things helps, and make sure you loop through things properly. The input stream will properly log error if something is wrong, excepting only if the degree is negative, for which we need a special case.

I have used a few standard objects instead of a loop; you can use whichever you find more convenient: just remember that there are N+1 doubles following your first integer value.

Finally, remember to use your Polynomial's functions justly: if you can use a vector to set all the coefficients in a single pass, just do that.

(BTW, this code was just typed-in off the top of my head. Typos and stupid errors may have occurred.)

edit modified as per Caleth’s comment.


问:
How to resolve MessageBodyWriter not found?
Error:
org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteToSEVERE: MessageBodyWriter not found for media type=application/vnd.xyzcompany.v1+json, type=class model.OrderStatus, genericType=class model.OrderStatu

OrderStatus is a model class.

Facing this issue when trying to return the Object of class OrderStatus.

The main reason for this is Media Type, when i tried it using application/json it worked, but need to do it with custom media type
like: application/vnd.xyzcompany.v1+json

Extra Info:
@Produces and @Consumes are used with the same media type and OrderStatus class is defined in the response of the request.

Wherever I read mostly found that, custom mime/media type need to be registered but don't know how to register and implement.

Can anyone help to resolve this issue.

Thanks in advance :)

答:
Using custom media/mime type and serializing/deserializing the received or sent object according to the new media type.

It just requires a class with "@Provider" annotation and a "@Produces". The produces annotation will be written as:  @Produces({"application/customType.v1+json", "application/json"}).

With a constructor/method having Object mapper serialization and deserialization.

NOTE: Keep this class in the package where all API classes are.

Example Code:

```<code>@Provider
@Produces({MediaType.APPLICATION_JSON, "application/customType.v1+json"})
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {

    public JacksonJsonProvider() {

        ObjectMapper objectMapper = new ObjectMapper()
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .registerModule(new JodaModule())
            .setDateFormat(new RFC3339DateFormat());

        setMapper(objectMapper);
    }
}
</code>```

Body:
Using custom media/mime type and serializing/deserializing the received or sent object according to the new media type.

It just requires a class with "@Provider" annotation and a "@Produces". The produces annotation will be written as:  @Produces({"application/customType.v1+json", "application/json"}).

With a constructor/method having Object mapper serialization and deserialization.

NOTE: Keep this class in the package where all API classes are.

Example Code:

@Provider
@Produces({MediaType.APPLICATION_JSON, "application/customType.v1+json"})
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {

    public JacksonJsonProvider() {

        ObjectMapper objectMapper = new ObjectMapper()
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .registerModule(new JodaModule())
            .setDateFormat(new RFC3339DateFormat());

        setMapper(objectMapper);
    }
}


问:
How do I make scrollbars in
 appear only when text overflows?
I have a certain number of ```</code> tags in my page, as shown. I'd like the horizontal scrollbars to appear only there are long lines of text in the tag.</p>

<p>Here is my attempt to do so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  background-color: #d0d0d0;
  overflow-x: scroll;
  margin: 3px 0;
  text-align: left;
}

main {
  max-width: 300px;
  margin: 0 auto;
}</code>```

Set up the master:
```# ./setup.sh --master
```

Set up the slaves:
```# ./setup.sh --slave --master-ip=10.0.2.2 --port=5670```
```
</div>
</div>
</p>

<p>However, the scrollbars are displayed even for <code>``` tags where there is no overflow. How can I do so?

答:
Give overflow-x: auto; instead of overflow-x: scroll;.

pre {
  background-color: #d0d0d0;
  overflow-x: auto;
  margin: 3px 0;
  text-align: left;
}

main {
  max-width: 300px;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  Set up the master:
  ```# ./setup.sh --master
  ```

  Set up the slaves:
  ```# ./setup.sh --slave --master-ip=10.0.2.2 --port=5670```
</main></code>```

Title: How do I make scrollbars in <pre> appear only when text overflows?

Body:
I have a certain number of
 tags in my page, as shown. I'd like the horizontal scrollbars to appear only there are long lines of text in the tag.

Here is my attempt to do so:

pre {
  background-color: #d0d0d0;
  overflow-x: scroll;
  margin: 3px 0;
  text-align: left;
}

main {
  max-width: 300px;
  margin: 0 auto;
}

Set up the master:

# ./setup.sh --master

Set up the slaves:

# ./setup.sh --slave --master-ip=10.0.2.2 --port=5670

However, the scrollbars are displayed even for
 tags where there is no overflow. How can I do so?

Body:
Give overflow-x: auto; instead of overflow-x: scroll;.

pre {
  background-color: #d0d0d0;
  overflow-x: auto;
  margin: 3px 0;
  text-align: left;
}

main {
  max-width: 300px;
  margin: 0 auto;
}

<main>
  Set up the master:
  <pre># ./setup.sh --master
  </pre>

  Set up the slaves:
  <pre># ./setup.sh --slave --master-ip=10.0.2.2 --port=5670</pre>
</main>


问:
Meteor React - Publish / Subscribe not working
I can't figure out where I am going wrong, but here is my code in imports/api

```<code>import { Mongo } from 'meteor/mongo';

Blogposts = new Mongo.Collection('blogposts');

if (Meteor.isServer) {

  Meteor.publish('allBlogposts', function () {
    return Blogposts.find({});
  });
}
</code>```

And in in my frontend jsx file:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import TrackerReact from 'meteor/ultimatejs:tracker-react';

Blogposts = new Mongo.Collection('blogposts');

 export default class BlogPage extends TrackerReact(React.Component) {

constructor(props) {
super(props);
this.state = {
  subscription: {
    blogposts: Meteor.subscribe('allBlogposts')
  }
}
}
</code>```

From there though, I can't seem to access any data from my database if I console log, I added two records to the database from the server.

How can I get this working for a simple console log that returns those two documents?

答:
```<code># api
import { Mongo } from 'meteor/mongo';

export default Blogposts = new Mongo.Collection('blogposts');

if (Meteor.isServer) {

   Meteor.publish('allBlogposts', function () {
      return Blogposts.find({});
   });
}
</code>```

Component

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { withTracker } from 'meteor/react-meteor-data';

#import your api
import { Blogposts } from "whatever/the/dir/is.js

class BlogPage extends Component {

# Everything here

}
#you write this function outside your component
BlogPage.propTypes = {
  currentUserPost: PropTypes.array.isRequired,
};
export default withTracker(()=>{
  Meteor.subscribe("allBlogposts");
  return {
    currentUserPost: Blogposts.find()
  }
})(BlogPage);
</code>```

Body:
I can't figure out where I am going wrong, but here is my code in imports/api

import { Mongo } from 'meteor/mongo';

Blogposts = new Mongo.Collection('blogposts');

if (Meteor.isServer) {

  Meteor.publish('allBlogposts', function () {
    return Blogposts.find({});
  });
}

And in in my frontend jsx file:

import React from 'react';
import ReactDOM from 'react-dom';
import TrackerReact from 'meteor/ultimatejs:tracker-react';

Blogposts = new Mongo.Collection('blogposts');

 export default class BlogPage extends TrackerReact(React.Component) {

constructor(props) {
super(props);
this.state = {
  subscription: {
    blogposts: Meteor.subscribe('allBlogposts')
  }
}
}

From there though, I can't seem to access any data from my database if I console log, I added two records to the database from the server.

How can I get this working for a simple console log that returns those two documents?

Body:
# api
import { Mongo } from 'meteor/mongo';

export default Blogposts = new Mongo.Collection('blogposts');

if (Meteor.isServer) {

   Meteor.publish('allBlogposts', function () {
      return Blogposts.find({});
   });
}

Component

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { withTracker } from 'meteor/react-meteor-data';

#import your api
import { Blogposts } from "whatever/the/dir/is.js

class BlogPage extends Component {

# Everything here

}
#you write this function outside your component
BlogPage.propTypes = {
  currentUserPost: PropTypes.array.isRequired,
};
export default withTracker(()=>{
  Meteor.subscribe("allBlogposts");
  return {
    currentUserPost: Blogposts.find()
  }
})(BlogPage);


问:
Is banned.h alive?
Banned.h was for several years touted as a SDL tool for C++ which could be downloaded from Microsoft as download item 24817. It looks like Microsoft has removed the file.Following link from online sources repeatedly end up at the Microsoft download center with a 404.
What is the fate of Banned.h? Has it been superseded with something else?
</p>

答:
I'm pretty certain they just made their undesirable functions reported as such by default, and you have to use _CRT_SECURE_NO_WARNINGS to stop being warned about them.

This makes sense from a security viewpoint since things should be more secure by default and require extra effort to make them less secure.

That ignores the fact, of course, that it's still relatively easy to screw things up if you misuse the "safe" (or security-enhanced) functions.

By that I mean such things as providing incorrect buffer sizes for strcpy_s, or giving an invalid but non-null pointer to fopen_s, which is, surprisingly, why they deprecated the original ones in the first place :-)

The unsafe ones are perfectly okay to use if you know what you're doing.

Title: Is banned.h alive?


问:
Function with a -> a -> a possible in Haskell?
I am going through Haskell Programming book and an in exercise on page 140, the author states this:

A hypothetical function a->a->a has two possible implementations. Write both possible versions.

I am assuming a -> a -> a  would imply a function that takes two arguments (a and a) - (which does not makes sense to me and if I declare a function with two args as a, ghci rightly complains too) and returns a

I think I am missing something, what is it?

答:
let f :: a -> a -> a, because there's no limitation on type a, the only possible 2 implementations would be just return 1st/2nd parameter, i.e.

```<code>f x _ = x
</code>```

or

```<code>f _ x = x
</code>```

Body:
let f :: a -> a -> a, because there's no limitation on type a, the only possible 2 implementations would be just return 1st/2nd parameter, i.e.

f x _ = x

or

f _ x = x


问:
joomla module that references the users component and contact component
I am looking to create a module for registering a new user for my joomla! website. So basically, I want to create a form that ask for all types of information (first name, last name, username, pw, address, phone, etc... ) and store information like the username, password, and email, in my using the joomla! com_users component and the address, phone, first name, and last name using the joomla! com_contacts component. I don't understand how/if I am able to do this. I don't know how I can reference components in my module. I don't want to rewrite either component. Thank you.</p>

答: The easiest thing to do would be to use ChronoForms. It has a built in bridge to allow custom user registration forms that would get the info you collect in to com_users. You could then set up the form to also insert the collected data in to the com_contacts table after it handles the registration. No code hacking required.</p>


问:
CMake: failed to run MSBuild command: MSBuild.exe
I am trying to build FIAT using CMake GUI on windows 10.

```<code>CMake Error at CMakeLists.txt:3 (project):
  Failed to run MSBuild command:

    MSBuild.exe

  to get the value of VCTargetsPath:
Configuring incomplete, errors occurred!
</code>```

I configured CMake to use Visual Studio 15 2017 compiler.

How can I fix this?

If needed, here is the CMakeLists.txt file

```<code>cmake_minimum_required(VERSION 3.2)
include(CheckCXXCompilerFlag)
project(FIAT CXX)

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

if(CHECK_CXX_COMPILER_USED1)
# Using Visual Studio C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "MSVCx")
# Using Intel C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "Intelx")
else(CHECK_CXX_COMPILER_USED1)
    # GCC or Clang
    # At least C++11
    CHECK_CXX_COMPILER_FLAG("-std=c++17" COMPILER_SUPPORTS_CXX17)
    CHECK_CXX_COMPILER_FLAG("-std=c++1z" COMPILER_SUPPORTS_CXX1Z)
    CHECK_CXX_COMPILER_FLAG("-std=c++14" COMPILER_SUPPORTS_CXX14)
    CHECK_CXX_COMPILER_FLAG("-std=c++1y" COMPILER_SUPPORTS_CXX1Y)
    CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
    if(COMPILER_SUPPORTS_CXX17)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
    elseif(COMPILER_SUPPORTS_CXX1Z)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1z")
    elseif(COMPILER_SUPPORTS_CXX14)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
    elseif(COMPILER_SUPPORTS_CXX1Y)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y")
    elseif(COMPILER_SUPPORTS_CXX11)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
    else(COMPILER_SUPPORTS_CXX17)
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
    endif(COMPILER_SUPPORTS_CXX17)

    if(CHECK_CXX_COMPILER_USED2)
    elseif("${CMAKE_CXX_COMPILER_ID}x" MATCHES "Clangx")
        # Using Clang
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors")
    elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "GNUx")
        # Using GCC
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic")
    endif(CHECK_CXX_COMPILER_USED2)
endif(CHECK_CXX_COMPILER_USED1)

#OpenCV
FIND_PACKAGE(OpenCV REQUIRED core imgproc highgui imgcodecs)
if(OpenCV_Found)
    INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIR})
endif(OpenCV_Found)

#Boost
FIND_PACKAGE(Boost REQUIRED program_options filesystem)
if(Boost_FOUND)
    INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
else(Boost_FOUND)
    set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "C:/local/boost_1_60_0/")
    set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "C:/local/boost_1_60_0/lib64-msvc-14.0")
    Find_PACKAGE(Boost)
    if(Boost_FOUND)
        INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
    endif(Boost_FOUND)
endif(Boost_FOUND)

set(Boost_USE_STATIC_LIBS        OFF)
set(Boost_USE_MULTITHREADED      ON)
set(Boost_USE_STATIC_RUNTIME     OFF)
set(BOOST_ALL_DYN_LINK           OFF)

# Annotation Lib
file(GLOB_RECURSE FIAT_LIB_HEADERS
    "${FIAT_SOURCE_DIR}/src/image/*.h" "${FIAT_SOURCE_DIR}/src/annotation/*.h" "${FIAT_SOURCE_DIR}/src/tools/*.h"
)

file(GLOB_RECURSE FIAT_LIB_SRC
    "${FIAT_SOURCE_DIR}/src/image/Image.cpp" "${FIAT_SOURCE_DIR}/src/annotation/*.cpp" "${FIAT_SOURCE_DIR}/src/tools/*.cpp"
)

add_library(utilities ${INCLUDE_DIRECTORIES} ${FIAT_LIB_HEADERS} ${FIAT_LIB_SRC})
target_link_libraries (utilities ${Boost_LIBRARIES} ${OpenCV_LIBRARIES} )

if(CHECK_CXX_COMPILER_USED_UTILITIES)

elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "MSVCx")
  # using Visual Studio C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "Intelx")
  # using Intel C++
else()
  # GCC or Clang
    target_link_libraries (utilities m )
endif(CHECK_CXX_COMPILER_USED_UTILITIES)

# Annotate
file(GLOB_RECURSE FIAT_ANNOTATE_HEADERS
)

file(GLOB_RECURSE FIAT_ANNOTATE_SRC
    "${FIAT_SOURCE_DIR}/src/app/annotate.cpp"
)

add_executable(annotate ${INCLUDE_DIRECTORIES} ${FIAT_LIB_HEADERS} ${FIAT_ANNOTATE_HEADERS} ${FIAT_ANNOTATE_SRC})
target_link_libraries(annotate utilities ${Boost_LIBRARIES} ${OpenCV_LIBRARIES})

if(CHECK_CXX_COMPILER_USED_ANNOTATE)
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "MSVCx")
  # using Visual Studio C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "Intelx")
  # using Intel C++
else()
  # GCC or Clang
    target_link_libraries (annotate m)
endif(CHECK_CXX_COMPILER_USED_ANNOTATE)
</code>```

As per your recommendation, I tried building from the Developer Command Prompt for VS2015 but still got the following error:

```<code>msbuild FIAT.vcxproj /p:configuration=debug
Microsoft (R) Build Engine version 14.0.25420.1
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 6/12/2017 5:16:26 AM.
Project "E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj" on node 1 (default targets).
E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj(1,1): error MSB4067: The element <#text> beneat
h element <Project> is unrecognized.
Done Building Project "E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj" (default targets) -- FA
ILED.

Build FAILED.

"E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj" (default target) (1) ->
  E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj(1,1): error MSB4067: The element <#text> bene
ath element <Project> is unrecognized.

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:00.03
</code>```

Here is my project's .vcxproj file

```<code><Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.default.props" />
  <PropertyGroup>
    <ConfigurationType>Application</ConfigurationType>
    <PlatformToolset>v120</PlatformToolset>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  Annotation.cpp Annotations.cpp app/annotate.cpp - image/Image.cpp test/image-test.cpp - tools/tools.cpp

  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotation.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotation.h" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotations.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotation.h" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/app/annotate.cpp" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/image/Image.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/image/Image.h" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/test/image-test.cpp" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/tools/tools.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/tools/tools.h" />
  </ItemGroup>

  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Targets" />
</Project>
</code>```

答:
The error reads a missing Path to MSBuild.exe

The possible solution to this is to install MSBuild.exe

Scroll down to Other Tools and Frameworks, and install Build Tools For Visual Studio

Body:
I am trying to build FIAT using CMake GUI on windows 10.

CMake Error at CMakeLists.txt:3 (project):
  Failed to run MSBuild command:

    MSBuild.exe

  to get the value of VCTargetsPath:
Configuring incomplete, errors occurred!

I configured CMake to use Visual Studio 15 2017 compiler.

How can I fix this?

If needed, here is the CMakeLists.txt file

cmake_minimum_required(VERSION 3.2)
include(CheckCXXCompilerFlag)
project(FIAT CXX)

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

if(CHECK_CXX_COMPILER_USED1)
# Using Visual Studio C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "MSVCx")
# Using Intel C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "Intelx")
else(CHECK_CXX_COMPILER_USED1)
    # GCC or Clang
    # At least C++11
    CHECK_CXX_COMPILER_FLAG("-std=c++17" COMPILER_SUPPORTS_CXX17)
    CHECK_CXX_COMPILER_FLAG("-std=c++1z" COMPILER_SUPPORTS_CXX1Z)
    CHECK_CXX_COMPILER_FLAG("-std=c++14" COMPILER_SUPPORTS_CXX14)
    CHECK_CXX_COMPILER_FLAG("-std=c++1y" COMPILER_SUPPORTS_CXX1Y)
    CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
    if(COMPILER_SUPPORTS_CXX17)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
    elseif(COMPILER_SUPPORTS_CXX1Z)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1z")
    elseif(COMPILER_SUPPORTS_CXX14)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
    elseif(COMPILER_SUPPORTS_CXX1Y)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y")
    elseif(COMPILER_SUPPORTS_CXX11)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
    else(COMPILER_SUPPORTS_CXX17)
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
    endif(COMPILER_SUPPORTS_CXX17)

    if(CHECK_CXX_COMPILER_USED2)
    elseif("${CMAKE_CXX_COMPILER_ID}x" MATCHES "Clangx")
        # Using Clang
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors")
    elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "GNUx")
        # Using GCC
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic")
    endif(CHECK_CXX_COMPILER_USED2)
endif(CHECK_CXX_COMPILER_USED1)

#OpenCV
FIND_PACKAGE(OpenCV REQUIRED core imgproc highgui imgcodecs)
if(OpenCV_Found)
    INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIR})
endif(OpenCV_Found)

#Boost
FIND_PACKAGE(Boost REQUIRED program_options filesystem)
if(Boost_FOUND)
    INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
else(Boost_FOUND)
    set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "C:/local/boost_1_60_0/")
    set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "C:/local/boost_1_60_0/lib64-msvc-14.0")
    Find_PACKAGE(Boost)
    if(Boost_FOUND)
        INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
    endif(Boost_FOUND)
endif(Boost_FOUND)

set(Boost_USE_STATIC_LIBS        OFF)
set(Boost_USE_MULTITHREADED      ON)
set(Boost_USE_STATIC_RUNTIME     OFF)
set(BOOST_ALL_DYN_LINK           OFF)

# Annotation Lib
file(GLOB_RECURSE FIAT_LIB_HEADERS
    "${FIAT_SOURCE_DIR}/src/image/*.h" "${FIAT_SOURCE_DIR}/src/annotation/*.h" "${FIAT_SOURCE_DIR}/src/tools/*.h"
)

file(GLOB_RECURSE FIAT_LIB_SRC
    "${FIAT_SOURCE_DIR}/src/image/Image.cpp" "${FIAT_SOURCE_DIR}/src/annotation/*.cpp" "${FIAT_SOURCE_DIR}/src/tools/*.cpp"
)

add_library(utilities ${INCLUDE_DIRECTORIES} ${FIAT_LIB_HEADERS} ${FIAT_LIB_SRC})
target_link_libraries (utilities ${Boost_LIBRARIES} ${OpenCV_LIBRARIES} )

if(CHECK_CXX_COMPILER_USED_UTILITIES)

elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "MSVCx")
  # using Visual Studio C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "Intelx")
  # using Intel C++
else()
  # GCC or Clang
    target_link_libraries (utilities m )
endif(CHECK_CXX_COMPILER_USED_UTILITIES)

# Annotate
file(GLOB_RECURSE FIAT_ANNOTATE_HEADERS
)

file(GLOB_RECURSE FIAT_ANNOTATE_SRC
    "${FIAT_SOURCE_DIR}/src/app/annotate.cpp"
)

add_executable(annotate ${INCLUDE_DIRECTORIES} ${FIAT_LIB_HEADERS} ${FIAT_ANNOTATE_HEADERS} ${FIAT_ANNOTATE_SRC})
target_link_libraries(annotate utilities ${Boost_LIBRARIES} ${OpenCV_LIBRARIES})

if(CHECK_CXX_COMPILER_USED_ANNOTATE)
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "MSVCx")
  # using Visual Studio C++
elseif("${CMAKE_CXX_COMPILER_ID}x" STREQUAL "Intelx")
  # using Intel C++
else()
  # GCC or Clang
    target_link_libraries (annotate m)
endif(CHECK_CXX_COMPILER_USED_ANNOTATE)

As per your recommendation, I tried building from the Developer Command Prompt for VS2015 but still got the following error:

msbuild FIAT.vcxproj /p:configuration=debug
Microsoft (R) Build Engine version 14.0.25420.1
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 6/12/2017 5:16:26 AM.
Project "E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj" on node 1 (default targets).
E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj(1,1): error MSB4067: The element <#text> beneat
h element <Project> is unrecognized.
Done Building Project "E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj" (default targets) -- FA
ILED.

Build FAILED.

"E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj" (default target) (1) ->
  E:\Work\FastImageAnnotationTool-master\FIAT.vcxproj(1,1): error MSB4067: The element <#text> bene
ath element <Project> is unrecognized.

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:00.03

Here is my project's .vcxproj file

<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.default.props" />
  <PropertyGroup>
    <ConfigurationType>Application</ConfigurationType>
    <PlatformToolset>v120</PlatformToolset>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  Annotation.cpp Annotations.cpp app/annotate.cpp - image/Image.cpp test/image-test.cpp - tools/tools.cpp

  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotation.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotation.h" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotations.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/annotation/Annotation.h" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/app/annotate.cpp" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/image/Image.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/image/Image.h" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/test/image-test.cpp" />
  </ItemGroup>

  <ItemGroup>
    <ClInclude Include="/src/tools/tools.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="/src/tools/tools.h" />
  </ItemGroup>

  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Targets" />
</Project>


问:
Set Fragment on Tab with multi line title
I'm working with two fragments that I'm setting on the Tabs.

I have two issues:

I want to set the title of the fragment in multi line instead of "..."

here's the code to add fragment and set its title

```<code>ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Current\nSubscription");
</code>```

I want to remove the extra space from around the icon and text on the tab to make it more compact and save some space.

答:
Showing "..." in tab titles will not make a good UI experience I suggest that you should set tabmode to scrollable and let tab titles take as much space they want. </p>

```<code><android.support.design.widget.TabLayout
                android:id="@+id/htab_tabs"
                android:layout_width="wrap_content"
                android:layout_height="?attr/actionBarSize"
                android:layout_gravity="bottom"
                app:tabIndicatorColor="@android:color/white"
                app:tabMode="scrollable" />
</code>```

Body:
I'm working with two fragments that I'm setting on the Tabs.

I have two issues:

I want to set the title of the fragment in multi line instead of "..."

here's the code to add fragment and set its title

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Current\nSubscription");

I want to remove the extra space from around the icon and text on the tab to make it more compact and save some space.

Body:
Showing "..." in tab titles will not make a good UI experience I suggest that you should set tabmode to scrollable and let tab titles take as much space they want.

<android.support.design.widget.TabLayout
                android:id="@+id/htab_tabs"
                android:layout_width="wrap_content"
                android:layout_height="?attr/actionBarSize"
                android:layout_gravity="bottom"
                app:tabIndicatorColor="@android:color/white"
                app:tabMode="scrollable" />


问:
How to set space between radio button to text in xamarin forms
My Custom renderer for Radio Button is,

public class RadioButtonRenderer : ViewRenderer
    {

```<code>    protected override void OnElementChanged(ElementChangedEventArgs<CustomRadioButton> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            e.OldElement.PropertyChanged += ElementOnPropertyChanged;
        }

        if (this.Control == null)
        {
            var radButton = new RadioButton(this.Context);
            radButton.CheckedChange += radButton_CheckedChange;

            this.SetNativeControl(radButton);
        }

        Control.Text = e.NewElement.Text;
        Control.Checked = e.NewElement.Checked;

        Element.PropertyChanged += ElementOnPropertyChanged;
    }
</code>```

Can anybody know how to set space between radio button to text.

答:
Android RadioButton widget is a CompoundButton and you can set its TextView's relative padding:

```<code>Control.SetPaddingRelative(150, 0, 0, 0);
</code>```

Body:
My Custom renderer for Radio Button is,

public class RadioButtonRenderer : ViewRenderer
    {

    protected override void OnElementChanged(ElementChangedEventArgs<CustomRadioButton> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            e.OldElement.PropertyChanged += ElementOnPropertyChanged;
        }

        if (this.Control == null)
        {
            var radButton = new RadioButton(this.Context);
            radButton.CheckedChange += radButton_CheckedChange;

            this.SetNativeControl(radButton);
        }

        Control.Text = e.NewElement.Text;
        Control.Checked = e.NewElement.Checked;

        Element.PropertyChanged += ElementOnPropertyChanged;
    }

Can anybody know how to set space between radio button to text.

Body:
Android RadioButton widget is a CompoundButton and you can set its TextView's relative padding:

Control.SetPaddingRelative(150, 0, 0, 0);


问:
Angular 2 | How to sort numeric value using pipe?
Good day,

How can i sort numeric value in angular 2 using pipes? or is their any builtin pipes for sorting numbers?

```<code><div class="group group1">
<div *ngFor="let apidata of data">
  <div *ngIf="apidata.AssignmentNumber[0] == 1" class="box">
      <div class="box-assignmentnumber-holder">
        <span id="AssignmentNumber" [ngStyle]="{'color': apidata.AssignmentNumber[1] == 1 ? '#FF8C00' : 'green'}">{{apidata.AssignmentNumber | desc}}</span>
      </div>
      <div id="arrow" (click)="this.clickMe =! this.clickMe"></div>
  </div>
</div>
</code>```

above is my code in displaying number, but i want to sort them in ascending order.

答:
you can refer this example of sorting numbers and words. this is inspired from http://embed.plnkr.co/DHLVc0

Example use

Basic Array of single type: *ngFor="#todo of todoService.todos | orderBy : '-'"

Multidimensional Array Sort on single column: *ngFor="#todo of todoService.todos | orderBy : ['-status']"

Multidimensional Array Sort on multiple columns: *ngFor="#todo of todoService.todos | orderBy : ['status', '-title']"

```<code>orderBy.ts

        import {Pipe, PipeTransform} from 'angular2/core';

        @Pipe({name: 'orderBy', pure: false})
        export class OrderBy implements PipeTransform {

            static _orderByComparator(a:any, b:any):number{

              if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
                //Isn't a number so lowercase the string to properly compare
                if(a.toLowerCase() < b.toLowerCase()) return -1;
                if(a.toLowerCase() > b.toLowerCase()) return 1;
              }
              else{
                //Parse strings as numbers to compare properly
                if(parseFloat(a) < parseFloat(b)) return -1;
                if(parseFloat(a) > parseFloat(b)) return 1;
              }

              return 0; //equal each other
            }

            transform(input:any, [config = '+']): any{

                if(!Array.isArray(input)) return input;

                if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
                    var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
                    var desc = propertyToCheck.substr(0, 1) == '-';

                    //Basic array
                    if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
                        return !desc ? input.sort() : input.sort().reverse();
                    }
                    else {
                        var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                            ? propertyToCheck.substr(1)
                            : propertyToCheck;

                        return input.sort(function(a:any,b:any){
                            return !desc
                                ? OrderBy._orderByComparator(a[property], b[property])
                                : -OrderBy._orderByComparator(a[property], b[property]);
                        });
                    }
                }
                else {
                    //Loop over property of the array in order and sort
                    return input.sort(function(a:any,b:any){
                        for(var i:number = 0; i < config.length; i++){
                            var desc = config[i].substr(0, 1) == '-';
                            var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                                ? config[i].substr(1)
                                : config[i];

                            var comparison = !desc
                                ? OrderBy._orderByComparator(a[property], b[property])
                                : -OrderBy._orderByComparator(a[property], b[property]);

                            //Don't return 0 yet in case of needing to sort by next property
                            if(comparison != 0) return comparison;
                        }

                        return 0; //equal each other
                    });
                }
            }
        }
</code>```

Body:
Good day,

How can i sort numeric value in angular 2 using pipes? or is their any builtin pipes for sorting numbers?

        {{apidata.AssignmentNumber | desc}}

above is my code in displaying number, but i want to sort them in ascending order.

Body:
you can refer this example of sorting numbers and words. this is inspired from http://embed.plnkr.co/DHLVc0

Example use

Basic Array of single type: *ngFor="#todo of todoService.todos | orderBy : '-'"

Multidimensional Array Sort on single column: *ngFor="#todo of todoService.todos | orderBy : ['-status']"

Multidimensional Array Sort on multiple columns: *ngFor="#todo of todoService.todos | orderBy : ['status', '-title']"

orderBy.ts

        import {Pipe, PipeTransform} from 'angular2/core';

        @Pipe({name: 'orderBy', pure: false})
        export class OrderBy implements PipeTransform {

            static _orderByComparator(a:any, b:any):number{

              if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
                //Isn't a number so lowercase the string to properly compare
                if(a.toLowerCase() < b.toLowerCase()) return -1;
                if(a.toLowerCase() > b.toLowerCase()) return 1;
              }
              else{
                //Parse strings as numbers to compare properly
                if(parseFloat(a) < parseFloat(b)) return -1;
                if(parseFloat(a) > parseFloat(b)) return 1;
              }

              return 0; //equal each other
            }

            transform(input:any, [config = '+']): any{

                if(!Array.isArray(input)) return input;

                if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
                    var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
                    var desc = propertyToCheck.substr(0, 1) == '-';

                    //Basic array
                    if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
                        return !desc ? input.sort() : input.sort().reverse();
                    }
                    else {
                        var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                            ? propertyToCheck.substr(1)
                            : propertyToCheck;

                        return input.sort(function(a:any,b:any){
                            return !desc
                                ? OrderBy._orderByComparator(a[property], b[property])
                                : -OrderBy._orderByComparator(a[property], b[property]);
                        });
                    }
                }
                else {
                    //Loop over property of the array in order and sort
                    return input.sort(function(a:any,b:any){
                        for(var i:number = 0; i < config.length; i++){
                            var desc = config[i].substr(0, 1) == '-';
                            var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                                ? config[i].substr(1)
                                : config[i];

                            var comparison = !desc
                                ? OrderBy._orderByComparator(a[property], b[property])
                                : -OrderBy._orderByComparator(a[property], b[property]);

                            //Don't return 0 yet in case of needing to sort by next property
                            if(comparison != 0) return comparison;
                        }

                        return 0; //equal each other
                    });
                }
            }
        }


问:
IF...<Sql query>....ELSE IF ....<Sql query>...Else
I am trying to use query in NamedParameterJdbcTemplate by writing a query with if condition for Postgresql.

I will be passing 2 parameters to the query, store and tot_store. I tried following query but it doesn't work. Any suggestion?

```<code>IF (:store=1)
BEGIN
    SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store asc;
END
ELSE IF (:store = 2)
BEGIN
    SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store asc;
END
ELSE
BEGIN
    SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store desc;
END
</code>```

The error says

```<code>syntax error at or near "IF"
</code>```

Thank you in advance

答:
PostgreSQL doesn't accept IF as a top level statement. It's not SQL-standard either.

Use CASE ... WHEN ...

IF is permitted in PL/PgSQL code blocks, though; see DO and CREATE FUNCTION.

In this case I'd write a single SQL statement and

```<code>ORDER BY
  CASE WHEN store IN (1,2) THEN -store
  ELSE store
  END DESC
</code>```

(untested)

Body:
I am trying to use query in NamedParameterJdbcTemplate by writing a query with if condition for Postgresql.

I will be passing 2 parameters to the query, store and tot_store. I tried following query but it doesn't work. Any suggestion?

IF (:store=1)
BEGIN
    SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store asc;
END
ELSE IF (:store = 2)
BEGIN
    SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store asc;
END
ELSE
BEGIN
    SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store desc;
END

The error says

syntax error at or near "IF"

Thank you in advance

Body:
PostgreSQL doesn't accept IF as a top level statement. It's not SQL-standard either.

Use CASE ... WHEN ...

IF is permitted in PL/PgSQL code blocks, though; see DO and CREATE FUNCTION.

In this case I'd write a single SQL statement and

ORDER BY
  CASE WHEN store IN (1,2) THEN -store
  ELSE store
  END DESC

(untested)