问:
Efficiently Implementing Java Native Interface Webcam Feed
I'm working on a project that takes video input from a webcam and displays regions of motion to the user.  My "beta" attempt at this project was to use the Java Media Framework to retrieve the webcam feed.  Through some utility functions, JMF conveniently returns webcam frames as BufferedImages, which I built a significant amount of framework around to process.  However, I soon realized that JMF isn't well supported by Sun/Oracle anymore, and some of the higher webcam resolutions (720p) are not accessible through the JMF interface.

I'd like to continue processing frames as BufferedImages, and use OpenCV (C++) to source the video feed.  Using OpenCV's framework alone, I've found that OpenCV does a good job of efficiently returning high-def webcam frames and painting them to screen.

I figured it would be pretty straightforward to feed this data into Java and achieve the same efficiency.  I just finished writing the JNI DLL to copy this data into a BufferedImage and return it to Java.  However, I'm finding that the amount of data copying I'm doing is really hindering performance.  I'm targeting 30 FPS, but it takes roughly 100 msec alone to even copy the data from the char array returned by OpenCV into a Java BufferedImage.  Instead, I'm seeing about 2-5 FPS.

When returning a frame capture, OpenCV provides a pointer to a 1D char array.  This data needs to be provided to Java, and apparently I don't have the time to copy any of it.

I need a better solution to get these frame captures into a BufferedImage.  A few solutions I'm considering, none of which I think are very good (fairly certain they would also perform poorly):

(1) Override BufferedImage, and return pixel data from various BufferedImage methods by making native calls to the DLL.  (Instead of doing the array copying at once, I return individual pixels as requested by the calling code).  Note that calling code typically needs all pixels in the image to paint the image or process it, so this individual pixel-grab operation would be implemented in a 2D for-loop.

(2) Instruct the BufferedImage to use a java.nio.ByteBuffer to somehow directly access data in the char array returned by OpenCV.  Would appreciate any tips as to how this is done.

(3) Do everything in C++ and forget Java.  Well well, yes this does sound like the most logical solution, however I will not have time to start this many-month project from scratch.

As of now, my JNI code has been written to return the BufferedImage, however at this point I'm willing to accept the return of a 1D char array and then put it into a BufferedImage.

By the way... the question here is:  What is the most efficient way to copy a 1D char array of image data into a BufferedImage?

Provided is the (inefficient) code that I use to source image from OpenCV and copy into BufferedImage:

```<code>JNIEXPORT jobject JNICALL Java_graphicanalyzer_ImageFeedOpenCV_getFrame
  (JNIEnv * env, jobject jThis, jobject camera)
{
 //get the memory address of the CvCapture device, the value of which is encapsulated in the camera jobject
 jclass cameraClass = env->FindClass("graphicanalyzer/Camera");
 jfieldID fid = env->GetFieldID(cameraClass,"pCvCapture","I");

 //get the address of the CvCapture device
 int a_pCvCapture = (int)env->GetIntField(camera, fid);

 //get a pointer to the CvCapture device
    CvCapture *capture = (CvCapture*)a_pCvCapture;

 //get a frame from the CvCapture device
 IplImage *frame = cvQueryFrame( capture );

 //get a handle on the BufferedImage class
 jclass bufferedImageClass = env->FindClass("java/awt/image/BufferedImage");
 if (bufferedImageClass == NULL)
 {
  return NULL;
 }

 //get a handle on the BufferedImage(int width, int height, int imageType) constructor
 jmethodID bufferedImageConstructor = env->GetMethodID(bufferedImageClass,"<init>","(III)V");

 //get the field ID of BufferedImage.TYPE_INT_RGB
 jfieldID imageTypeFieldID = env->GetStaticFieldID(bufferedImageClass,"TYPE_INT_RGB","I");

 //get the int value from the BufferedImage.TYPE_INT_RGB field
 jint imageTypeIntRGB = env->GetStaticIntField(bufferedImageClass,imageTypeFieldID);

 //create a new BufferedImage
 jobject ret = env->NewObject(bufferedImageClass, bufferedImageConstructor, (jint)frame->width, (jint)frame->height, imageTypeIntRGB);

 //get a handle on the method BufferedImage.getRaster()
 jmethodID getWritableRasterID = env->GetMethodID(bufferedImageClass, "getRaster", "()Ljava/awt/image/WritableRaster;");

 //call the BufferedImage.getRaster() method
 jobject writableRaster = env->CallObjectMethod(ret,getWritableRasterID);

 //get a handle on the WritableRaster class
 jclass writableRasterClass = env->FindClass("java/awt/image/WritableRaster");

 //get a handle on the WritableRaster.setPixel(int x, int y, int[] rgb) method
 jmethodID setPixelID = env->GetMethodID(writableRasterClass, "setPixel", "(II[I)V"); //void setPixel(int, int, int[])

 //iterate through the frame we got above and set each pixel within the WritableRaster
 jintArray rgbArray = env->NewIntArray(3);
 jint rgb[3];
 char *px;
 for (jint x=0; x < frame->width; x++)
 {
  for (jint y=0; y < frame->height; y++)
  {
   px = frame->imageData+(frame->widthStep*y+x*frame->nChannels);
   rgb[0] = abs(px[2]);  // OpenCV returns BGR bit order
   rgb[1] = abs(px[1]);  // OpenCV returns BGR bit order
   rgb[2] = abs(px[0]);  // OpenCV returns BGR bit order
   //copy jint array into jintArray
   env->SetIntArrayRegion(rgbArray,0,3,rgb); //take values in rgb and move to rgbArray
   //call setPixel()  this is a copy operation
   env->CallVoidMethod(writableRaster,setPixelID,x,y,rgbArray);
  }
 }

 return ret;  //return the BufferedImage
}
</code>```

答:
As a secondary consideration, if the only difference between the image data array returned by OpenCV and what is required by Java is the BGR vs RGB, then

```<code>px = frame->imageData+(frame->widthStep*y+x*frame->nChannels);
rgb[0] = abs(px[2]);  // OpenCV returns BGR bit order
rgb[1] = abs(px[1]);  // OpenCV returns BGR bit order
rgb[2] = abs(px[0]);  // OpenCV returns BGR bit order
</code>```

is a relatively inefficient way to convert them.  Instead you could do something like:

```<code>uint32 px = frame->imageData+(frame->widthStep*y+x*frame->nChannels);
javaArray[ofs]=((px&0x00FF0000)>>16)|(px&0x0000FF00)|((px&0x000000FF)<<16);
</code>```

(note my C code is rusty, so this might not be entirely valid, but it shows what is needed).

Body:
I'm working on a project that takes video input from a webcam and displays regions of motion to the user.  My "beta" attempt at this project was to use the Java Media Framework to retrieve the webcam feed.  Through some utility functions, JMF conveniently returns webcam frames as BufferedImages, which I built a significant amount of framework around to process.  However, I soon realized that JMF isn't well supported by Sun/Oracle anymore, and some of the higher webcam resolutions (720p) are not accessible through the JMF interface.

I'd like to continue processing frames as BufferedImages, and use OpenCV (C++) to source the video feed.  Using OpenCV's framework alone, I've found that OpenCV does a good job of efficiently returning high-def webcam frames and painting them to screen.

I figured it would be pretty straightforward to feed this data into Java and achieve the same efficiency.  I just finished writing the JNI DLL to copy this data into a BufferedImage and return it to Java.  However, I'm finding that the amount of data copying I'm doing is really hindering performance.  I'm targeting 30 FPS, but it takes roughly 100 msec alone to even copy the data from the char array returned by OpenCV into a Java BufferedImage.  Instead, I'm seeing about 2-5 FPS.

When returning a frame capture, OpenCV provides a pointer to a 1D char array.  This data needs to be provided to Java, and apparently I don't have the time to copy any of it.

I need a better solution to get these frame captures into a BufferedImage.  A few solutions I'm considering, none of which I think are very good (fairly certain they would also perform poorly):

(1) Override BufferedImage, and return pixel data from various BufferedImage methods by making native calls to the DLL.  (Instead of doing the array copying at once, I return individual pixels as requested by the calling code).  Note that calling code typically needs all pixels in the image to paint the image or process it, so this individual pixel-grab operation would be implemented in a 2D for-loop.

(2) Instruct the BufferedImage to use a java.nio.ByteBuffer to somehow directly access data in the char array returned by OpenCV.  Would appreciate any tips as to how this is done.

(3) Do everything in C++ and forget Java.  Well well, yes this does sound like the most logical solution, however I will not have time to start this many-month project from scratch.

As of now, my JNI code has been written to return the BufferedImage, however at this point I'm willing to accept the return of a 1D char array and then put it into a BufferedImage.

By the way... the question here is:  What is the most efficient way to copy a 1D char array of image data into a BufferedImage?

Provided is the (inefficient) code that I use to source image from OpenCV and copy into BufferedImage:

JNIEXPORT jobject JNICALL Java_graphicanalyzer_ImageFeedOpenCV_getFrame
  (JNIEnv * env, jobject jThis, jobject camera)
{
 //get the memory address of the CvCapture device, the value of which is encapsulated in the camera jobject
 jclass cameraClass = env->FindClass("graphicanalyzer/Camera");
 jfieldID fid = env->GetFieldID(cameraClass,"pCvCapture","I");

 //get the address of the CvCapture device
 int a_pCvCapture = (int)env->GetIntField(camera, fid);

 //get a pointer to the CvCapture device
    CvCapture *capture = (CvCapture*)a_pCvCapture;

 //get a frame from the CvCapture device
 IplImage *frame = cvQueryFrame( capture );

 //get a handle on the BufferedImage class
 jclass bufferedImageClass = env->FindClass("java/awt/image/BufferedImage");
 if (bufferedImageClass == NULL)
 {
  return NULL;
 }

 //get a handle on the BufferedImage(int width, int height, int imageType) constructor
 jmethodID bufferedImageConstructor = env->GetMethodID(bufferedImageClass,"<init>","(III)V");

 //get the field ID of BufferedImage.TYPE_INT_RGB
 jfieldID imageTypeFieldID = env->GetStaticFieldID(bufferedImageClass,"TYPE_INT_RGB","I");

 //get the int value from the BufferedImage.TYPE_INT_RGB field
 jint imageTypeIntRGB = env->GetStaticIntField(bufferedImageClass,imageTypeFieldID);

 //create a new BufferedImage
 jobject ret = env->NewObject(bufferedImageClass, bufferedImageConstructor, (jint)frame->width, (jint)frame->height, imageTypeIntRGB);

 //get a handle on the method BufferedImage.getRaster()
 jmethodID getWritableRasterID = env->GetMethodID(bufferedImageClass, "getRaster", "()Ljava/awt/image/WritableRaster;");

 //call the BufferedImage.getRaster() method
 jobject writableRaster = env->CallObjectMethod(ret,getWritableRasterID);

 //get a handle on the WritableRaster class
 jclass writableRasterClass = env->FindClass("java/awt/image/WritableRaster");

 //get a handle on the WritableRaster.setPixel(int x, int y, int[] rgb) method
 jmethodID setPixelID = env->GetMethodID(writableRasterClass, "setPixel", "(II[I)V"); //void setPixel(int, int, int[])

 //iterate through the frame we got above and set each pixel within the WritableRaster
 jintArray rgbArray = env->NewIntArray(3);
 jint rgb[3];
 char *px;
 for (jint x=0; x < frame->width; x++)
 {
  for (jint y=0; y < frame->height; y++)
  {
   px = frame->imageData+(frame->widthStep*y+x*frame->nChannels);
   rgb[0] = abs(px[2]);  // OpenCV returns BGR bit order
   rgb[1] = abs(px[1]);  // OpenCV returns BGR bit order
   rgb[2] = abs(px[0]);  // OpenCV returns BGR bit order
   //copy jint array into jintArray
   env->SetIntArrayRegion(rgbArray,0,3,rgb); //take values in rgb and move to rgbArray
   //call setPixel()  this is a copy operation
   env->CallVoidMethod(writableRaster,setPixelID,x,y,rgbArray);
  }
 }

 return ret;  //return the BufferedImage
}

Body:
As a secondary consideration, if the only difference between the image data array returned by OpenCV and what is required by Java is the BGR vs RGB, then

px = frame->imageData+(frame->widthStep*y+x*frame->nChannels);
rgb[0] = abs(px[2]);  // OpenCV returns BGR bit order
rgb[1] = abs(px[1]);  // OpenCV returns BGR bit order
rgb[2] = abs(px[0]);  // OpenCV returns BGR bit order

is a relatively inefficient way to convert them.  Instead you could do something like:

uint32 px = frame->imageData+(frame->widthStep*y+x*frame->nChannels);
javaArray[ofs]=((px&0x00FF0000)>>16)|(px&0x0000FF00)|((px&0x000000FF)<<16);

(note my C code is rusty, so this might not be entirely valid, but it shows what is needed).


来源: stackexchange

问:
Angular2 build under angular-cli with directive and ng build --prod
I have an angular-cli app,

```<code>npm -v 3.10.8
node -v v6.9.1
angular2 ^2.4.0
angular/cli 1.0.0-beta.32.3
</code>```

when I add to package.json this

```<code>"angular2-auto-scroll": "1.0.12"
</code>```

angular2-auto-scrol website

and in app.module.ts import it

```<code>import { Angular2AutoScroll } from "angular2-auto-scroll/lib/angular2-auto-scroll.directive";
</code>```

and add it to declarations section ng build --prod fails with this error

```<code>ERROR in Unexpected value 'Angular2AutoScroll in C:/coding/workspace/myapp/myapp-web/node_modules/angular2-auto-scroll/lib/angular2-auto-scroll.directive.d.ts' declared by the module 'AppModule in C:/coding/workspace/myapp/myapp-web/app_code/app/app.module.ts'
ERROR in ./app_code/main.ts Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'C:\coding\workspace\myapp\myapp-web\app_code'
 @ ./app_code/main.ts 6:0-74
 @ multi ./app_code/main.ts
</code>```

however when I build with just ng build without --prod then all build fine.
Does anyone know what could be the reason? Or any other way I can import this npm package so it does not fail PROD build?

答:
The issue is with AOT compilation. AOT happens by default when using --prod flag.

take a look at the source code for angular2-auto-scroll That project defines one TS file in the src/angular2-auto-scroll.directive.ts

If you look at the tsconfig.js file specifically  "module": "commonjs". you'll see that the module this directive transpiles to is commonjs
If you look in your project under C:/coding/workspace/myapp/myapp-web/node_modules/angular2-auto-scroll/lib/ you'll see a TS type definition .d.ts, a .js and a .map file. the js file is a commonjs module.

AOT does not like commonjs modules, you can research that on your own, it needs either an es5 or es6 module.

All that said, here are some options to fix it

Copy the directive TS file from the source github angular2-auto-scroll.directive.ts  to your prject and remove the dependency.

or you can make a pull request to the repo asking to change the "module": "commonjs" to "module": "es6" note: I opened an issue for it here

or if you do not care for aot, (which is highly recommended btw), you can cancel it by running buildcommand with --aot=false read here on build options

hope this helps.

Resources on AOT:
https://angular.io/docs/ts/latest/cookbook/aot-compiler.html
https://github.com/angular/angular-cli/issues/1732

ContentLicense: CC BY-SA 3.0

Body:
I have an angular-cli app,

npm -v 3.10.8
node -v v6.9.1
angular2 ^2.4.0
angular/cli 1.0.0-beta.32.3

when I add to package.json this

"angular2-auto-scroll": "1.0.12"

angular2-auto-scrol website

and in app.module.ts import it

import { Angular2AutoScroll } from "angular2-auto-scroll/lib/angular2-auto-scroll.directive";

and add it to declarations section ng build --prod fails with this error

ERROR in Unexpected value 'Angular2AutoScroll in C:/coding/workspace/myapp/myapp-web/node_modules/angular2-auto-scroll/lib/angular2-auto-scroll.directive.d.ts' declared by the module 'AppModule in C:/coding/workspace/myapp/myapp-web/app_code/app/app.module.ts'
ERROR in ./app_code/main.ts Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'C:\coding\workspace\myapp\myapp-web\app_code'
 @ ./app_code/main.ts 6:0-74
 @ multi ./app_code/main.ts

however when I build with just ng build without --prod then all build fine.
Does anyone know what could be the reason? Or any other way I can import this npm package so it does not fail PROD build?


问:
Rsolnp: In cbind(temp, funv) : number of rows of result is not a multiple of vector length (arg 1)
I'm new to stackoverflow and searched a lot, but couldn't find an answer to my question. I'm trying to minimise the problem bellow with the optimisation package Rsolnp. Although the solver gives me a solution, every time I run the code I get the following warning message:

Warning messages: 1: In cbind(temp, funv) :
  number of rows of result is not a multiple of vector length (arg 1)

Furthermore, the solution is completely different from the solutions I get with ipop and solve.QP. Their solutions are almost the same (0.2480, 0.0000, 0.0121, 0.7400).
I tried many different formulations of the problem, but could not figure out what I did wrong. I am thankful for all help and information!

```<code>library(Rsolnp)
# Starting Values
x0 <- c(0.25,0,0.01,0.75)

fn <- function(x){
  d <- c(0.0308, 0.0269, 0.0145, 0.0130)
  d <- -d
  D <- cbind(c(0.1486, 0.0778, -0.0240, -0.0154),
         c(0.0778, 0.1170, 0.0066, 0.0029),
         c(-0.0240, 0.0066, 0.0444, 0.0193),
         c(-0.0154, 0.0029, 0.0193, 0.0148))
 out <- t(d) %*% x + 0.5 * (t(x) %*% D %*% x)
 out
}

# Inequality Constraint: 0 =< x 0 =< 1
lx <- rep(0,4)
ux <- rep(1,4)

sol <- solnp(pars = x0,
         fun = fn,
         eqfun = sum,
         eqB = 1,
         ineqLB = lx,
         ineqUB = ux)
sol$pars
</code>```

Body:
I'm new to stackoverflow and searched a lot, but couldn't find an answer to my question. I'm trying to minimise the problem bellow with the optimisation package Rsolnp. Although the solver gives me a solution, every time I run the code I get the following warning message:

Warning messages: 1: In cbind(temp, funv) :
  number of rows of result is not a multiple of vector length (arg 1)

Furthermore, the solution is completely different from the solutions I get with ipop and solve.QP. Their solutions are almost the same (0.2480, 0.0000, 0.0121, 0.7400).
I tried many different formulations of the problem, but could not figure out what I did wrong. I am thankful for all help and information!

library(Rsolnp)
# Starting Values
x0 <- c(0.25,0,0.01,0.75)

fn <- function(x){
  d <- c(0.0308, 0.0269, 0.0145, 0.0130)
  d <- -d
  D <- cbind(c(0.1486, 0.0778, -0.0240, -0.0154),
         c(0.0778, 0.1170, 0.0066, 0.0029),
         c(-0.0240, 0.0066, 0.0444, 0.0193),
         c(-0.0154, 0.0029, 0.0193, 0.0148))
 out <- t(d) %*% x + 0.5 * (t(x) %*% D %*% x)
 out
}

# Inequality Constraint: 0 =< x 0 =< 1
lx <- rep(0,4)
ux <- rep(1,4)

sol <- solnp(pars = x0,
         fun = fn,
         eqfun = sum,
         eqB = 1,
         ineqLB = lx,
         ineqUB = ux)
sol$pars

Body:
Make the result of your objective function, fn, explicitly numeric:

fn <- function(x){
  d <- c(0.0308, 0.0269, 0.0145, 0.0130)
  d <- -d
  D <- cbind(c(0.1486, 0.0778, -0.0240, -0.0154),
             c(0.0778, 0.1170, 0.0066, 0.0029),
             c(-0.0240, 0.0066, 0.0444, 0.0193),
             c(-0.0154, 0.0029, 0.0193, 0.0148))
  out <- t(d) %*% x + 0.5 * (t(x) %*% D %*% x)
  as.numeric(out)
}

and I get

Iter: 1 fn: -0.01153   Pars:  0.24798607502 0.00000002295 0.01205720515
  0.73995669928 Iter: 2 fn: -0.01153     Pars:  0.247984418270 0.000000003318 0.012080555874 0.739935021900 solnp--> Completed in 2 iterations

sol$pars
  [1] 2.479844e-01 3.317577e-09 1.208056e-02 7.399350e-01


问:
Memory Management in Glib
How is storage/memory reclaimed in Glib? I've called g_object_unref() and the ref-counts are zero but I'm not sure any storage is ever reclaimed.

Do I need to call a routine? If so, which routine. If not, what?

答:
Much of the memory allocation in GLib is done using the slice allocator, which has better performance when allocating lots of identical-sized blocks of memory, as happens a lot in GLib-using code.

You won't see memory usage jump up and down with the slice allocator in the same way that you would when using traditional malloc. The slice allocator often keeps memory in use for a while in order to reallocate it to other blocks.

If you want to force the slice allocator to behave like malloc, use the environment variable G_SLICE=always-malloc. That's not recommended for  production, but it is the recommended way to use valgrind on GLib programs.

Title: Memory Management in Glib


问:
Python global vs local variables?
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

```<code>import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)
</code>```

答:
When you call i in your function at line 10, in d[i], the Python interpreter you're using first checks for that variable in the local scope. If it doesn't find it, it then checks in the next scope, which in your case happens to be the global one. At this point, you are calling the global variable.

However, as soon as you do i += 1, i becomes a local variable since it's now defined in the local scope.

I'm not 100% on what you expect to happen, though. Are you wondering why the second run of the function returns different results?
If so, I believe your problem lies with your size_0 variable.

You define size_0 globally, but at the very start of your function, re-define it locally and that's the definition your function ends up using while the global size_0 ends up not being used at all. If you were to remove:

```<code>size_0 = sys.getsizeof(d)
</code>```

from your function, each run would produce the same result.

What really helps to figure out these issues is adding various code that helps track the execution of your code. In this example, you could add a bunch of print() statements at critical points, such as print(d, size_0)  # inside and outside the function.

It's difficult to give anymore advice as it's not clear to me what the code is supposed to accomplish.

Title: Python global vs local variables?

Body:
I'm having trouble understanding why my code works the way it does. Right now, I'm initializing a global variable i set to 0, so it makes sense that if I print it anywhere outside my function, I should get 0.

When I print i inside the function, I get 6 and 12 after calling the function twice. I think this is because the global i is 0, but some local i variable isn't. However, when I'm calling reach_load with i as a parameter, aren't I passing in the global value of i (0)?

import sys

d = {}
size_0 = sys.getsizeof(d)
i = 0

def reach_load(d, size_0, i):
    size_0 = sys.getsizeof(d)
    while size_0 == sys.getsizeof(d):
        d[i] = i
        i += 1
    print(i)

reach_load(d, size_0, i)
reach_load(d, size_0, i)

Body:
When you call i in your function at line 10, in d[i], the Python interpreter you're using first checks for that variable in the local scope. If it doesn't find it, it then checks in the next scope, which in your case happens to be the global one. At this point, you are calling the global variable.

However, as soon as you do i += 1, i becomes a local variable since it's now defined in the local scope.

I'm not 100% on what you expect to happen, though. Are you wondering why the second run of the function returns different results?
If so, I believe your problem lies with your size_0 variable.

You define size_0 globally, but at the very start of your function, re-define it locally and that's the definition your function ends up using while the global size_0 ends up not being used at all. If you were to remove:

size_0 = sys.getsizeof(d)

from your function, each run would produce the same result.

What really helps to figure out these issues is adding various code that helps track the execution of your code. In this example, you could add a bunch of print() statements at critical points, such as print(d, size_0)  # inside and outside the function.

It's difficult to give anymore advice as it's not clear to me what the code is supposed to accomplish.


问:
When I upload my CodeIgniter 3.1.2 blog to Godaddy I get a "No input file specified." error
I am wondering if anyone knows why I get the following error when uploading my CodeIgniter 3.1.2 blog to my Godaddy hosting server:

No input file specified.

The blog works locally at localhost/blog but does not work at mysite.com/blog

My config looks like the below:

```<code>    $config['base_url'] = 'http://mysite/blog';
$config['index_page'] = 'index.php';
$config['uri_protocol'] = 'PATH_INFO';
</code>```

and my htaccess file that resides in my 'application' directory looks like the below:

```<code>    <IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /mysite/

RewriteEngine On
RewriteBase /blog/

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#‘system’ can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn’t true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#This last condition enables access to the images and css folders, and the robots.txt file
#Submitted by Michael Radlmaier (mradlmaier)
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>

<IfModule !mod_rewrite.c>

ErrorDocument 404 /index.php
</IfModule>
</code>```

答:
Try using this htaccess on your root application directory:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,NC,L]
</code>```

Error must be explained with more details, i don't now if that error is thrown by apache, codeigniter or PHP.

Body:
I am wondering if anyone knows why I get the following error when uploading my CodeIgniter 3.1.2 blog to my Godaddy hosting server:

No input file specified.

The blog works locally at localhost/blog but does not work at mysite.com/blog

My config looks like the below:

    $config['base_url'] = 'http://mysite/blog';
$config['index_page'] = 'index.php';
$config['uri_protocol'] = 'PATH_INFO';

and my htaccess file that resides in my 'application' directory looks like the below:

    <IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /mysite/

RewriteEngine On
RewriteBase /blog/

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#‘system’ can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn’t true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#This last condition enables access to the images and css folders, and the robots.txt file
#Submitted by Michael Radlmaier (mradlmaier)
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>

<IfModule !mod_rewrite.c>

ErrorDocument 404 /index.php
</IfModule>

Body:
Try using this htaccess on your root application directory:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,NC,L]

Error must be explained with more details, i don't now if that error is thrown by apache, codeigniter or PHP.


问:
Hide subview of different view controller
I have a view that acts as a background (light grey 0.5 alpha) for for another custom alert view.

When the user taps my OK button on the custom alert, i want to hide the custom alert and the background view also.

Both views are subviews of the same superview...

I do this in the buttonTapped: method to hide the views, and it works for the first attempt, but from the second time onwards, the background views never dismiss... the alerts hide correctly every time.

```<code>[UIView animateWithDuration:0.5f animations:^{
    self.view.alpha=0.0f; //hide alert
    [self.view.superview viewWithTag:1].alpha=0.0f; //hide background
}];
</code>```

They are added as subviews, as follows:

```<code>ResultDialogController *dialogController = [[[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil] retain];
ResultBackgroundViewController *bgViewController = [[[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil] retain];

dialogController.view.alpha=0;
bgViewController.view.alpha=0;
bgViewController.view.tag=1;

[UIView animateWithDuration:0.5f animations:^{
    bgViewController.view.alpha=0.5f;
    dialogController.view.alpha=1.0f;
    }];

[self.view addSubview:bgViewController.view];
[self.view addSubview:dialogController.view];
[dialogController release];
[bgViewController release];
</code>```

How can i always dismiss the background view?

Thanks

答:
You don't seem to remove the views, you are just making the invisible by setting the alpha to zero. So every time you call your second code sample you will add a new version of the background view and the dialog view to self.view. At the second call you will have two background views, both with tag = 1 and you are getting your first background view from the call to [self.view.superview viewWithTag:1] which is why your newly added background view does not get invisible.

But that is not all, you also have a memory leak for ResultDialogController and ResultBackgroundViewController. The call to retain is not necessary when you are calling initWithNibName:bundle:. Perhaps you are doing this because you some crash when you released the controllers?

What you should do is to create ivars and properties for your controllers.

```<code>@property (nonatomic, retain) ResultDialogController *resultController;
@property (nonatomic, retain) ResultBackgroundController *backgroundController;
</code>```

Then when showing the controllers you can do something like:

```<code>ResultDialogController *dialogController = [[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil];
self.dialogController = dialogController;

ResultBackgroundViewController *bgViewController = [[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil];
self.backgroundController = bgViewController;

// do the same as before
</code>```

Then in buttonTapped: you do:

```<code>[UIView animateWithDuration:0.5f
     animations: ^{
      self.dialogController.view.alpha = 0;
      self.backgroundController.view.alpha = 0;
     }
     completion: ^(BOOL finished){
      [self.dialogController.view removeFromSuperview];
      [self.backgroundController.view removeFromSuperview];
     }
 ];
</code>```

And to top it off, don't forget to release the controller ivars in dealloc.

ContentLicense: CC BY-SA 2.5

Body:
I have a view that acts as a background (light grey 0.5 alpha) for for another custom alert view.

When the user taps my OK button on the custom alert, i want to hide the custom alert and the background view also.

Both views are subviews of the same superview...

I do this in the buttonTapped: method to hide the views, and it works for the first attempt, but from the second time onwards, the background views never dismiss... the alerts hide correctly every time.

[UIView animateWithDuration:0.5f animations:^{
    self.view.alpha=0.0f; //hide alert
    [self.view.superview viewWithTag:1].alpha=0.0f; //hide background
}];

They are added as subviews, as follows:

ResultDialogController *dialogController = [[[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil] retain];
ResultBackgroundViewController *bgViewController = [[[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil] retain];

dialogController.view.alpha=0;
bgViewController.view.alpha=0;
bgViewController.view.tag=1;

[UIView animateWithDuration:0.5f animations:^{
    bgViewController.view.alpha=0.5f;
    dialogController.view.alpha=1.0f;
    }];

[self.view addSubview:bgViewController.view];
[self.view addSubview:dialogController.view];
[dialogController release];
[bgViewController release];

How can i always dismiss the background view?

Thanks

Body:
You don't seem to remove the views, you are just making the invisible by setting the alpha to zero. So every time you call your second code sample you will add a new version of the background view and the dialog view to self.view. At the second call you will have two background views, both with tag = 1 and you are getting your first background view from the call to [self.view.superview viewWithTag:1] which is why your newly added background view does not get invisible.

But that is not all, you also have a memory leak for ResultDialogController and ResultBackgroundViewController. The call to retain is not necessary when you are calling initWithNibName:bundle:. Perhaps you are doing this because you some crash when you released the controllers?

What you should do is to create ivars and properties for your controllers.

@property (nonatomic, retain) ResultDialogController *resultController;
@property (nonatomic, retain) ResultBackgroundController *backgroundController;

Then when showing the controllers you can do something like:

ResultDialogController *dialogController = [[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil];
self.dialogController = dialogController;

ResultBackgroundViewController *bgViewController = [[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil];
self.backgroundController = bgViewController;

// do the same as before

Then in buttonTapped: you do:

[UIView animateWithDuration:0.5f
     animations: ^{
      self.dialogController.view.alpha = 0;
      self.backgroundController.view.alpha = 0;
     }
     completion: ^(BOOL finished){
      [self.dialogController.view removeFromSuperview];
      [self.backgroundController.view removeFromSuperview];
     }
 ];

And to top it off, don't forget to release the controller ivars in dealloc.


问:
Javascript object literal notation executing all values
I want based on the case execute a function, out of a choice of 5 functions. and then take the return value of that function, use that to execute one extra function ( same for each case )

All my functions are synchronous I believe.

```<code>var x = require('./file2.js')

export default (metadata) => {
    return (req, next) => {
      var fn = new x (req, next, metadata)
      var metric = (req.body.metric)
      var choices = {
                "1": fn.one(),
                "2": fn.one(),
                "3": fn.one(),
                "4": fn.one(),
                "5": fn.two(),
                "6": fn.three(),
                "7": fn.four(),
                "8": fn.five()
      };
var jql = choices[metric]// When I put console.log's in all the function (one through five) they all print out.
</code>```

file2.js:

```<code>var x = function (req, next, metadata) {
this.req = req;
this.next = next;
this.start = metadata.body.start;
}

x.prototype.one = function (){
   var jql = ['test',
    'AND ' + this.start].join("\n")
   return jql
}
module.exports = x;
</code>```

答:
If you trying to do what I think you trying to do then you need something like this:</p>

```<code>/*
 Since you want to call a method on an instance of a class, first bind them to
 the proper scope (might want to rethink the name fn).
 Function#bind creates a new function that executes with the proper scope
*/
const one = fn.one.bind(fn)
const two = fn.two.bind(fn)
const three = fn.three.bind(fn)
const four = fn.four.bind(fn)
const five = fn.five.bind(fn)

// Create your object of choices with these functions
const choices = {
  "1": one,
  "2": one,
  "3": one,
  "4": one,
  "5": two,
  "6": three,
  "7": four,
  "8": five
}

// Then you can use it like this:
choices['1'](/* whatever arguments it needs */)
</code>```

Body:
I want based on the case execute a function, out of a choice of 5 functions. and then take the return value of that function, use that to execute one extra function ( same for each case )

All my functions are synchronous I believe.

var x = require('./file2.js')

export default (metadata) => {
    return (req, next) => {
      var fn = new x (req, next, metadata)
      var metric = (req.body.metric)
      var choices = {
                "1": fn.one(),
                "2": fn.one(),
                "3": fn.one(),
                "4": fn.one(),
                "5": fn.two(),
                "6": fn.three(),
                "7": fn.four(),
                "8": fn.five()
      };
var jql = choices[metric]// When I put console.log's in all the function (one through five) they all print out.

file2.js:

var x = function (req, next, metadata) {
this.req = req;
this.next = next;
this.start = metadata.body.start;
}

x.prototype.one = function (){
   var jql = ['test',
    'AND ' + this.start].join("\n")
   return jql
}
module.exports = x;

Body:
If you trying to do what I think you trying to do then you need something like this:

/*
 Since you want to call a method on an instance of a class, first bind them to
 the proper scope (might want to rethink the name fn).
 Function#bind creates a new function that executes with the proper scope
*/
const one = fn.one.bind(fn)
const two = fn.two.bind(fn)
const three = fn.three.bind(fn)
const four = fn.four.bind(fn)
const five = fn.five.bind(fn)

// Create your object of choices with these functions
const choices = {
  "1": one,
  "2": one,
  "3": one,
  "4": one,
  "5": two,
  "6": three,
  "7": four,
  "8": five
}

// Then you can use it like this:
choices['1'](/* whatever arguments it needs */)


问:
Mockito - @Spy vs @Mock
I understand a spy calls the real methods on an object, while a mock calls methods on the double object. Also spies are to be avoided unless there is a code smell.

However, how do spies work and when should I actually use them?
How are they different from mocks?

答:
I have created a runable example here https://www.surasint.com/mockito-with-spy/

I copy some of it here.

If you have something like this code:

```<code>public void transfer( DepositMoneyService depositMoneyService,
                      WithdrawMoneyService withdrawMoneyService,
                      double amount, String fromAccount, String toAccount) {
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}
</code>```

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some legacy code, dependency is in the code like this:

```<code>    public void transfer(String fromAccount, String toAccount, double amount) {
        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();
        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
</code>```

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

```<code>    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();
        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }
</code>```

Then you can use the spy the inject the dependency like this:

```<code>DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target)
            .proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target)
            .proxyWithdrawMoneyServiceCreator();
</code>```

More detail in the link above.

ContentLicense: CC BY-SA 4.0

Title: Mockito - @Spy vs @Mock

Body:
I have created a runable example here https://www.surasint.com/mockito-with-spy/

I copy some of it here.

If you have something like this code:

public void transfer( DepositMoneyService depositMoneyService,
                      WithdrawMoneyService withdrawMoneyService,
                      double amount, String fromAccount, String toAccount) {
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some legacy code, dependency is in the code like this:

    public void transfer(String fromAccount, String toAccount, double amount) {
        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();
        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();
        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }

Then you can use the spy the inject the dependency like this:

DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target)
            .proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target)
            .proxyWithdrawMoneyServiceCreator();

More detail in the link above.


问:
Button aligned to bottom of RelativeLayout is cut off
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>
</code>```

答:
It is really difficult to understand why UI is distorted there can be many reasons of that but which I highly suspect is limit of text is exceeding in your input boxes which causing UI distortion. Please add screenshot for better understanding. So according to it I tried to reduce text sizes and margins between the views to make sure UI not distort if that was due to few margin.</p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Diagnostic"
    android:textSize="12sp"/>

<EditText
    android:id="@+id/emailTB"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/section_label"
    android:layout_marginTop="22dp"
    android:ems="10"
    android:hint="Hint"
    android:inputType="textEmailAddress"
    android:textSize="12sp"/>

<EditText
    android:id="@+id/messageTB"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/emailTB"
    android:layout_marginTop="25dp"
    android:ems="10"
    android:hint="Hint"
    android:inputType="textMultiLine"
    android:maxLines="10"
    android:textSize="12sp"/>

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="Button" />

</RelativeLayout>
</code>```

Body:
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

Body:
It is really difficult to understand why UI is distorted there can be many reasons of that but which I highly suspect is limit of text is exceeding in your input boxes which causing UI distortion. Please add screenshot for better understanding. So according to it I tried to reduce text sizes and margins between the views to make sure UI not distort if that was due to few margin.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Diagnostic"
    android:textSize="12sp"/>

<EditText
    android:id="@+id/emailTB"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/section_label"
    android:layout_marginTop="22dp"
    android:ems="10"
    android:hint="Hint"
    android:inputType="textEmailAddress"
    android:textSize="12sp"/>

<EditText
    android:id="@+id/messageTB"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/emailTB"
    android:layout_marginTop="25dp"
    android:ems="10"
    android:hint="Hint"
    android:inputType="textMultiLine"
    android:maxLines="10"
    android:textSize="12sp"/>

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="Button" />

</RelativeLayout>


问:
Async IDataErrorInfo - WPF
I have a problem when I want to use IDataErrorInfo (.NET 4.0) asynchronously. This code works perfectly.

```<code>EditViewModel.cs

public class EditViewModel : CustomViewModel, IDataErrorInfo
{
    string IDataErrorInfo.Error
    {
        get { throw new NotImplementedException(); }
    }

    string IDataErrorInfo.this[string propertyName] => _validationHandler.Validate(this, propertyName);

}

ValidationHandler.cs

public string Validate(object currentInstance, string propertyName)
{
    // BLA BLA BLA BLA BLA

    return ReturnErrorString

}
</code>```

What I want now is to be able to do it asynchronously. The code I leave below does not work. It does not return error or anything, only my form does not open and my application freezes.

```<code>private async Task<string> AsyncValidation(object currentInstance, string propertyName)
{
    return await TaskEx.Run(() =>
        {
            // BLA BLA BLA BLA BLA

            return ReturnErrorString
        }
    );
}

public string Validate(object currentInstance, string propertyName)
{
    return AsyncValidation(currentInstance, propertyName).Result;
}
</code>```

What am I doing wrong? Thank you

答:
You can't actually implement the IDataErrorInfo interface asynchronously as it just defines a property and an indexer, none of which are or may be  implemented asynchronously.

Calling an async method in the indexer will not make the validation asynchronous as the indexer itself is not being awaited by the validation framework. There is nothing you can do to change this really. An async method should be async all the way and you should not mix blocking and async code: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx.

You may want to look into the INotifyDataErrorInfo interface that was introduced in the .NET Framework 4.5. This interface does support asynchronous validation. Please refer to the following TechNet article for more information and an example: https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx.

Title: Async IDataErrorInfo - WPF

Body:
I have a problem when I want to use IDataErrorInfo (.NET 4.0) asynchronously. This code works perfectly.

EditViewModel.cs

public class EditViewModel : CustomViewModel, IDataErrorInfo
{
    string IDataErrorInfo.Error
    {
        get { throw new NotImplementedException(); }
    }

    string IDataErrorInfo.this[string propertyName] => _validationHandler.Validate(this, propertyName);

}

ValidationHandler.cs

public string Validate(object currentInstance, string propertyName)
{
    // BLA BLA BLA BLA BLA

    return ReturnErrorString

}

What I want now is to be able to do it asynchronously. The code I leave below does not work. It does not return error or anything, only my form does not open and my application freezes.

private async Task<string> AsyncValidation(object currentInstance, string propertyName)
{
    return await TaskEx.Run(() =>
        {
            // BLA BLA BLA BLA BLA

            return ReturnErrorString
        }
    );
}

public string Validate(object currentInstance, string propertyName)
{
    return AsyncValidation(currentInstance, propertyName).Result;
}

What am I doing wrong? Thank you


问:
How to get 10 per line -leap years
Please help with formatting my output.

I have been asked to "Write a program that displays all the leap years, ten per line, in the twenty-first century (from 2001 to 2100), separated by exactly one space".

Although I get the right results, it's not in the required format.

Thanks in advance

```<code>    public class Leapyear {
    public static void main(String[] args) {
        //declare variabls;
     int year;
     int count=1;
     int yearsperline = 10;
     //loop
     for(year=2001;2001<=2100;year++){
         if((year%4==0 && year%100!=0) || (year%400==0))
             System.out.print(year+",");
           if ( year ==2100)
               break;
        while (count%10==0)
        System.out.println();
     }
     }

   }
</code>```

答:
```<code>    int startFromYear = 2001;
    int stopAtYear = 2100;
    int count = 0;

    for(int i = startFromYear; i <= stopAtYear; i++){
        if((i % 4 == 0 && i % 100 != 0)||(i % 400 == 0)){
            System.out.print(i + " ");
            count++;
            if(count % 10 ==0)
                System.out.println();
       }

  }
</code>```

Title: How to get 10 per line -leap years

Body:
Please help with formatting my output.

I have been asked to "Write a program that displays all the leap years, ten per line, in the twenty-first century (from 2001 to 2100), separated by exactly one space".

Although I get the right results, it's not in the required format.

Thanks in advance

    public class Leapyear {
    public static void main(String[] args) {
        //declare variabls;
     int year;
     int count=1;
     int yearsperline = 10;
     //loop
     for(year=2001;2001<=2100;year++){
         if((year%4==0 && year%100!=0) || (year%400==0))
             System.out.print(year+",");
           if ( year ==2100)
               break;
        while (count%10==0)
        System.out.println();
     }
     }

   }


问:
Sql two line intersection
I'm working on a geo project and have some question about that. I draw line with latitude longitude data like the picture below. 1,2,3 are the position I get from db. I want to draw line on that route (A,B are the start and end of the line) and get the intersection data (intersection position or distance to the A or B) from that. What is the rational way for this process?

答:
You can use coordinate geometry functions. Good sample and documentation here: http://www.mathopenref.com/coordintersection.html
You have 2 line, you need to check both with A-B.</p>

Title: Sql two line intersection


问:
Bash script for iterating through defined set of file names and performing commands
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

```<code>/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;
</code>```

Then the next command is analogous:

```<code>/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;
</code>```

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

答:
Time for the find-based solution.

```<code>find . -maxdepth 1 -regextype posix-extended -type d -regex '.*/[0-9]{2}$' -exec \
    bash -c 'dir=${1##*/}
    cd $1
    cp /home/files/*Session{$dir}.* .
    svn add *Session${dir}.*
    svn commit'  -- {} \;
</code>```

EDIT: now more findy than ever.

Body:
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;

Then the next command is analogous:

/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

Body:
Time for the find-based solution.

find . -maxdepth 1 -regextype posix-extended -type d -regex '.*/[0-9]{2}$' -exec \
    bash -c 'dir=${1##*/}
    cd $1
    cp /home/files/*Session{$dir}.* .
    svn add *Session${dir}.*
    svn commit'  -- {} \;

EDIT: now more findy than ever.


问:
Java: PrintStream to String?
I have a function that takes an object of a certain type, and a PrintStream to which to print, and outputs a representation of that object. How can I capture this function's output in a String? Specifically, I want to use it as in a toString method.

答:
Define and initialize a Scanner variable named inSS that creates an input string stream using the String variable myStrLine.

Ans:
    Scanner inSS = new Scanner(myStrLine);

Title: Java: PrintStream to String?


问:
How can I extract data from a specific HTML link with html.parser in Python?
I have what I need for a very dumbed-down parser below. I'd like to create a method that takes in a URL to an HTML page (example: http://www.dictionary.com/browse/example) as a parameter and uses this parser to show me all of the data it encounters. I don't need somebody to give me the solution. However, advice would be appreciated. Thank you.</p>

```<code>from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')
</code>```

答:
This is how I ended up extracting data from a URL, in this case, http://python.org/.</p>

```<code>from html.parser import HTMLParser
from urllib.request import urlopen

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
html = urlopen('http://python.org/')
thing = html.read()
parser.feed(thing.decode("utf-8"))
</code>```

Body:
I have what I need for a very dumbed-down parser below. I'd like to create a method that takes in a URL to an HTML page (example: http://www.dictionary.com/browse/example) as a parameter and uses this parser to show me all of the data it encounters. I don't need somebody to give me the solution. However, advice would be appreciated. Thank you.

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<title>Test</title>'
            '
Parse me!
')

Body:
This is how I ended up extracting data from a URL, in this case, http://python.org/.

from html.parser import HTMLParser
from urllib.request import urlopen

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
html = urlopen('http://python.org/')
thing = html.read()
parser.feed(thing.decode("utf-8"))


问:
Loading data from fixtures to the database ( associations )
I have two models, Project and Todo.

Project stores an array of Todos.

Migration for Project:

```<code>  def up
    create_table :projects do |t|
      t.string :title, null: false
      t.timestamps null: false
    end
  end
</code>```

Migration for Todo:

```<code>  def up
    create_table :todos do |t|
      t.string :text, null: false
      t.boolean :isCompleted, null:false
      t.integer :project_id, null:false
      t.timestamps null: false
    end
  end
</code>```

project.rb

```<code>class Project < ActiveRecord::Base
  has_many :todos
end
</code>```

todo.rb

```<code>class Todo < ActiveRecord::Base
  belongs_to :project
end
</code>```

projects.yml

```<code>family:
  title: 'Семья'

work:
  title: 'Работа'

therest:
  title: 'Прочее'
</code>```

todos.yml

```<code>family_todos:
  text: 'Купить молоко'
  isCompleted: false
  project_id: family

work_todos:
  text: 'Закончить проект'
  isCompleted: false
  project_id: work

therest_todos:
  text: 'Познать бесконечность'
  isCompleted: true
  project_id: therest
</code>```

How can I connect them properly, so when I call a project I can see all the todos inside it? Plus I'm curious how can I add the date via the yml files like an array?

答:
If you want to pre-fill your database, then better way is to use seeds.rb, which is located in db/.

Simply use ruby here and classes from your rails application, e.g., create a project and a todo for it:

```<code>project = Project.create!(...)
project.todos.create!(...)
</code>```

And then simply run rake db:seed to execute it.

You can read more with examples here: http://www.xyzpub.com/en/ruby-on-rails/3.2/seed_rb.html

Body:
I have two models, Project and Todo.

Project stores an array of Todos.

Migration for Project:

  def up
    create_table :projects do |t|
      t.string :title, null: false
      t.timestamps null: false
    end
  end

Migration for Todo:

  def up
    create_table :todos do |t|
      t.string :text, null: false
      t.boolean :isCompleted, null:false
      t.integer :project_id, null:false
      t.timestamps null: false
    end
  end

project.rb

class Project < ActiveRecord::Base
  has_many :todos
end

todo.rb

class Todo < ActiveRecord::Base
  belongs_to :project
end

projects.yml

family:
  title: 'Семья'

work:
  title: 'Работа'

therest:
  title: 'Прочее'

todos.yml

family_todos:
  text: 'Купить молоко'
  isCompleted: false
  project_id: family

work_todos:
  text: 'Закончить проект'
  isCompleted: false
  project_id: work

therest_todos:
  text: 'Познать бесконечность'
  isCompleted: true
  project_id: therest

How can I connect them properly, so when I call a project I can see all the todos inside it? Plus I'm curious how can I add the date via the yml files like an array?

Body:
If you want to pre-fill your database, then better way is to use seeds.rb, which is located in db/.

Simply use ruby here and classes from your rails application, e.g., create a project and a todo for it:

project = Project.create!(...)
project.todos.create!(...)

And then simply run rake db:seed to execute it.

You can read more with examples here: http://www.xyzpub.com/en/ruby-on-rails/3.2/seed_rb.html


问:
How to integrate Google Location API with android Marshmallow runtime permissions system?
I am trying to get the user's location in my Activity using Google Location API. I have a button, on which if user taps, the location of the user should be retrieved and sent to the app backend.
As per Google's documentation, the

```<code>LocationServices.FusedLocationApi
                        .getLastLocation(apiClient)
</code>```

method has to be called in onConnected method. However, the method throws error if I am not checking for permission granted by the user.

My problem is I am asking for permission in onClick method of my button.

I tried putting

```<code>LocationServices.FusedLocationApi
                        .getLastLocation(apiClient)
</code>```

inside the onClick method but it returns a null object.

Is there a proper way to ask location permission from user on tap of a button and not in onCreate method of the activity and still be able to get the location of the user?

答:
I assume you are calling :

```<code>mGoogleApiClient.connect();
</code>```

in onStart(). Which calls the onConnected() method when the activity starts. You can call it on Button Click after asking run-time permission for Location. Then you will be able to getLastLocation() in onConnected() and you won't face permission error.

```<code>button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                   if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)){
                        mGoogleApiClient.connect();
                    }
                    else{
                        // ask run-time permission
                    }
                }
            }
        });
</code>```

Hope this helps.

Body:
I am trying to get the user's location in my Activity using Google Location API. I have a button, on which if user taps, the location of the user should be retrieved and sent to the app backend.
As per Google's documentation, the

LocationServices.FusedLocationApi
                        .getLastLocation(apiClient)

method has to be called in onConnected method. However, the method throws error if I am not checking for permission granted by the user.

My problem is I am asking for permission in onClick method of my button.

I tried putting

LocationServices.FusedLocationApi
                        .getLastLocation(apiClient)

inside the onClick method but it returns a null object.

Is there a proper way to ask location permission from user on tap of a button and not in onCreate method of the activity and still be able to get the location of the user?

Body:
I assume you are calling :

mGoogleApiClient.connect();

in onStart(). Which calls the onConnected() method when the activity starts. You can call it on Button Click after asking run-time permission for Location. Then you will be able to getLastLocation() in onConnected() and you won't face permission error.

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                   if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)){
                        mGoogleApiClient.connect();
                    }
                    else{
                        // ask run-time permission
                    }
                }
            }
        });

Hope this helps.


问:
Laravel Ratchet socket Auth
I am starting learning Ratchet (reactPHP) I am using laravel. But I came to a line about security.
How can I deny websocket connection based on user is logged in or not

```<code>public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
        if(Auth::check()){
            echo 'user logged in';
        }else{
            echo "New connection! ({$conn->resourceId})\n";
        }

    }
</code>```

I used something like this but it passes the Auth::check and console always shows New Connection.

答:
You cannot use Auth::user() anymore with WebSocket. The WebSocket server is handling multiple connections (so Auth::user() dosent have any sense). BUT you can access the user session.

more details here

https://laravel.io/forum/01-16-2015-loading-laravels-session-using-ratchet

Title: Laravel Ratchet socket Auth

Body:
I am starting learning Ratchet (reactPHP) I am using laravel. But I came to a line about security.
How can I deny websocket connection based on user is logged in or not

public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
        if(Auth::check()){
            echo 'user logged in';
        }else{
            echo "New connection! ({$conn->resourceId})\n";
        }

    }

I used something like this but it passes the Auth::check and console always shows New Connection.


问:
Regex that matches a number with commas for every three digits
How would you write a regex that matches a number with commas for every three digits? It must match the following: '42', '1,234', and '6,368,745'.

but not the following: '12,34,567' (which has only two digits between the commas), '1234' (which lacks commas).

I know this question has been asked and answered before, but those were only for solutions where the string passed to the regex was one of those numbers. I was wondering what the best way to do it if the regex is passed the whole string '42 1,234 6,368,745 12,34,567 1234'.

I managed to do it by splitting the string first and then looping through it like below:

```<code>regexsplit = re.compile(r'^\d{1,3}(,\d{3})*$')
splitstring = string.split()
matches = []

for num in splitstring:
    if regexsplit.search(num) is not None:
        matches.append(regexsplit.search(num).group())

print matches
</code>```

First, I'm wondering if there is a more efficient way of writing that code. Secondly, I'm wondering if there is a way to do it without splitting the string and using the .findall() method. I know you'd no longer be able to use the ^ and $ to anchor the beginning and end, so I've done:

```<code>regexnosplit = re.compile(r'(\d{1,3}(,\d{3})*)')
matches2 = []

for groups in regexnosplit.findall(string):
    print groups[0]
</code>```

However, I'm obviously still getting '12', '34,567', '123', '4' returned, so I'm guessing I need to pass a more robust regex, but I can't seem to find a solution.

答:
I would do it this way, trying to find the unwanted patterns:</p>

```<code>import re

s = '42 1,234 6,368,745 12,34,567 1234'

rgx = re.compile(',[0-9]{1,2},|[0-9]{4,}')
nums = [x for x in s.split() if not rgx.search(x)]

print nums  # ['42', '1,234', '6,368,745']
</code>```

Body:
How would you write a regex that matches a number with commas for every three digits? It must match the following: '42', '1,234', and '6,368,745'.

but not the following: '12,34,567' (which has only two digits between the commas), '1234' (which lacks commas).

I know this question has been asked and answered before, but those were only for solutions where the string passed to the regex was one of those numbers. I was wondering what the best way to do it if the regex is passed the whole string '42 1,234 6,368,745 12,34,567 1234'.

I managed to do it by splitting the string first and then looping through it like below:

regexsplit = re.compile(r'^\d{1,3}(,\d{3})*$')
splitstring = string.split()
matches = []

for num in splitstring:
    if regexsplit.search(num) is not None:
        matches.append(regexsplit.search(num).group())

print matches

First, I'm wondering if there is a more efficient way of writing that code. Secondly, I'm wondering if there is a way to do it without splitting the string and using the .findall() method. I know you'd no longer be able to use the ^ and $ to anchor the beginning and end, so I've done:

regexnosplit = re.compile(r'(\d{1,3}(,\d{3})*)')
matches2 = []

for groups in regexnosplit.findall(string):
    print groups[0]

However, I'm obviously still getting '12', '34,567', '123', '4' returned, so I'm guessing I need to pass a more robust regex, but I can't seem to find a solution.

Body:
I would do it this way, trying to find the unwanted patterns:

import re

s = '42 1,234 6,368,745 12,34,567 1234'

rgx = re.compile(',[0-9]{1,2},|[0-9]{4,}')
nums = [x for x in s.split() if not rgx.search(x)]

print nums  # ['42', '1,234', '6,368,745']


问:
UITableView leaking?
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}
</code>```

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?

答:
Explicitly release tableView in your dealloc method and see what happens.

Or better yet, clean all -> Build and Analyze, tell us what you see

Title: UITableView leaking?

Body:
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?


问:
can't add a class to the tab by clicking a button- js is not working
I can't active the tab by clicking the next button in tab2. I want that if i click on the "next" tab3 content will appear. as well as the tab3 will be active also.
I used another way to change the content and active the tab but then tab is not active then(for tab1).

html code:

```<code><div class="panel with-nav-tabs panel-info">
    <div class="panel-heading">
        <ul class="nav nav-tabs" id="hi">
            <li class="active"><a href="#tab1info" role="tab" data-toggle="tab">tab1</a></li>
            <li><a href="#tab2info" role="tab" data-toggle="tab">tab2</a></li>
            <li><a href="#tab3info" role="tab" data-toggle="tab">tab3</a></li>
        </ul>
    </div>
    <div class="panel-body">

    <div class="tab-content">
        <div class="tab-pane fade" id="tab1info">
            tab1 contents
            <a href="#tab2info " data-toggle="tab">Next</a>
        </div>
        <div class="tab-pane fade" id="tab2info">
            <a onclick="iyo()" id="aaa">Next</a>
        </div>

        <div class="tab-pane fade" id="tab3info">tab3contents</div>
    </div>
</div>
</code>```

and my js code:

```<code> function iyo () {
     $('tab3info').addClass('active');
 };
</code>```

答:
Please check this working code.

 function iyo() {
        $('[href="#tab2info"]').parent().removeClass('active');
        $('#tab2info').removeClass('active in');
        $('[href="#tab3info"]').parent().addClass('active');
        $('#tab3info').addClass('active in');
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="panel with-nav-tabs panel-info">
    <div class="panel-heading">
        <ul class="nav nav-tabs" id="hi">
            <li class="active">tab1</li>
            <li>tab2</li>
            <li>tab3</li>

        </ul>
    </div>
    <div class="panel-body">
        <div class="tab-content">
            <div class="tab-pane fade" id="tab1info">
                tab1 contents
                      Next
            </div>

            <div class="tab-pane fade" id="tab2info">
                Next
            </div>

            <div class="tab-pane fade" id="tab3info">tab3contents</div>
        </div>
    </div>
</div></code>```

Body:
I can't active the tab by clicking the next button in tab2. I want that if i click on the "next" tab3 content will appear. as well as the tab3 will be active also.
I used another way to change the content and active the tab but then tab is not active then(for tab1).

html code:

tab1

tab2

tab3

            tab1 contents
            Next

            Next

tab3contents

and my js code:

 function iyo () {
     $('tab3info').addClass('active');
 };

Body:
Please check this working code.

 function iyo() {
        $('[href="#tab2info"]').parent().removeClass('active');
        $('#tab2info').removeClass('active in');
        $('[href="#tab3info"]').parent().addClass('active');
        $('#tab3info').addClass('active in');
    }

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="panel with-nav-tabs panel-info">
    <div class="panel-heading">
        <ul class="nav nav-tabs" id="hi">
            <li class="active"><a href="#tab1info" role="tab" data-toggle="tab">tab1</a></li>
            <li><a href="#tab2info" role="tab" data-toggle="tab">tab2</a></li>
            <li><a href="#tab3info" role="tab" data-toggle="tab">tab3</a></li>

        </ul>
    </div>
    <div class="panel-body">
        <div class="tab-content">
            <div class="tab-pane fade" id="tab1info">
                tab1 contents
                      <a href="#tab2info " data-toggle="tab">Next</a>
            </div>

            <div class="tab-pane fade" id="tab2info">
                <a onclick="iyo()" id="aaa">Next</a>
            </div>

            <div class="tab-pane fade" id="tab3info">tab3contents</div>
        </div>
    </div>
</div>


问:
C++ - Class not updating member properly
I've been programming an adventure game and have everything working up until the movement throughout a two-dimensional array dungeon. The Maps are their own struct, while the Character is a class. One of the member variables of the Character class is a Map, curMap, which represents the map the player is currently on. However, in testing in Main.cpp, the works but the map doesn't update properly. Here's the code, after which I'll explain what I've already done.

Maps.h

```<code>#include <string>
#include <vector>

using namespace std;

struct Map {
    vector<string> layout;
    vector<int> exits; //indices in allMaps array
    string name;
    int level;
    Map();
    Map(vector<string> l, vector<int> e, string n, int lvl);

};

extern Map noMap;
extern Map highashPlainsA, highashPlainsB, highashPlainsC; //Highash Plains
extern Map alnwick, alnwickForge, alnwickMarket, alnwickInn; //Alnwick
extern vector<Map> allMaps;

extern vector<string> blankLayout;
extern vector<string> plainsLayoutA, plainsLayoutB, plainsLayoutC; //Highash Plains
extern vector<string> alnwickLayout; //Major Towns
extern vector<string> forgeLayout, marketLayout, innLayout; //Town Buildings
</code>```

Maps.cpp

```<code>#include "Maps.h"

Map::Map() :
    layout(blankLayout),
    exits({0, 0, 0, 0}),
    name("_NO_MAP_"),
    level(0){}

Map::Map(vector<string> l, vector<int> e, string n, int lvl) :
    layout(l),
    exits(e),
    name(n),
    level(lvl){}

Map noMap = Map();
Map highashPlainsA = Map(plainsLayoutA, {4, 3, 2}, "Highash Plains A", 1);
vector<Map> allMaps = {noMap, highashPlainsA};

vector<string> blankLayout =
{"##############################",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "##############################"};

vector<string> plainsLayoutA =
{"##########################33##",
 "# G #####   ####### E ####   2",
 "# # # D # #  G      #        2",
 "# # #  ## ####################",
 "# # ##E#   #   G            G#",
 "#E# G#  G                   G#",
 "# #    ##########E############",
 "# #### #DE  G              ED#",
 "# ###D #DE         G       ED#",
 "################111###########"};
</code>```

Character.h (I cut out a lot of unimportant code here)

```<code>#include "Maps.h"
#include <iostream>

class Character {

Map curMap;

public:
    Character();
    ~Character();
    void SetMap(Map map);
    Map GetMap();
};

extern Character player;
</code>```

Character.cpp (Left out said unimportant code here as well)

```<code>#include "Character.h"

Character::Character() : curMap(highashPlainsA){}

Character::~Character(){}

void Character::SetMap(Map map){
    cout << "OLD MAP NAME: " << curMap.name << "\n";
    curMap = map;
    curMap.layout = map.layout;
    curMap.exits = map.exits;
    curMap.name = map.name;
    curMap.level = map.level;
    cout << "NEW MAP NAME: " << curMap.name << "\n";
}

Map Character::GetMap(){
    return curMap;
}

Character player = Character();
</code>```

Main.cpp

```<code>#include "Character.h"

int main(){
    player.SetMap(highashPlainsA);
    cout << "\nSIZE OF CURRENT LAYOUT: " << player.GetMap().layout.size() << "\n";
    cout << "SIZE OF PLAINS A: " << plainsLayoutA.size() << "\n";
    cout << "Name of map: " << player.GetMap().name << "\n";
//  cout << "Layout of map: \n" << player.GetMap().layout[0] << "\n" << player.GetMap().layout[1] << "\n" << player.GetMap().layout[2] << "\n"<< player.GetMap().layout[3] << "\n"; // Crashes because for whatever reason the layout size is 0
    return 0;
}
</code>```

What has been tested:
In Character::SetMap() I even tried changing each individual variable, but shouldn't setting the Map as a whole change all of those values? Additionally, in Map::Map(vector<string> l, vector<int> e, string n, int lvl), I tried it without an initializer list but it still didn't work. I didn't really expect it to, but it was worth a shot I guess.

The issues:

Console Output:

```<code>OLD MAP NAME: Highash Plains A
NEW MAP NAME: Highash Plains A

SIZE OF CURRENT LAYOUT: 0
SIZE OF PLAINS A: 10
Name of map: Highash Plains A
</code>```

The character class does initialize the curMap member, and calls the default constructor to do so. This is intended functionality, because it doesn't matter what map the player is on during setup. However, upon trying to set the map to another precreated Map instance (using SetMap(), everything goes downhill from there. According to the console logging, curMap's name was set to the correct name (OLD MAP NAME) and it maintained this when set to the new map. But, the layout returns a null vector whereas a log of the direct size of the target vector gives the proper value. What is going on, and how can I fix it?

答:
I think you should also pass the map to your updateMap function:

```<code>void Character::UpdateMap(Map map){
curMap = map;//and all other initiations depending on your object
sHandler.ClearScreen(); //In a separate class that does work, is just a call to system("cls")
sHandler.DisplayMap(curMap); //For loop from 0 to (but not including) the size of the layout vector, uses cout to print each row. Works given the correct layout.
</code>```

}

Body:
I've been programming an adventure game and have everything working up until the movement throughout a two-dimensional array dungeon. The Maps are their own struct, while the Character is a class. One of the member variables of the Character class is a Map, curMap, which represents the map the player is currently on. However, in testing in Main.cpp, the works but the map doesn't update properly. Here's the code, after which I'll explain what I've already done.

Maps.h

#include <string>
#include <vector>

using namespace std;

struct Map {
    vector<string> layout;
    vector<int> exits; //indices in allMaps array
    string name;
    int level;
    Map();
    Map(vector<string> l, vector<int> e, string n, int lvl);

};

extern Map noMap;
extern Map highashPlainsA, highashPlainsB, highashPlainsC; //Highash Plains
extern Map alnwick, alnwickForge, alnwickMarket, alnwickInn; //Alnwick
extern vector<Map> allMaps;

extern vector<string> blankLayout;
extern vector<string> plainsLayoutA, plainsLayoutB, plainsLayoutC; //Highash Plains
extern vector<string> alnwickLayout; //Major Towns
extern vector<string> forgeLayout, marketLayout, innLayout; //Town Buildings

Maps.cpp

#include "Maps.h"

Map::Map() :
    layout(blankLayout),
    exits({0, 0, 0, 0}),
    name("_NO_MAP_"),
    level(0){}

Map::Map(vector<string> l, vector<int> e, string n, int lvl) :
    layout(l),
    exits(e),
    name(n),
    level(lvl){}

Map noMap = Map();
Map highashPlainsA = Map(plainsLayoutA, {4, 3, 2}, "Highash Plains A", 1);
vector<Map> allMaps = {noMap, highashPlainsA};

vector<string> blankLayout =
{"##############################",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "##############################"};

vector<string> plainsLayoutA =
{"##########################33##",
 "# G #####   ####### E ####   2",
 "# # # D # #  G      #        2",
 "# # #  ## ####################",
 "# # ##E#   #   G            G#",
 "#E# G#  G                   G#",
 "# #    ##########E############",
 "# #### #DE  G              ED#",
 "# ###D #DE         G       ED#",
 "################111###########"};

Character.h (I cut out a lot of unimportant code here)

#include "Maps.h"
#include <iostream>

class Character {

Map curMap;

public:
    Character();
    ~Character();
    void SetMap(Map map);
    Map GetMap();
};

extern Character player;

Character.cpp (Left out said unimportant code here as well)

#include "Character.h"

Character::Character() : curMap(highashPlainsA){}

Character::~Character(){}

void Character::SetMap(Map map){
    cout << "OLD MAP NAME: " << curMap.name << "\n";
    curMap = map;
    curMap.layout = map.layout;
    curMap.exits = map.exits;
    curMap.name = map.name;
    curMap.level = map.level;
    cout << "NEW MAP NAME: " << curMap.name << "\n";
}

Map Character::GetMap(){
    return curMap;
}

Character player = Character();

Main.cpp

#include "Character.h"

int main(){
    player.SetMap(highashPlainsA);
    cout << "\nSIZE OF CURRENT LAYOUT: " << player.GetMap().layout.size() << "\n";
    cout << "SIZE OF PLAINS A: " << plainsLayoutA.size() << "\n";
    cout << "Name of map: " << player.GetMap().name << "\n";
//  cout << "Layout of map: \n" << player.GetMap().layout[0] << "\n" << player.GetMap().layout[1] << "\n" << player.GetMap().layout[2] << "\n"<< player.GetMap().layout[3] << "\n"; // Crashes because for whatever reason the layout size is 0
    return 0;
}

What has been tested:
In Character::SetMap() I even tried changing each individual variable, but shouldn't setting the Map as a whole change all of those values? Additionally, in Map::Map(vector<string> l, vector<int> e, string n, int lvl), I tried it without an initializer list but it still didn't work. I didn't really expect it to, but it was worth a shot I guess.

The issues:

Console Output:

OLD MAP NAME: Highash Plains A
NEW MAP NAME: Highash Plains A

SIZE OF CURRENT LAYOUT: 0
SIZE OF PLAINS A: 10
Name of map: Highash Plains A

The character class does initialize the curMap member, and calls the default constructor to do so. This is intended functionality, because it doesn't matter what map the player is on during setup. However, upon trying to set the map to another precreated Map instance (using SetMap(), everything goes downhill from there. According to the console logging, curMap's name was set to the correct name (OLD MAP NAME) and it maintained this when set to the new map. But, the layout returns a null vector whereas a log of the direct size of the target vector gives the proper value. What is going on, and how can I fix it?

Body:
I think you should also pass the map to your updateMap function:

void Character::UpdateMap(Map map){
curMap = map;//and all other initiations depending on your object
sHandler.ClearScreen(); //In a separate class that does work, is just a call to system("cls")
sHandler.DisplayMap(curMap); //For loop from 0 to (but not including) the size of the layout vector, uses cout to print each row. Works given the correct layout.

}


问:
MySQL does not seem to store databases anywhere
The MySQL command line works fine and connects well to PHP. However, the databases don't seem to be stored anywhere in the computer. I tried looking in C:\Program Files\MySQL\MySQL Server 5.7\ for the data folder, but there is none. I don't know if this is actually a problem or not but it is worrying me. Any help would be greatly appreciated.

答: Check programdata folder: C:\ProgramData\MySQL</p>


问:
Floating Action Menu in Horizontal Direction
I am new to android development and I am using this library for my FABs and FAB menus. All the expansion of FABs in this library are vertical. But I want a horizontal expanding of FAB menu items. How do I do that ??

library

答:
Try using this Library

it has a horizontal orientation for floating action menu.

in Gradle:

```<code>compile 'it.sephiroth.android.library.floatingmenu:floatingmenu:1.0.1'
</code>```

in code:

```<code> FloatingActionMenu mFloatingMenu = new FloatingActionMenu
            .Builder(this)
            .addItem(item1)
            .withScrollDelegate(new FloatingActionMenu.AbsListViewScrollDelegate(mListView))
            .withThreshold(R.dimen.float_action_threshold)
            .withGap(R.dimen.float_action_item_gap)
            .withHorizontalPadding(R.dimen.float_action_h_padding)
            .withVerticalPadding(R.dimen.float_action_v_padding)
            .withGravity(FloatingActionMenu.Gravity.CENTER_HORIZONTAL | FloatingActionMenu.Gravity.BOTTOM)
            .withDirection(FloatingActionMenu.Direction.Horizontal)
            .animationDuration(300)
            .animationInterpolator(new OvershootInterpolator())
            .visible(visible)
            .build();

    mFloatingMenu.setOnItemClickListener(this);
</code>```

this is the orientation line:

```<code>.withDirection(FloatingActionMenu.Direction.Horizontal)
</code>```

or:

```<code>.withDirection(FloatingActionMenu.Direction.Vertical)
</code>```

This is another library which can be used:

https://github.com/futuresimple/android-floating-action-button

Body:
Try using this Library

it has a horizontal orientation for floating action menu.

in Gradle:

compile 'it.sephiroth.android.library.floatingmenu:floatingmenu:1.0.1'

in code:

 FloatingActionMenu mFloatingMenu = new FloatingActionMenu
            .Builder(this)
            .addItem(item1)
            .withScrollDelegate(new FloatingActionMenu.AbsListViewScrollDelegate(mListView))
            .withThreshold(R.dimen.float_action_threshold)
            .withGap(R.dimen.float_action_item_gap)
            .withHorizontalPadding(R.dimen.float_action_h_padding)
            .withVerticalPadding(R.dimen.float_action_v_padding)
            .withGravity(FloatingActionMenu.Gravity.CENTER_HORIZONTAL | FloatingActionMenu.Gravity.BOTTOM)
            .withDirection(FloatingActionMenu.Direction.Horizontal)
            .animationDuration(300)
            .animationInterpolator(new OvershootInterpolator())
            .visible(visible)
            .build();

    mFloatingMenu.setOnItemClickListener(this);

this is the orientation line:

.withDirection(FloatingActionMenu.Direction.Horizontal)

or:

.withDirection(FloatingActionMenu.Direction.Vertical)

This is another library which can be used:

https://github.com/futuresimple/android-floating-action-button


问:
Why is it "impossible" to implement garbage collection in C because of weak typing?
I was told by a rather smart person that you cannot implement garbage collection in C because of it's weakly typed. The basic idea seems to be that C gives you too much freedom. He mentioned casting pointers without type checking...

I don't really grok the idea. Can someone give me an explanation and possibly a code sample of why this wouldn't work.

NOTE: Obviously C is about speed and why would you want to add garbage collection? I'm just curious really.

答:
He probably referred to the fact that you can cast a pointer to an int and back to the original pointer type. It's pretty much impossible for a GC to clean up correctly when you do that, consider:

```<code>char * p = (char *) malloc(16);
int i = (int) p;
p = 0;
// GC runs and finds that the memory is no longer referenced
p = (char *) i;
// p is now a dangling pointer
</code>```

EDIT: The above will only produce a dangling pointer with a precise GC. As others have pointed out, a conservative collector can still correctly handle this scenario as it assumes that any bit pattern that could be a valid pointer actually is a pointer and will thus not free the memory allocated. However, this is of course no longer possible when i is further modified such that it no longer looks like a valid pointer to the collector, e.g. as follows:

```<code>char * p = (char *) malloc(16);
int i = ~((int) p);
p = 0;
// GC runs and finds that the memory is no longer referenced
p = (char *) ~i;
// p is now a dangling pointer
</code>```

Moreover, (again as others have pointed out) it's only impossible to implement a GC for C if you want to retain the full functionality of the language. If you refrain from using tricks like the above (i.e. you confine yourself to a subset of the possible operations) then GC is indeed feasible.

OwnerDisplayName: Tim Merrifield

LastEditorDisplayName: Norman Ramsey

Body:
He probably referred to the fact that you can cast a pointer to an int and back to the original pointer type. It's pretty much impossible for a GC to clean up correctly when you do that, consider:

char * p = (char *) malloc(16);
int i = (int) p;
p = 0;
// GC runs and finds that the memory is no longer referenced
p = (char *) i;
// p is now a dangling pointer

EDIT: The above will only produce a dangling pointer with a precise GC. As others have pointed out, a conservative collector can still correctly handle this scenario as it assumes that any bit pattern that could be a valid pointer actually is a pointer and will thus not free the memory allocated. However, this is of course no longer possible when i is further modified such that it no longer looks like a valid pointer to the collector, e.g. as follows:

char * p = (char *) malloc(16);
int i = ~((int) p);
p = 0;
// GC runs and finds that the memory is no longer referenced
p = (char *) ~i;
// p is now a dangling pointer

Moreover, (again as others have pointed out) it's only impossible to implement a GC for C if you want to retain the full functionality of the language. If you refrain from using tricks like the above (i.e. you confine yourself to a subset of the possible operations) then GC is indeed feasible.