问:
rectangle document detection using hough transform opencv android
I am trying to detect rectangle document using opencv 4 android sdk . First i tried to detect it by finding contours but it is not working  with multi color documents.You can check this link to get better idea :
detecting multi color document with OpenCV4Android

I researched a lot and found that it can be done using houghline transform.So i followed following way to detect document:

original image -> cvtColor -> GaussianBlur filter -> dilate it to sharpen edges -> applied watershed image segmentation algorithm -> canny edge detection with dynamic otsu's threshold -> then applied hough line transform

what i did for hough line transform is:

```<code>Imgproc.HoughLinesP(watershedMat, lines, 1, Math.PI / 180, 50, 100, 50);

    List<Line> horizontals = new ArrayList<>();
    List<Line> verticals = new ArrayList<>();
    for (int x = 0; x < lines.rows(); x++)
    {
        double[] vec = lines.get(x, 0);
        double x1 = vec[0],
                y1 = vec[1],
                x2 = vec[2],
                y2 = vec[3];
        Point start = new Point(x1, y1);
        Point end = new Point(x2, y2);
        Line line = new Line(start, end);
        if (Math.abs(x1 - x2) > Math.abs(y1-y2)) {
            horizontals.add(line);
        } else if (Math.abs(x2 - x1) < Math.abs(y2 - y1)){
            verticals.add(line);
        }
    }
</code>```

and from above list of horizontal and vertical lines , i am finding intersection points as below:

```<code>protected Point computeIntersection (Line l1, Line l2) {
    double x1 = l1._p1.x, x2= l1._p2.x, y1 = l1._p1.y, y2 = l1._p2.y;
    double x3 = l2._p1.x, x4 = l2._p2.x, y3 = l2._p1.y, y4 = l2._p2.y;
    double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

   // double angle = angleBetween2Lines(l1,l2);
    Log.e("houghline","angle between 2 lines = "+angle);
    Point pt = new Point();
    pt.x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
    pt.y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;

  return pt;
}
</code>```

and from that four intersection points i am drawing lines . So, far i am able to detect document through it . see below image :

but , when other objects are concernced with the document ,it tries to detect them also. i am going top to down rows and left to right cols to find intersections of the largest rectangle . I am getting following issues :

As you can see in above images , when other object comes on the screen it is going to detect it too. How to detect only document ? and ignore other objects ?
Here is my original image :

Any help will be highly appreciated !! thanks in advance

答:
General infos

I'm using OpenCV 3.2.0 on Windows 10, however all of the mentioned functionality should be available in 2.4 and or Android.

I've resized the image for better visualization. This does not affect the current approach to solve the problem,
however if we were to use some sort of edge detection, we absolutely should use the orignial image size.

The current solution provided uses a lot of custom functiality (LAB color detection, contour size analysis, etc.) which cannot
be pulished here. If you need help for specific areas you can of course ask for help in the comments.

General observation of the problem

There are several reasons why your previous approaches did not work.
Before we get to the solution, here are some observations that need to be considered:

You have an object that contains both darker and brighter elements compared to the background.

You have an object that consists of rather distinct parts regarding both brightness and color, as well es general homogeneity.
In fact, the object is split by a section that looks a lot like the background.

You have background objects that are clearly distinguishable from the general background (e.g. the black object in the upper right corner).

The object is often captured from a slightly tilted perspective. This causes a perspective transformation of the otherwise rectangular object.

Solution

Considering the obove mentioned observations, I don't think simple thresholding or edge detection will yield any reliable results, especially when looking at the variations between the different images of the same scene.
As a solution, I'd propose foreground and/or background color detection and classification via LAB or HSV color space.
Sample images of the most prominent colors should be used to classify the respective areas.
E.g. for the foreground the dark and bright red as well as the gold/yellowish color of the book. The background consists of a rather homogeneous grayish color which can be used for its detection.
Potential algorithm:

Detect and classify fore- and background according to LAB color space. Use a sensible color distance threshold (for me something around 8-10% worked in LAB space - AB space might work for 5-7%).
If the color variation due to varying brightness becomes a problem then switch to a brightness independent approach (e.g. just juse the AB components and ignore the L component)

Exclude parts of background from foreground detection (there may be some overlap in classification so this order will prevent confusion).

On the remaining binary image, apply a contour search and discard contours with too small areas.

The remaining contours form the book. Create a convex hull which you can use as the object ROI.

Advantages:

Very accurate

Works across multiple scenarios (changing background, different illumination - if the right color space is used)

Disadvantages:

Difficult to implement for a beginner (knowledge of LAB or HSV, color distances, support for multi-color classification, etc.)

Color detection completely dependent on background and foreground. That means if the book changes and is e.g. blue, the sample images have to be adapted.

This approach won't work, if all of the top, bottom or the sides of the book look like the background. If that is the case, these parts of the book will be classified as background.

Difficulty of a general solution

There are reasons why the current approach, albeit advanced, will not suffice for general application (varying books, varying backgrounds, etc.).

If you want a generic system, that can automatically detect varying books in varying background, you're in for some trouble.
That reaches a level of difficulty that will be hard to solve. It kind of reminds me of the detection of licence plates:
varying illumination, noise, stained objects, strongly varying backgrounds, bad contrast, etc.
And even if you manage this, here is the catch: such a system will only work for specific types of license plates.
The same applies to your books.

Tests

Since you posted a very similar question (detecting multi color document with OpenCV4Android), I took the liberty of
using the image posted there as well as the ones you provided here.
Since one of the images was only available with a red ROI, I used my Photoshop skill level > 9000 to remove the red ROI :).

Sample images for background classification

Sample images for foreground classification

Images

Background classification

Foreground classification

Detected objects

Update

Quick LAB crash course

Since the theory on color spaces is quite vast, you should first read up on some basics and key points.
My quick search found this site which nicely explains some important points: http://www.learnopencv.com/color-spaces-in-opencv-cpp-python/
- We will use the float variant of OpenCV since it is the simplest one to use (unaltered LAB range, no scaling, no shfiting, etc.).
- LAB value range:
L* axis (lightness) ranges from 0 to 100
a* and b* (color attributes) axis range from -128 to +127
Sources and references:
What are the ranges of coordinates in the CIELAB color space?
http://www.colourphil.co.uk/lab_lch_colour_space.shtml

Color distance

https://en.wikipedia.org/wiki/Color_difference

Essentially, we use the Euclidean distance between the two colors.
Of course we can omit components from the two colors we compare, e.g. the luminance component (L).

In order to get an intuitive color distance metric, we can simple normalize the color distances to a range between 0.0 and 1.0.
This way we can interpet color distances as deviation in percentage.

Example

Let's use the images from the tutorial page posted above and use them in an example.
The example application shows the following things:
- BGR to LAB conversion
- (L)AB distance calculation
- (L)AB distance normalization
- Color classification according to BGR/LAB values and color distance thresholding
- How colors of objects can change under varying illumination conditions
- How the distances to other colors my become bigger/close the darker/lighter the image gets (this also becomes clear if you carefully read the posted link).

Additional tip:
The example should show that a single color is often not enough to detect objects of color in strongly varying illumination conditions.
A solution could be to use different color distance thresholds for each color by empirical analysis.
An alternative is to use many classification sample colors for each color you want to find. You'd have to calcualte the color distance
to each of these sample colors and combine the found values by ORing the results.

Code and images

(images taken from http://www.learnopencv.com/color-spaces-in-opencv-cpp-python/
 - a tutorial by Satya Mallick)

```<code>#include <opencv2/opencv.hpp>

// Normalization factors for (L)AB distance calculation
// LAB range:
// L: 0.0 - 100.0
// A: -128.0 - 127.0
// B: -128.0 - 127.0
static const float labNormalizationFactor = (float)(1.f / (std::sqrt(std::pow(100, 2) + std::pow(255, 2) + std::pow(255, 2))));
static const float abNormalizationFactor = (float)(1.f / (std::sqrt(std::pow(255, 2) + std::pow(255, 2))));

float labExample_calculateLabDistance(const cv::Vec3f& c1, const cv::Vec3f& c2)
{
    return (float)cv::norm(c1, c2) * labNormalizationFactor;
}

float labExample_calculateAbDistance(const cv::Vec3f& c1, const cv::Vec3f& c2)
{
    cv::Vec2f c1Temp(c1(1), c1(2));
    cv::Vec2f c2Temp(c2(1), c2(2));
    return (float)cv::norm(c1Temp, c2Temp) * abNormalizationFactor;
}

void labExample_calculateLabDistance(
    cv::Mat& imgLabFloat,
    cv::Mat& distances,
    const cv::Vec3f labColor,
    const bool useOnlyAbDistance
)
{
    // Get size for general usage
    const auto& size = imgLabFloat.size();

    distances = cv::Mat::zeros(size, CV_32F);
    distances = 1.f;

    for (int y = 0; y < size.height; ++y)
    {
        for (int x = 0; x < size.width; ++x)
        {
            // Read LAB value
            const auto& value = imgLabFloat.at<cv::Vec3f>(y,x);

            // Calculate distance
            float distanceValue;
            if (useOnlyAbDistance)
            {
                distanceValue = labExample_calculateAbDistance(value, labColor);
            }
            else
            {
                distanceValue = labExample_calculateLabDistance(value, labColor);
            }

            distances.at<float>(y,x) = distanceValue;
        }
    }
}

// Small hacky function to convert a single
// BGR color value to LAB float.
// Since the conversion function is not directly available
// we just use a Mat object to do the conversion.
cv::Vec3f labExample_bgrUchar2LabFloat(const cv::Scalar bgr)
{
    // Build Mat with single bgr pixel
    cv::Mat matWithSinglePixel = cv::Mat::zeros(1, 1, CV_8UC3);
    matWithSinglePixel.setTo(bgr);

    // Convert to float and scale accordingly
    matWithSinglePixel.convertTo(matWithSinglePixel, CV_32FC3, 1.0 / 255.0);

    // Convert to LAB and return value
    cv::cvtColor(matWithSinglePixel, matWithSinglePixel, CV_BGR2Lab);
    auto retval = matWithSinglePixel.at<cv::Vec3f>(0, 0);

    return retval;
}

void labExample_convertImageBgrUcharToLabFloat(cv::Mat& src, cv::Mat& dst)
{
    src.convertTo(dst, CV_32FC3, 1.0 / 255.0);
    cv::cvtColor(dst, dst, CV_BGR2Lab);
}

void labExample()
{
    // Load image
    std::string path = "./Testdata/Stackoverflow lab example/";
    std::string filename1 = "1.jpg";
    std::string fqn1 = path + filename1;
    cv::Mat img1 = cv::imread(fqn1, cv::IMREAD_COLOR);
    std::string filename2 = "2.jpg";
    std::string fqn2 = path + filename2;
    cv::Mat img2 = cv::imread(fqn2, cv::IMREAD_COLOR);

    // Combine images by scaling the second image so both images have the same number of columns and then combining them.
    float scalingFactorX = (float)img1.cols / img2.cols;
    float scalingFactorY = scalingFactorX;
    cv::resize(img2, img2, cv::Size(), scalingFactorX, scalingFactorY);

    std::vector<cv::Mat> mats;
    mats.push_back(img1);
    mats.push_back(img2);
    cv::Mat img;
    cv::vconcat(mats, img);

    // Lets use some reference colors.
    // Remember: OpenCV uses BGR as default color space so all colors
    // are BGR by default, too.
    cv::Scalar bgrColorRed(52, 42, 172);
    cv::Scalar bgrColorOrange(3, 111, 219);
    cv::Scalar bgrColorYellow(1, 213, 224);
    cv::Scalar bgrColorBlue(187, 95, 0);
    cv::Scalar bgrColorGray(127, 127, 127);

    // Build LAB image
    cv::Mat imgLabFloat;
    labExample_convertImageBgrUcharToLabFloat(img, imgLabFloat);

    // Convert bgr ref color to lab float.
    // INSERT color you want to analyze here:
    auto colorLabFloat = labExample_bgrUchar2LabFloat(bgrColorRed);

    cv::Mat colorDistancesWithL;
    cv::Mat colorDistancesWithoutL;
    labExample_calculateLabDistance(imgLabFloat, colorDistancesWithL, colorLabFloat, false);
    labExample_calculateLabDistance(imgLabFloat, colorDistancesWithoutL, colorLabFloat, true);

    // Color distances. They can differ for every color being analyzed.
    float maxColorDistanceWithL = 0.07f;
    float maxColorDistanceWithoutL = 0.07f;

    cv::Mat detectedValuesWithL = colorDistancesWithL <= maxColorDistanceWithL;
    cv::Mat detectedValuesWithoutL = colorDistancesWithoutL <= maxColorDistanceWithoutL;

    cv::Mat imgWithDetectedValuesWithL = cv::Mat::zeros(img.size(), CV_8UC3);
    cv::Mat imgWithDetectedValuesWithoutL = cv::Mat::zeros(img.size(), CV_8UC3);

    img.copyTo(imgWithDetectedValuesWithL, detectedValuesWithL);
    img.copyTo(imgWithDetectedValuesWithoutL, detectedValuesWithoutL);

    cv::imshow("img", img);
    cv::imshow("colorDistancesWithL", colorDistancesWithL);
    cv::imshow("colorDistancesWithoutL", colorDistancesWithoutL);
    cv::imshow("detectedValuesWithL", detectedValuesWithL);
    cv::imshow("detectedValuesWithoutL", detectedValuesWithoutL);
    cv::imshow("imgWithDetectedValuesWithL", imgWithDetectedValuesWithL);
    cv::imshow("imgWithDetectedValuesWithoutL", imgWithDetectedValuesWithoutL);
    cv::waitKey();
}

int main(int argc, char** argv)
{
    labExample();
}
</code>```

Body:
I am trying to detect rectangle document using opencv 4 android sdk . First i tried to detect it by finding contours but it is not working  with multi color documents.You can check this link to get better idea :
detecting multi color document with OpenCV4Android

I researched a lot and found that it can be done using houghline transform.So i followed following way to detect document:

original image -> cvtColor -> GaussianBlur filter -> dilate it to sharpen edges -> applied watershed image segmentation algorithm -> canny edge detection with dynamic otsu's threshold -> then applied hough line transform

what i did for hough line transform is:

Imgproc.HoughLinesP(watershedMat, lines, 1, Math.PI / 180, 50, 100, 50);

    List<Line> horizontals = new ArrayList<>();
    List<Line> verticals = new ArrayList<>();
    for (int x = 0; x < lines.rows(); x++)
    {
        double[] vec = lines.get(x, 0);
        double x1 = vec[0],
                y1 = vec[1],
                x2 = vec[2],
                y2 = vec[3];
        Point start = new Point(x1, y1);
        Point end = new Point(x2, y2);
        Line line = new Line(start, end);
        if (Math.abs(x1 - x2) > Math.abs(y1-y2)) {
            horizontals.add(line);
        } else if (Math.abs(x2 - x1) < Math.abs(y2 - y1)){
            verticals.add(line);
        }
    }

and from above list of horizontal and vertical lines , i am finding intersection points as below:

protected Point computeIntersection (Line l1, Line l2) {
    double x1 = l1._p1.x, x2= l1._p2.x, y1 = l1._p1.y, y2 = l1._p2.y;
    double x3 = l2._p1.x, x4 = l2._p2.x, y3 = l2._p1.y, y4 = l2._p2.y;
    double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

   // double angle = angleBetween2Lines(l1,l2);
    Log.e("houghline","angle between 2 lines = "+angle);
    Point pt = new Point();
    pt.x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
    pt.y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;

  return pt;
}

and from that four intersection points i am drawing lines . So, far i am able to detect document through it . see below image :

but , when other objects are concernced with the document ,it tries to detect them also. i am going top to down rows and left to right cols to find intersections of the largest rectangle . I am getting following issues :

As you can see in above images , when other object comes on the screen it is going to detect it too. How to detect only document ? and ignore other objects ?
Here is my original image :

Any help will be highly appreciated !! thanks in advance

Body:
General infos

I'm using OpenCV 3.2.0 on Windows 10, however all of the mentioned functionality should be available in 2.4 and or Android.

I've resized the image for better visualization. This does not affect the current approach to solve the problem,
however if we were to use some sort of edge detection, we absolutely should use the orignial image size.

The current solution provided uses a lot of custom functiality (LAB color detection, contour size analysis, etc.) which cannot
be pulished here. If you need help for specific areas you can of course ask for help in the comments.

General observation of the problem

There are several reasons why your previous approaches did not work.
Before we get to the solution, here are some observations that need to be considered:

You have an object that contains both darker and brighter elements compared to the background.

You have an object that consists of rather distinct parts regarding both brightness and color, as well es general homogeneity.
In fact, the object is split by a section that looks a lot like the background.

You have background objects that are clearly distinguishable from the general background (e.g. the black object in the upper right corner).

The object is often captured from a slightly tilted perspective. This causes a perspective transformation of the otherwise rectangular object.

Solution

Considering the obove mentioned observations, I don't think simple thresholding or edge detection will yield any reliable results, especially when looking at the variations between the different images of the same scene.
As a solution, I'd propose foreground and/or background color detection and classification via LAB or HSV color space.
Sample images of the most prominent colors should be used to classify the respective areas.
E.g. for the foreground the dark and bright red as well as the gold/yellowish color of the book. The background consists of a rather homogeneous grayish color which can be used for its detection.
Potential algorithm:

Detect and classify fore- and background according to LAB color space. Use a sensible color distance threshold (for me something around 8-10% worked in LAB space - AB space might work for 5-7%).
If the color variation due to varying brightness becomes a problem then switch to a brightness independent approach (e.g. just juse the AB components and ignore the L component)

Exclude parts of background from foreground detection (there may be some overlap in classification so this order will prevent confusion).

On the remaining binary image, apply a contour search and discard contours with too small areas.

The remaining contours form the book. Create a convex hull which you can use as the object ROI.

Advantages:

Very accurate

Works across multiple scenarios (changing background, different illumination - if the right color space is used)

Disadvantages:

Difficult to implement for a beginner (knowledge of LAB or HSV, color distances, support for multi-color classification, etc.)

Color detection completely dependent on background and foreground. That means if the book changes and is e.g. blue, the sample images have to be adapted.

This approach won't work, if all of the top, bottom or the sides of the book look like the background. If that is the case, these parts of the book will be classified as background.

Difficulty of a general solution

There are reasons why the current approach, albeit advanced, will not suffice for general application (varying books, varying backgrounds, etc.).

If you want a generic system, that can automatically detect varying books in varying background, you're in for some trouble.
That reaches a level of difficulty that will be hard to solve. It kind of reminds me of the detection of licence plates:
varying illumination, noise, stained objects, strongly varying backgrounds, bad contrast, etc.
And even if you manage this, here is the catch: such a system will only work for specific types of license plates.
The same applies to your books.

Tests

Since you posted a very similar question (detecting multi color document with OpenCV4Android), I took the liberty of
using the image posted there as well as the ones you provided here.
Since one of the images was only available with a red ROI, I used my Photoshop skill level > 9000 to remove the red ROI :).

Sample images for background classification

Sample images for foreground classification

Images

Background classification

Foreground classification

Detected objects

Update

Quick LAB crash course

Since the theory on color spaces is quite vast, you should first read up on some basics and key points.
My quick search found this site which nicely explains some important points: http://www.learnopencv.com/color-spaces-in-opencv-cpp-python/
- We will use the float variant of OpenCV since it is the simplest one to use (unaltered LAB range, no scaling, no shfiting, etc.).
- LAB value range:
L* axis (lightness) ranges from 0 to 100
a* and b* (color attributes) axis range from -128 to +127
Sources and references:
What are the ranges of coordinates in the CIELAB color space?
http://www.colourphil.co.uk/lab_lch_colour_space.shtml

Color distance

https://en.wikipedia.org/wiki/Color_difference

Essentially, we use the Euclidean distance between the two colors.
Of course we can omit components from the two colors we compare, e.g. the luminance component (L).

In order to get an intuitive color distance metric, we can simple normalize the color distances to a range between 0.0 and 1.0.
This way we can interpet color distances as deviation in percentage.

Example

Let's use the images from the tutorial page posted above and use them in an example.
The example application shows the following things:
- BGR to LAB conversion
- (L)AB distance calculation
- (L)AB distance normalization
- Color classification according to BGR/LAB values and color distance thresholding
- How colors of objects can change under varying illumination conditions
- How the distances to other colors my become bigger/close the darker/lighter the image gets (this also becomes clear if you carefully read the posted link).

Additional tip:
The example should show that a single color is often not enough to detect objects of color in strongly varying illumination conditions.
A solution could be to use different color distance thresholds for each color by empirical analysis.
An alternative is to use many classification sample colors for each color you want to find. You'd have to calcualte the color distance
to each of these sample colors and combine the found values by ORing the results.

Code and images

(images taken from http://www.learnopencv.com/color-spaces-in-opencv-cpp-python/
 - a tutorial by Satya Mallick)

#include <opencv2/opencv.hpp>

// Normalization factors for (L)AB distance calculation
// LAB range:
// L: 0.0 - 100.0
// A: -128.0 - 127.0
// B: -128.0 - 127.0
static const float labNormalizationFactor = (float)(1.f / (std::sqrt(std::pow(100, 2) + std::pow(255, 2) + std::pow(255, 2))));
static const float abNormalizationFactor = (float)(1.f / (std::sqrt(std::pow(255, 2) + std::pow(255, 2))));

float labExample_calculateLabDistance(const cv::Vec3f& c1, const cv::Vec3f& c2)
{
    return (float)cv::norm(c1, c2) * labNormalizationFactor;
}

float labExample_calculateAbDistance(const cv::Vec3f& c1, const cv::Vec3f& c2)
{
    cv::Vec2f c1Temp(c1(1), c1(2));
    cv::Vec2f c2Temp(c2(1), c2(2));
    return (float)cv::norm(c1Temp, c2Temp) * abNormalizationFactor;
}

void labExample_calculateLabDistance(
    cv::Mat& imgLabFloat,
    cv::Mat& distances,
    const cv::Vec3f labColor,
    const bool useOnlyAbDistance
)
{
    // Get size for general usage
    const auto& size = imgLabFloat.size();

    distances = cv::Mat::zeros(size, CV_32F);
    distances = 1.f;

    for (int y = 0; y < size.height; ++y)
    {
        for (int x = 0; x < size.width; ++x)
        {
            // Read LAB value
            const auto& value = imgLabFloat.at<cv::Vec3f>(y,x);

            // Calculate distance
            float distanceValue;
            if (useOnlyAbDistance)
            {
                distanceValue = labExample_calculateAbDistance(value, labColor);
            }
            else
            {
                distanceValue = labExample_calculateLabDistance(value, labColor);
            }

            distances.at<float>(y,x) = distanceValue;
        }
    }
}

// Small hacky function to convert a single
// BGR color value to LAB float.
// Since the conversion function is not directly available
// we just use a Mat object to do the conversion.
cv::Vec3f labExample_bgrUchar2LabFloat(const cv::Scalar bgr)
{
    // Build Mat with single bgr pixel
    cv::Mat matWithSinglePixel = cv::Mat::zeros(1, 1, CV_8UC3);
    matWithSinglePixel.setTo(bgr);

    // Convert to float and scale accordingly
    matWithSinglePixel.convertTo(matWithSinglePixel, CV_32FC3, 1.0 / 255.0);

    // Convert to LAB and return value
    cv::cvtColor(matWithSinglePixel, matWithSinglePixel, CV_BGR2Lab);
    auto retval = matWithSinglePixel.at<cv::Vec3f>(0, 0);

    return retval;
}

void labExample_convertImageBgrUcharToLabFloat(cv::Mat& src, cv::Mat& dst)
{
    src.convertTo(dst, CV_32FC3, 1.0 / 255.0);
    cv::cvtColor(dst, dst, CV_BGR2Lab);
}

void labExample()
{
    // Load image
    std::string path = "./Testdata/Stackoverflow lab example/";
    std::string filename1 = "1.jpg";
    std::string fqn1 = path + filename1;
    cv::Mat img1 = cv::imread(fqn1, cv::IMREAD_COLOR);
    std::string filename2 = "2.jpg";
    std::string fqn2 = path + filename2;
    cv::Mat img2 = cv::imread(fqn2, cv::IMREAD_COLOR);

    // Combine images by scaling the second image so both images have the same number of columns and then combining them.
    float scalingFactorX = (float)img1.cols / img2.cols;
    float scalingFactorY = scalingFactorX;
    cv::resize(img2, img2, cv::Size(), scalingFactorX, scalingFactorY);

    std::vector<cv::Mat> mats;
    mats.push_back(img1);
    mats.push_back(img2);
    cv::Mat img;
    cv::vconcat(mats, img);

    // Lets use some reference colors.
    // Remember: OpenCV uses BGR as default color space so all colors
    // are BGR by default, too.
    cv::Scalar bgrColorRed(52, 42, 172);
    cv::Scalar bgrColorOrange(3, 111, 219);
    cv::Scalar bgrColorYellow(1, 213, 224);
    cv::Scalar bgrColorBlue(187, 95, 0);
    cv::Scalar bgrColorGray(127, 127, 127);

    // Build LAB image
    cv::Mat imgLabFloat;
    labExample_convertImageBgrUcharToLabFloat(img, imgLabFloat);

    // Convert bgr ref color to lab float.
    // INSERT color you want to analyze here:
    auto colorLabFloat = labExample_bgrUchar2LabFloat(bgrColorRed);

    cv::Mat colorDistancesWithL;
    cv::Mat colorDistancesWithoutL;
    labExample_calculateLabDistance(imgLabFloat, colorDistancesWithL, colorLabFloat, false);
    labExample_calculateLabDistance(imgLabFloat, colorDistancesWithoutL, colorLabFloat, true);

    // Color distances. They can differ for every color being analyzed.
    float maxColorDistanceWithL = 0.07f;
    float maxColorDistanceWithoutL = 0.07f;

    cv::Mat detectedValuesWithL = colorDistancesWithL <= maxColorDistanceWithL;
    cv::Mat detectedValuesWithoutL = colorDistancesWithoutL <= maxColorDistanceWithoutL;

    cv::Mat imgWithDetectedValuesWithL = cv::Mat::zeros(img.size(), CV_8UC3);
    cv::Mat imgWithDetectedValuesWithoutL = cv::Mat::zeros(img.size(), CV_8UC3);

    img.copyTo(imgWithDetectedValuesWithL, detectedValuesWithL);
    img.copyTo(imgWithDetectedValuesWithoutL, detectedValuesWithoutL);

    cv::imshow("img", img);
    cv::imshow("colorDistancesWithL", colorDistancesWithL);
    cv::imshow("colorDistancesWithoutL", colorDistancesWithoutL);
    cv::imshow("detectedValuesWithL", detectedValuesWithL);
    cv::imshow("detectedValuesWithoutL", detectedValuesWithoutL);
    cv::imshow("imgWithDetectedValuesWithL", imgWithDetectedValuesWithL);
    cv::imshow("imgWithDetectedValuesWithoutL", imgWithDetectedValuesWithoutL);
    cv::waitKey();
}

int main(int argc, char** argv)
{
    labExample();
}


来源: stackexchange

问:
Laravel PHP Global object
I'm new to the world of OOP and I'm trying to make a Laravel application.

The app I'm making is to facilitate a game. The game has got a startdate and an enddate. However throughout my application it's nice to know the period of the game (enddate - startdate) and the relative period compared to a year ( period / 365 ). I defined the start date and end date in a configuration file.

Is it wise to create a class where I set the period and the relative period? The class should only be instantiated once ... so a singleton?

Any pointers/best practices are welcome!

答:
You could simply create a static class so it never has to be instantiated.

If you want to create a singleton you can check the Laravel docs:

```<code>$this->app->singleton('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});
</code>```

Once you've added this to the register method of a service provider (e.g. AppServiceProvider) you can access it by type hinting it inside a controller method or by calling $api = resolve('HelpSpot\API'); (see the docs)

ContentLicense: CC BY-SA 3.0

Title: Laravel PHP Global object

Body:
You could simply create a static class so it never has to be instantiated.

If you want to create a singleton you can check the Laravel docs:

$this->app->singleton('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});

Once you've added this to the register method of a service provider (e.g. AppServiceProvider) you can access it by type hinting it inside a controller method or by calling $api = resolve('HelpSpot\API'); (see the docs)


问:
Grep regex not working with square brackets
So I was trying to write a regex in grep to match square brackets, i.e [ad] should match [ and ]. But I was getting different results on using capturing groups and character classes. Also the result is different on putting ' in the beginning and end of regex string.

So these are the different result that I am getting.

Using capturing groups works fine

```<code>echo "[ad]" | grep -E '(\[|\])'
[ad]
</code>```

Using capturing groups without ' gives syntax error

```<code>echo "[ad]" | grep -E (\[|\])
bash: syntax error near unexpected token `('
</code>```

using character class with [ followed by ] gives no output

```<code>echo "[ad]" | grep -E [\[\]]
</code>```

Using character class with ] followed by [ works correctly

```<code>echo "[ad]" | grep -E [\]\[]
[ad]
</code>```

Using character class with ] followed by [ and using ' does not work

```<code>echo "[ad]" | grep -E '[\]\[]'
</code>```

It'd be great if someone could explain the difference between them.

答:
Firstly, always quote Regex pattern to prevent shell interpretation beforehand:

```<code>$ echo "[ad]" | grep -E '(\[|\])'
[ad]
</code>```

Secondly, within [] surrounded by quotes, you don't need to escape the [] inside, just write them as is within the outer []:

```<code>$ echo "[ad]" | grep -E '[][]'
[ad]
</code>```

Body:
So I was trying to write a regex in grep to match square brackets, i.e [ad] should match [ and ]. But I was getting different results on using capturing groups and character classes. Also the result is different on putting ' in the beginning and end of regex string.

So these are the different result that I am getting.

Using capturing groups works fine

echo "[ad]" | grep -E '(\[|\])'
[ad]

Using capturing groups without ' gives syntax error

echo "[ad]" | grep -E (\[|\])
bash: syntax error near unexpected token `('

using character class with [ followed by ] gives no output

echo "[ad]" | grep -E [\[\]]

Using character class with ] followed by [ works correctly

echo "[ad]" | grep -E [\]\[]
[ad]

Using character class with ] followed by [ and using ' does not work

echo "[ad]" | grep -E '[\]\[]'

It'd be great if someone could explain the difference between them.

Body:
Firstly, always quote Regex pattern to prevent shell interpretation beforehand:

$ echo "[ad]" | grep -E '(\[|\])'
[ad]

Secondly, within [] surrounded by quotes, you don't need to escape the [] inside, just write them as is within the outer []:

$ echo "[ad]" | grep -E '[][]'
[ad]


问:
gridview to sql server database
is there any way to insert in bulk (i mean all gridview rows) to sql server database in single submit. its an ASP.Net app and I also want to validate data.</p>

答: Have a look at using SqlBulkCopy Class</p>

ContentLicense: CC BY-SA 2.5

Title: gridview to sql server database

Body: Have a look at using SqlBulkCopy Class


问:
Is there a provision for PF in ns3 for wimax
Can we implement packet scheduling algorithms in NS3 for WIMAX? If so what is the best reference for it? i have a google-group discussion link for LTE implementation but i wanted to know that if it works with WIMAX or not.

PF in LTE using NS3

答: Yes, there are such capabilities. Please refer to the documentation on Scheduling References </p>


问:
How to use group by in md-select in AngularJS?
I want to bind the below data to the dropdown in two group. one is Text File and another one is RDBMS Category.

1) Text File

a) AWS

b) Azure

c) Mainframe

2) RDBMS

a) Oracle

b) Sybase

c) Teradata

d) MySQL

e) SQLServer

f) DB2

```<code><md-input-container>
        <md-select name="databaseType" ng-change="databaseTypeChange()" ng-model="form.databaseType" class="input-div" required ng-disabled="update && view">
          <md-option  ng-value="databaseType" ng-repeat="databaseType in databaseTypes | groupBy:'databaseType.Category'">{{databaseType.Subcategory}}</md-option>
        </md-select>
        <div ng-messages="DataAccessRoleForm.databaseType.$error">
          <div ng-message="required">required</div>
        </div>
      </md-input-container>

$scope.databaseTypes.push({ "ID": template_id, "Category": category, "Subcategory": template_name, "JsonSchema": schema });
</code>```

答:
You have to handle it with filter filter mate. Get the group name for md-optgroup by having ng-repeat on it & reducing the options array object. so your html coded will look like

```<code><md-select ng-model="selection" placeholder="Select an Option">
  <md-optgroup label="{{currentGroup}}" ng-repeat="currentGroup in groupList">
    <md-option ng-value="item" ng-repeat="item in items | filter: {group: currentGroup}">{{item.name}}</md-option>
  </md-optgroup>
</md-select>

$scope.groupList = $scope.items.reduce(function(previous, current) {
if (previous.indexOf(current.group) === -1) {
  previous.push(current.group);
}
  //console.log(previous);
  return previous;
}, []);
</code>```

Here's a working plunker for your requirement

http://plnkr.co/edit/ApuUq7V88ad6uplKjKSC?p=preview

Now this's not as elegant as group by of ng-options but it works fine.

Body:
I want to bind the below data to the dropdown in two group. one is Text File and another one is RDBMS Category.

1) Text File

a) AWS

b) Azure

c) Mainframe

2) RDBMS

a) Oracle

b) Sybase

c) Teradata

d) MySQL

e) SQLServer

f) DB2

<md-input-container>
        <md-select name="databaseType" ng-change="databaseTypeChange()" ng-model="form.databaseType" class="input-div" required ng-disabled="update && view">
          <md-option  ng-value="databaseType" ng-repeat="databaseType in databaseTypes | groupBy:'databaseType.Category'">{{databaseType.Subcategory}}</md-option>
        </md-select>

required

      </md-input-container>

$scope.databaseTypes.push({ "ID": template_id, "Category": category, "Subcategory": template_name, "JsonSchema": schema });

Body:
You have to handle it with filter filter mate. Get the group name for md-optgroup by having ng-repeat on it & reducing the options array object. so your html coded will look like

<md-select ng-model="selection" placeholder="Select an Option">
  <md-optgroup label="{{currentGroup}}" ng-repeat="currentGroup in groupList">
    <md-option ng-value="item" ng-repeat="item in items | filter: {group: currentGroup}">{{item.name}}</md-option>
  </md-optgroup>
</md-select>

$scope.groupList = $scope.items.reduce(function(previous, current) {
if (previous.indexOf(current.group) === -1) {
  previous.push(current.group);
}
  //console.log(previous);
  return previous;
}, []);

Here's a working plunker for your requirement

http://plnkr.co/edit/ApuUq7V88ad6uplKjKSC?p=preview

Now this's not as elegant as group by of ng-options but it works fine.


问:
Javascript Read large files failed
A JSON file is 6 GB. When reading it with the following code,

```<code>var fs = require('fs');
var contents = fs.readFileSync('large_file.txt').toString();
</code>```

It had the following error:

```<code>buffer.js:182
    throw err;
    ^

RangeError: "size" argument must not be larger than 2147483647
    at Function.Buffer.allocUnsafe (buffer.js:209:3)
    at tryCreateBuffer (fs.js:530:21)
    at Object.fs.readFileSync (fs.js:569:14)
    at Object.<anonymous> (/home/readHugeFile.js:4:19)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
</code>```

Could somebody help, please?

答:
The maximum size for a Buffer, which is what readFileSync() uses internally to hold the file data, is about 2GB (source: https://nodejs.org/api/buffer.html#buffer_buffer_kmaxlength).

You probably need a streaming JSON parser, like JSONStream, to process your file:

```<code>const JSONStream = require('JSONStream');
const fs         = require('fs');

fs.createReadStream('large_file.json')
  .pipe(JSONStream.parse('*'))
  .on('data', entry => {
    console.log('entry', entry);
  });
</code>```

Title: Javascript Read large files failed

Body:
A JSON file is 6 GB. When reading it with the following code,

var fs = require('fs');
var contents = fs.readFileSync('large_file.txt').toString();

It had the following error:

buffer.js:182
    throw err;
    ^

RangeError: "size" argument must not be larger than 2147483647
    at Function.Buffer.allocUnsafe (buffer.js:209:3)
    at tryCreateBuffer (fs.js:530:21)
    at Object.fs.readFileSync (fs.js:569:14)
    at Object.<anonymous> (/home/readHugeFile.js:4:19)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)

Could somebody help, please?

Body:
The maximum size for a Buffer, which is what readFileSync() uses internally to hold the file data, is about 2GB (source: https://nodejs.org/api/buffer.html#buffer_buffer_kmaxlength).

You probably need a streaming JSON parser, like JSONStream, to process your file:

const JSONStream = require('JSONStream');
const fs         = require('fs');

fs.createReadStream('large_file.json')
  .pipe(JSONStream.parse('*'))
  .on('data', entry => {
    console.log('entry', entry);
  });


问:
Simplest way to convert a string representing JSON array into Java array List of key value pairs
I have json string which looks like the following:

```<code> "users":[
      {user_id=1,
       user_name=foo,
       profile_image=profile.png},
      {user_id=2,
       ............},
       .............
          ]
</code>```

How can I convert it into a java arraylist of key,value pairs?

答:
```<code>HashMap<String,Object> result =
    new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
</code>```

Body:
I have json string which looks like the following:

 "users":[
      {user_id=1,
       user_name=foo,
       profile_image=profile.png},
      {user_id=2,
       ............},
       .............
          ]

How can I convert it into a java arraylist of key,value pairs?


问:
How to make an error message appear if a name is not available in a file in C?
So I managed to code a solution or finding names in files to validate login. If the ID is there in the file, the program will allow the user to go further. But the issue is, if the user doesn't enter a registered name, the code will just crash, as there is no way to put an error message. Here's the code:

```<code>void loginadmin()
{
    FILE *fp = fopen("C:\\Users\\khali\\Desktop\\C programming project\\admin.txt", "r");
    char loginID [200];
    char password [200];
    char name[200];

    printf("Please enter your login ID below\n");
    scanf("%s", &loginID);

    while (!feof(fp))
    {
        fgets(name, 200, fp );
        if (strncmp(name, loginID, strlen(loginID)) == 0)
        {
            printf("\nWelcome %s", name);
        }

    }
    fclose(fp);
}
</code>```

Now in this code, the part:

```<code>while (!feof(fp))
        {
            fgets(name, 200, fp );
            if (strncmp(name, loginID, strlen(loginID)) == 0)
            {
                printf("\nWelcome %s", name);
            }

        }
        fclose(fp);
    }
</code>```

I wrote it in such a way that it read every line in file, showed validity, and then went on the next line:

```<code>while (!feof(fp))
        {
            fgets(name, 200, fp );
            if (strncmp(name, loginID, strlen(loginID)) == 0)
            {
                printf("\nWelcome %s", name);
            }
            else;
            {
                printf("\nWrong input");
            }
        }
        fclose(fp);
    }
</code>```

Can someone help me put the validation in correct way so that the code only shows validation line once and doesnt run the code again and again and print validity of the code again and again until the correct name has been reached, and also to give users another try instead of running the code all over again.
Cheers :)

答:
The condition you are looking for is when the program has checked all the names in the file (reached the end-of-file) but hasn't found any valid ones. You're going to need a variable to keep track of whether any valid name has been found.
Whenever you get to the section of code handling the two names being equal, you set the variable to 1. Otherwise it remains its default value.
This way after you exit the loop (reach the end of the file) and the variable is not changed, that means none of the names in the file were the same as the one entered by the user.
The other thing you want - giving the user the ability to try again - is also simple. You want to repeat the whole process of asking for a name and checking whether it's correct or not until the user is identified. The way to do that would be using another loop.
So, something like this:

```<code>#include <errno.h>
#include <stdio.h>
#include <string.h>

const char* list_file_name = "admin_users.txt";

int main(int argc, char** argv) {
    FILE* list_file;
    char loginID[200], name[200];
    int identified = 0, error = 0;
    if ((list_file = fopen(list_file_name, "r")) == NULL) {
            error = errno;
            fprintf(stderr, "Couldn't open users.\n");
            return error;
    }
    while (identified == 0) {
            printf("Please enter your login ID: ");
            if (!fgets(loginID, 200, stdin)) {
                    error = errno;
                    fprintf(stderr, "\nCan't read login ID.");
                    goto cleanup;
            }
            while (fgets(name, 200, list_file)) {
                    if (!strcmp(name, loginID)) {
                            identified = 1;
                            printf("Welcome %s", name);
                            break;
                    }
            }
            if (identified == 0)
                    printf("Incorrect username. Please try again.\n");
            rewind(list_file);
    }
    cleanup:
    fclose(list_file);
    return error;
}
</code>```

What you should consider with these problems is when do I want to print the error and once you know that, you should find the place in your code that matches the point you are looking for. If there's no block like that anywhere, you will have to create it by adding more conditions.

Body:
So I managed to code a solution or finding names in files to validate login. If the ID is there in the file, the program will allow the user to go further. But the issue is, if the user doesn't enter a registered name, the code will just crash, as there is no way to put an error message. Here's the code:

void loginadmin()
{
    FILE *fp = fopen("C:\\Users\\khali\\Desktop\\C programming project\\admin.txt", "r");
    char loginID [200];
    char password [200];
    char name[200];

    printf("Please enter your login ID below\n");
    scanf("%s", &loginID);

    while (!feof(fp))
    {
        fgets(name, 200, fp );
        if (strncmp(name, loginID, strlen(loginID)) == 0)
        {
            printf("\nWelcome %s", name);
        }

    }
    fclose(fp);
}

Now in this code, the part:

while (!feof(fp))
        {
            fgets(name, 200, fp );
            if (strncmp(name, loginID, strlen(loginID)) == 0)
            {
                printf("\nWelcome %s", name);
            }

        }
        fclose(fp);
    }

I wrote it in such a way that it read every line in file, showed validity, and then went on the next line:

while (!feof(fp))
        {
            fgets(name, 200, fp );
            if (strncmp(name, loginID, strlen(loginID)) == 0)
            {
                printf("\nWelcome %s", name);
            }
            else;
            {
                printf("\nWrong input");
            }
        }
        fclose(fp);
    }

Can someone help me put the validation in correct way so that the code only shows validation line once and doesnt run the code again and again and print validity of the code again and again until the correct name has been reached, and also to give users another try instead of running the code all over again.
Cheers :)

Body:
The condition you are looking for is when the program has checked all the names in the file (reached the end-of-file) but hasn't found any valid ones. You're going to need a variable to keep track of whether any valid name has been found.
Whenever you get to the section of code handling the two names being equal, you set the variable to 1. Otherwise it remains its default value.
This way after you exit the loop (reach the end of the file) and the variable is not changed, that means none of the names in the file were the same as the one entered by the user.
The other thing you want - giving the user the ability to try again - is also simple. You want to repeat the whole process of asking for a name and checking whether it's correct or not until the user is identified. The way to do that would be using another loop.
So, something like this:

#include <errno.h>
#include <stdio.h>
#include <string.h>

const char* list_file_name = "admin_users.txt";

int main(int argc, char** argv) {
    FILE* list_file;
    char loginID[200], name[200];
    int identified = 0, error = 0;
    if ((list_file = fopen(list_file_name, "r")) == NULL) {
            error = errno;
            fprintf(stderr, "Couldn't open users.\n");
            return error;
    }
    while (identified == 0) {
            printf("Please enter your login ID: ");
            if (!fgets(loginID, 200, stdin)) {
                    error = errno;
                    fprintf(stderr, "\nCan't read login ID.");
                    goto cleanup;
            }
            while (fgets(name, 200, list_file)) {
                    if (!strcmp(name, loginID)) {
                            identified = 1;
                            printf("Welcome %s", name);
                            break;
                    }
            }
            if (identified == 0)
                    printf("Incorrect username. Please try again.\n");
            rewind(list_file);
    }
    cleanup:
    fclose(list_file);
    return error;
}

What you should consider with these problems is when do I want to print the error and once you know that, you should find the place in your code that matches the point you are looking for. If there's no block like that anywhere, you will have to create it by adding more conditions.


问:
How to correct Zend_Uri_Exception (YouTube API with PHP Zend Gdata)
I am using Zend Gdata to interface with the YouTube API from a PHP script. I actually had this working fine, and suddenly I am getting a fatal error about a 'Zend_Uri_Exception' with message 'Invalid URI supplied'. How can I correct the exception?

CODE:

```<code>require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');

$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setOrderBy($this->data['ItemVideo']['sort']);
$query->setRacy('include');
$query->setCategory($this->data['ItemVideo']['q']);

try {
  $videoFeed = $yt->getVideoFeed($query);
} catch(Exception $e) {
  echo var_dump($query) . '<p></p>' . $e;
}
</code>```

OUTPUT:

```<code>object(Zend_Gdata_YouTube_VideoQuery)#79 (4) { ["_params:protected"]
=>  array(2) { ["orderby"]=>  string(9) "relevance" ["racy"]=>  string
(7) "include" } ["_defaultFeedUri:protected"]=>  NULL
["_url:protected"]=>  NULL ["_category:protected"]=>  string(14)
"charlie bit me" }

exception 'Zend_Uri_Exception' with message 'Invalid URI supplied' in /
web/php/balistik_list_app/app/vendors/ZendGdata/library/Zend/Uri/
Http.php:136 Stack trace: #0 /web/php/balistik_list_app/app/vendors/
ZendGdata/library/Zend/Uri.php(123): Zend_Uri_Http->__construct
('http', '//gdata.youtube...') #1 /web/php/balistik_list_app/app/
vendors/ZendGdata/library/Zend/Http/Client.php(257): Zend_Uri::factory
('http://gdata.yo...') #2 /web/php/balistik_list_app/app/vendors/
ZendGdata/library/Zend/Gdata/App.php(476): Zend_Http_Client->setUri
('http://gdata.yo...') #3 /web/php/balistik_list_app/app/vendors/
ZendGdata/library/Zend/Gdata.php(203): Zend_Gdata_App-
>performHttpRequest('GET', 'http://gdata.yo...', Array, NULL, NULL,

NULL) #4 /web/php/balistik_list_app/app/vendors/ZendGdata/library/Zend/
Gdata/App.php(610): Zend_Gdata->performHttpRequest('GET', 'http://
gdata.yo...') #5 /web/php/balistik_list_app/app/vendors/ZendGdata/
library/Zend/Gdata/App.php(541): Zend_Gdata_App->get('http://
gdata.yo...') #6 /web/php/balistik_list_app/app/vendors/ZendGdata/
library/Zend/Gdata/App.php(147): Zend_Gdata_App->importUrl('http://
gdata.yo...', 'Zend_Gdata_YouT...') #7 /web/php/balistik_list_app/app/
vendors/ZendGdata/library/Zend/Gdata.php(148): Zend_Gdata_App->getFeed
('http://gdata.yo...', 'Zend_Gdata_YouT...') #8 /web/php/
balistik_list_app/app/vendors/ZendGdata/library/Zend/Gdata/YouTube.php
(171): Zend_Gdata->getFeed('http://gdata.yo...', 'Zend_Gdata_YouT...')
#9 /web/php/balistik_list_app/app/controllers/
item_videos_controller.php(35): Zend_Gdata_YouTube->getVideoFeed(Object
(Zend_Gdata_YouTube_VideoQuery)) #10 /web/php/balistik_list_app/cake/
libs/object.php(114): ItemVideosController->search() #11 /web/php/
balistik_list_app/cake/dispatcher.php(259): Object->dispatchMethod
('search', Array) #12 /web/php/balistik_list_app/cake/dispatcher.php
(213): Dispatcher->_invoke(Object(ItemVideosController), Array) #13 /
web/php/balistik_list_app/app/webroot/index.php(90): Dispatcher-
>dispatch(NULL) #14 {main}
</code>```

答:
I just tried on
link text

And it seems that racy is not authorized in version 2

```<code><errors xmlns='http://schemas.google.com/g/2005'>
<error>
<domain>GData</domain>
<code>InvalidRequestUriException</code>
<internalReason>Parameter racy not available in version 2</internalReason>
</error>
</errors>
</code>```

The request

```<code>GET /feeds/api/videos?q=Comedy%2Bdog&safeSearch=none&racy=include
GData-Version: 2

X-GData-Client: ytapi-google-jsdemo

Content-Type: application/atom+xml

Cache-Control: no-cache
</code>```

Try to remove the racy control or set a different version

```<code>GET /feeds/api/videos?q=Comedy%2Bdog&search=none&racy=include
</code>```

This one is working

OwnerDisplayName: RyOnLife

Body:
I am using Zend Gdata to interface with the YouTube API from a PHP script. I actually had this working fine, and suddenly I am getting a fatal error about a 'Zend_Uri_Exception' with message 'Invalid URI supplied'. How can I correct the exception?

CODE:

require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');

$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setOrderBy($this->data['ItemVideo']['sort']);
$query->setRacy('include');
$query->setCategory($this->data['ItemVideo']['q']);

try {
  $videoFeed = $yt->getVideoFeed($query);
} catch(Exception $e) {
  echo var_dump($query) . '

' . $e;
}

OUTPUT:

object(Zend_Gdata_YouTube_VideoQuery)#79 (4) { ["_params:protected"]
=>  array(2) { ["orderby"]=>  string(9) "relevance" ["racy"]=>  string
(7) "include" } ["_defaultFeedUri:protected"]=>  NULL
["_url:protected"]=>  NULL ["_category:protected"]=>  string(14)
"charlie bit me" }

exception 'Zend_Uri_Exception' with message 'Invalid URI supplied' in /
web/php/balistik_list_app/app/vendors/ZendGdata/library/Zend/Uri/
Http.php:136 Stack trace: #0 /web/php/balistik_list_app/app/vendors/
ZendGdata/library/Zend/Uri.php(123): Zend_Uri_Http->__construct
('http', '//gdata.youtube...') #1 /web/php/balistik_list_app/app/
vendors/ZendGdata/library/Zend/Http/Client.php(257): Zend_Uri::factory
('http://gdata.yo...') #2 /web/php/balistik_list_app/app/vendors/
ZendGdata/library/Zend/Gdata/App.php(476): Zend_Http_Client->setUri
('http://gdata.yo...') #3 /web/php/balistik_list_app/app/vendors/
ZendGdata/library/Zend/Gdata.php(203): Zend_Gdata_App-
>performHttpRequest('GET', 'http://gdata.yo...', Array, NULL, NULL,

NULL) #4 /web/php/balistik_list_app/app/vendors/ZendGdata/library/Zend/
Gdata/App.php(610): Zend_Gdata->performHttpRequest('GET', 'http://
gdata.yo...') #5 /web/php/balistik_list_app/app/vendors/ZendGdata/
library/Zend/Gdata/App.php(541): Zend_Gdata_App->get('http://
gdata.yo...') #6 /web/php/balistik_list_app/app/vendors/ZendGdata/
library/Zend/Gdata/App.php(147): Zend_Gdata_App->importUrl('http://
gdata.yo...', 'Zend_Gdata_YouT...') #7 /web/php/balistik_list_app/app/
vendors/ZendGdata/library/Zend/Gdata.php(148): Zend_Gdata_App->getFeed
('http://gdata.yo...', 'Zend_Gdata_YouT...') #8 /web/php/
balistik_list_app/app/vendors/ZendGdata/library/Zend/Gdata/YouTube.php
(171): Zend_Gdata->getFeed('http://gdata.yo...', 'Zend_Gdata_YouT...')
#9 /web/php/balistik_list_app/app/controllers/
item_videos_controller.php(35): Zend_Gdata_YouTube->getVideoFeed(Object
(Zend_Gdata_YouTube_VideoQuery)) #10 /web/php/balistik_list_app/cake/
libs/object.php(114): ItemVideosController->search() #11 /web/php/
balistik_list_app/cake/dispatcher.php(259): Object->dispatchMethod
('search', Array) #12 /web/php/balistik_list_app/cake/dispatcher.php
(213): Dispatcher->_invoke(Object(ItemVideosController), Array) #13 /
web/php/balistik_list_app/app/webroot/index.php(90): Dispatcher-
>dispatch(NULL) #14 {main}

Body:
I just tried on
link text

And it seems that racy is not authorized in version 2

<errors xmlns='http://schemas.google.com/g/2005'>
<error>
<domain>GData</domain>
<code>InvalidRequestUriException</code>
<internalReason>Parameter racy not available in version 2</internalReason>
</error>
</errors>

The request

GET /feeds/api/videos?q=Comedy%2Bdog&safeSearch=none&racy=include
GData-Version: 2

X-GData-Client: ytapi-google-jsdemo

Content-Type: application/atom+xml

Cache-Control: no-cache

Try to remove the racy control or set a different version

GET /feeds/api/videos?q=Comedy%2Bdog&search=none&racy=include

This one is working

OwnerDisplayName: stunti


问:
Xcode 'CodeSign error: code signing is required'
I've been working on an iPhone project with iOS 4.0. I just downloaded Xcode 3.2.4 with iOS SDK 4.1 so that I can work with the updated iOS. Upon opening the project in the udpated Xcode, I found that the target read 'Base SDK Missing'. I fixed that by following the instructions here.

Now when I try building targeting any version of iOS, I receive this error (with the corresponding version referenced in the error text):

CodeSign Error: code signing is required for product type 'Application' in SDK 'Device - iOS 4.1'

I have the Team Provisioning Profile created by Xcode installed, that Provisioning Profile has my certificate, and the Code Signing Entity selected is 'iPhone Developer: Aaron Milam'.

Any ideas as to what I could be missing here?

答:
Most common cause, considering that all certificates are installed properly is not specifying the Code Signing Identity in the Active Target settings along with the Project settings. Change these from  to iPhone Developer (Xcode will select the right profile depending on App ID match).

In Xcode , change from Simulator to Device (in the dropdown at the top of the Xcode window), so that your target for application deployment will be the Device.

The default ID which is a wild card ID is like a catch all iD, when associated in Code Signing (if you are using sample files to build, they will most obviously not have com.coolapps.appfile imports, in which case without the 'Team Provisioning profile', your build would fail.  So you would want to set this in your

Xcode->Project ->Edit Project Settings->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

and also (VERY IMPORTANT)

Xcode->Project ->Edit Active Target ->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

Complete steps for a beginner at:
http://codevelle.wordpress.com/2010/12/21/moving-from-ios-simulator-to-the-ios-device-smoothly-without-code-sign-error/


问:
How to use redux with fela and react?
fist thanks for your attention.
I am trying to use fela for dynamically styling my component. Also for manage the states of app, we need to use redux. In fela we need to use a Provider to wrap all component of app. also in redux we have the same thing. for example the root of the app we have :

```<code>import { createRenderer } from 'fela'
import { Provider } from 'react-fela'
import { render } from 'react-dom'
import React from 'react'

const renderer = createRenderer()

render(
   <Provider renderer={renderer}>
     <App />
   </Provider>,
 document.getElementById('app')
)
</code>```

and in root of redux app we have:

```<code>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'

let store = createStore(todoApp)

render(
   <Provider store={store}>
       <App />
   </Provider>,
   document.getElementById('root')
)
</code>```

And my problem is how to use this packages together.

答:
when use as syntax in import can solve this problem. for example:

```<code>import React from 'react'
import { render } from 'react-dom'
import { Provider as ReduxProvider } from 'react-redux'
import { Provider as FelaProvider } from 'react-fela'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'

let store = createStore(todoApp)

render(
   <ReduxProvider store={store}>
       <FelaProvider>
           <App />
       </FelaProvider>
   </ReduxProvider>,
   document.getElementById('root')
)
</code>```

Title: How to use redux with fela and react?

Body:
fist thanks for your attention.
I am trying to use fela for dynamically styling my component. Also for manage the states of app, we need to use redux. In fela we need to use a Provider to wrap all component of app. also in redux we have the same thing. for example the root of the app we have :

import { createRenderer } from 'fela'
import { Provider } from 'react-fela'
import { render } from 'react-dom'
import React from 'react'

const renderer = createRenderer()

render(
   <Provider renderer={renderer}>
     <App />
   </Provider>,
 document.getElementById('app')
)

and in root of redux app we have:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'

let store = createStore(todoApp)

render(
   <Provider store={store}>
       <App />
   </Provider>,
   document.getElementById('root')
)

And my problem is how to use this packages together.

Body:
when use as syntax in import can solve this problem. for example:

import React from 'react'
import { render } from 'react-dom'
import { Provider as ReduxProvider } from 'react-redux'
import { Provider as FelaProvider } from 'react-fela'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'

let store = createStore(todoApp)

render(
   <ReduxProvider store={store}>
       <FelaProvider>
           <App />
       </FelaProvider>
   </ReduxProvider>,
   document.getElementById('root')
)


问:
Execute external program from Java (with cmd, Windows)
I've done many research for executing an external program (e.g. iTunes) by some simple code, however the suggestions did never work. Sometimes nothing happend, sometimes I got this error message:
English: Unable to find "Discord". Be sure the name is written correctly and try again.

My Code is the following:

```<code>try {
    String name = (String) "start " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
    ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd /D %HOMEDRIVE%%HOMEPATH%/Desktop", "/c", name);
    p.start();
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

In my example I get the name of the external program from a JTable, this part is working fine. The ProcessBuilder is changing the directory to the desktop first. Then the external program should be executed by the start <program name> command. With this code I get the mentioned error message.

If you have a solution with cmd, please include changing the directory to the desktop.

答:
According to: cmd.exe,

/D     Ignore registry AutoRun commands
            HKLM | HKCU \Software\Microsoft\Command Processor\AutoRun

Did you mean start.exe /D not cmd.exe /D?

and also they told that

If /C or /K is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commands separated by the command separator '&' or '&&' are accepted if surrounded by quotes.

Did you mean cmd.exe /C "cd %HOMEDRIVE%%HOMEPATH%\Desktop & Discord"?

Body:
I've done many research for executing an external program (e.g. iTunes) by some simple code, however the suggestions did never work. Sometimes nothing happend, sometimes I got this error message:
English: Unable to find "Discord". Be sure the name is written correctly and try again.

My Code is the following:

try {
    String name = (String) "start " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
    ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd /D %HOMEDRIVE%%HOMEPATH%/Desktop", "/c", name);
    p.start();
} catch (Exception e) {
    e.printStackTrace();
}

In my example I get the name of the external program from a JTable, this part is working fine. The ProcessBuilder is changing the directory to the desktop first. Then the external program should be executed by the start <program name> command. With this code I get the mentioned error message.

If you have a solution with cmd, please include changing the directory to the desktop.


答:
I change your code, so that the user is asked for a login ID until a valid ID was found or the user inputs an empty string. If a valid login ID was found the loop does not continue. See the code above and read the comments:</p>

```<code>FILE *fp =
   fopen("C:\\Users\\khali\\Desktop\\C programming project\\admin.txt", "r");
char loginID [200];
char password [200];
char name[200];
int found = 0; // will become 1 if the login ID was found
while (fp && !found) {
    printf("Please enter your login ID below\n");
    scanf("%s", &loginID);
    if ( loginID[0] == 0 ) { // test if the inut is an empty string and break
      break;
    }
    fseek(fp, 0, SEEK_SET); // start every search at the beginning of the file
    while (!found && !feof(fp)) { // test if found or end of file
        fgets(name, 200, fp );
        if (strncmp(name, loginID, strlen(loginID)) == 0) {
            found = 1; // the name was found and we are finished
            printf("\nWelcome %s", name);
        }
    }
}
if (fp) {
    fclose(fp);
}
</code>```

Title: How to make an error message appear if a name is not available in a file in C?

Body:
I change your code, so that the user is asked for a login ID until a valid ID was found or the user inputs an empty string. If a valid login ID was found the loop does not continue. See the code above and read the comments:

FILE *fp =
   fopen("C:\\Users\\khali\\Desktop\\C programming project\\admin.txt", "r");
char loginID [200];
char password [200];
char name[200];
int found = 0; // will become 1 if the login ID was found
while (fp && !found) {
    printf("Please enter your login ID below\n");
    scanf("%s", &loginID);
    if ( loginID[0] == 0 ) { // test if the inut is an empty string and break
      break;
    }
    fseek(fp, 0, SEEK_SET); // start every search at the beginning of the file
    while (!found && !feof(fp)) { // test if found or end of file
        fgets(name, 200, fp );
        if (strncmp(name, loginID, strlen(loginID)) == 0) {
            found = 1; // the name was found and we are finished
            printf("\nWelcome %s", name);
        }
    }
}
if (fp) {
    fclose(fp);
}


问:
how to "sync" VB Project after dynamically adding a function?
I am writing an Excel VBA project that creates new functions during code execution.

The newly added functions need to be able to be executed immediately.

While I do see the new functions added, I receive an "1004" run-time error on the first execution.

The below code adds a new function testMethod into an existing DynamicFunctions module (if the function is not already there) and executes it.

code snippets taken from  Dynamic Code Generate & Execute@VBA and from Programming The VBA Editor

The error message:
"Run-time error '1004':
Cannot run the macro 'testMethod'. The macro may not be available in this workbook or all macros may be disabled"

(notice on second execution, the function already in the module so the code simply executes it and pops the message box)

```<code>Dim code As String
code = "Public Function testMethod()" & vbNewLine & _
            vbTab & "MsgBox """ & Time & """" & vbNewLine & _
            "End Function"

Dim methodExist As Boolean
methodExist = checkProcName("testMethod")

If (methodExist = False) Then
    Dim VBComp As VBIDE.VBComponent
    Set VBComp = ThisWorkbook.VBProject.VBComponents("DynamicFunctions")
    Call VBComp.CodeModule.AddFromString(code)
End If

Application.Run "testMethod"

Function checkProcName(sProcName As String) As Boolean
' ===========================================================================
' Found on http://www.cpearson.com at http://www.cpearson.com/excel/vbe.aspx
' then modified
'
' USAGE:
' to check if a procedure exists, call 'checkProcName' passing
' in the target workbook (which should be open), the Module,
' and the procedure name
'
' ===========================================================================
Dim oVBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule

Dim ProcName As String
Dim ProcKind As VBIDE.vbext_ProcKind

checkProcName = False

Set VBProj = ThisWorkbook.VBProject
Set VBComp = VBProj.VBComponents("DynamicFunctions")
Set CodeMod = VBComp.CodeModule

With CodeMod
    LineNum = .CountOfDeclarationLines + 1
    Do Until LineNum >= .CountOfLines
        ProcName = .ProcOfLine(LineNum, ProcKind)
        If ProcName = sProcName Then
            checkProcName = True
            Exit Do
        End If
        Debug.Print ProcName
        LineNum = .ProcStartLine(ProcName, ProcKind) + .ProcCountLines(ProcName, ProcKind) + 1
    Loop
End With

End Function
</code>```

答:
Unless there is a specific reason you need to have the DynamicFunctions module in your project, you could always create one on the fly, run the code and delete when done.

```<code>Public Sub CreateModuleRunMethodAndDelete()
    Dim code As String
        code = "Public Function testMethod()" & vbNewLine & _
                vbTab & "MsgBox """ & Time & """" & vbNewLine & _
                "End Function"

    'Create and append code
    With ThisWorkbook.VBProject
        With .VBComponents.Add(vbext_ct_StdModule)
            .Name = "Temp"
            .CodeModule.AddFromString code
        End With
    End With

    'Run
    Application.Run "testMethod"

    'Delete module
    With ThisWorkbook.VBProject
        .VBComponents.Remove .VBComponents("Temp")
     End With
End Sub
</code>```

Edit:

Create procedure if not exists and run.

```<code>Public Sub RunMethod()
    Dim code As String
        code = "Public Function testMethod()" & vbNewLine & _
                vbTab & "MsgBox """ & Time & """" & vbNewLine & _
                "End Function"

    If Not checkProcName("testMethod") Then
        ThisWorkbook.VBProject.VBComponents("DynamicFunctions").CodeModule.AddFromString code
    End If

    Application.Run "testMethod"

End Sub
</code>```

Body:
I am writing an Excel VBA project that creates new functions during code execution.

The newly added functions need to be able to be executed immediately.

While I do see the new functions added, I receive an "1004" run-time error on the first execution.

The below code adds a new function testMethod into an existing DynamicFunctions module (if the function is not already there) and executes it.

code snippets taken from  Dynamic Code Generate & Execute@VBA and from Programming The VBA Editor

The error message:
"Run-time error '1004':
Cannot run the macro 'testMethod'. The macro may not be available in this workbook or all macros may be disabled"

(notice on second execution, the function already in the module so the code simply executes it and pops the message box)

Dim code As String
code = "Public Function testMethod()" & vbNewLine & _
            vbTab & "MsgBox """ & Time & """" & vbNewLine & _
            "End Function"

Dim methodExist As Boolean
methodExist = checkProcName("testMethod")

If (methodExist = False) Then
    Dim VBComp As VBIDE.VBComponent
    Set VBComp = ThisWorkbook.VBProject.VBComponents("DynamicFunctions")
    Call VBComp.CodeModule.AddFromString(code)
End If

Application.Run "testMethod"

Function checkProcName(sProcName As String) As Boolean
' ===========================================================================
' Found on http://www.cpearson.com at http://www.cpearson.com/excel/vbe.aspx
' then modified
'
' USAGE:
' to check if a procedure exists, call 'checkProcName' passing
' in the target workbook (which should be open), the Module,
' and the procedure name
'
' ===========================================================================
Dim oVBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule

Dim ProcName As String
Dim ProcKind As VBIDE.vbext_ProcKind

checkProcName = False

Set VBProj = ThisWorkbook.VBProject
Set VBComp = VBProj.VBComponents("DynamicFunctions")
Set CodeMod = VBComp.CodeModule

With CodeMod
    LineNum = .CountOfDeclarationLines + 1
    Do Until LineNum >= .CountOfLines
        ProcName = .ProcOfLine(LineNum, ProcKind)
        If ProcName = sProcName Then
            checkProcName = True
            Exit Do
        End If
        Debug.Print ProcName
        LineNum = .ProcStartLine(ProcName, ProcKind) + .ProcCountLines(ProcName, ProcKind) + 1
    Loop
End With

End Function

Body:
Unless there is a specific reason you need to have the DynamicFunctions module in your project, you could always create one on the fly, run the code and delete when done.

Public Sub CreateModuleRunMethodAndDelete()
    Dim code As String
        code = "Public Function testMethod()" & vbNewLine & _
                vbTab & "MsgBox """ & Time & """" & vbNewLine & _
                "End Function"

    'Create and append code
    With ThisWorkbook.VBProject
        With .VBComponents.Add(vbext_ct_StdModule)
            .Name = "Temp"
            .CodeModule.AddFromString code
        End With
    End With

    'Run
    Application.Run "testMethod"

    'Delete module
    With ThisWorkbook.VBProject
        .VBComponents.Remove .VBComponents("Temp")
     End With
End Sub

Edit:

Create procedure if not exists and run.

Public Sub RunMethod()
    Dim code As String
        code = "Public Function testMethod()" & vbNewLine & _
                vbTab & "MsgBox """ & Time & """" & vbNewLine & _
                "End Function"

    If Not checkProcName("testMethod") Then
        ThisWorkbook.VBProject.VBComponents("DynamicFunctions").CodeModule.AddFromString code
    End If

    Application.Run "testMethod"

End Sub


问:
Swift Alamofire Getting Token from Refresh Token Request Error
I'm pretty new to using Alamofire, and I am banging my head against the wall with this request. I'm using GIDSignIn, and successfully get a token and refresh token for the user, with the scope ["https://www.googleapis.com/auth/youtube.readonly"].

I'm trying to complete this request, as shown as an example on the site. The site says to ignore using client_secret for iOS, which I do.

```<code>POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token
</code>```

Below is how I've implemented it with Alamofire. My client_id is the value from the CLIENT_ID key in the GoogleService-Info.Plist, a string ending in .apps.googleusercontent.com. The refresh_token also seems to have the right format from other examples I've seen online.

```<code>let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
    "client_id" : client_id,
    "refresh_token" : refresh_token,
    "grant_type" : "refresh_token"
]

Alamofire.request(endpoint, method: .post,
                  parameters: parameters,
                  encoding: JSONEncoding.default)

        .responseJSON { (data) in
            print("data: \(data)")
            let json = JSON(data.result)
        }
</code>```

The data response is

```<code>data: SUCCESS: {
    error = "unsupported_grant_type";
    "error_description" = "Invalid grant_type: ";
}
</code>```

Not terribly successful. Do I need to configure my request differently, or get appropriate access / permission to get the token? Thank you so much!

答:
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help

```<code>  let headers = [
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
</code>```

Body:
I'm pretty new to using Alamofire, and I am banging my head against the wall with this request. I'm using GIDSignIn, and successfully get a token and refresh token for the user, with the scope ["https://www.googleapis.com/auth/youtube.readonly"].

I'm trying to complete this request, as shown as an example on the site. The site says to ignore using client_secret for iOS, which I do.

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token

Below is how I've implemented it with Alamofire. My client_id is the value from the CLIENT_ID key in the GoogleService-Info.Plist, a string ending in .apps.googleusercontent.com. The refresh_token also seems to have the right format from other examples I've seen online.

let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
    "client_id" : client_id,
    "refresh_token" : refresh_token,
    "grant_type" : "refresh_token"
]

Alamofire.request(endpoint, method: .post,
                  parameters: parameters,
                  encoding: JSONEncoding.default)

        .responseJSON { (data) in
            print("data: \(data)")
            let json = JSON(data.result)
        }

The data response is

data: SUCCESS: {
    error = "unsupported_grant_type";
    "error_description" = "Invalid grant_type: ";
}

Not terribly successful. Do I need to configure my request differently, or get appropriate access / permission to get the token? Thank you so much!

Body:
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help

  let headers = [
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in


问:
Javascript POST input file to API and get response
I am testing out CamCard API and I wonder how should I post the image taken by my camera to the API and get the response and display it in my page?

That's the sample code they provide and I would like to know how can I achieve to take picture from webcam and POST it to API and get response and display.

Any guidance would be appreciated :)

答:
You can use Jpeg_Camera library to take a picture from the webcam.

And you can post the output using ajax post to the required destination and can use the ajax response as per your need.

Load Jpeg_camera

```<code><script src="/jpeg_camera/jpeg_camera_with_dependencies.min.js" type="text/javascript"></script>
</code>```

var camera = new JpegCamera("#camera");

var snapshot = camera.capture();

snapshot.show(); // Display the snapshot

snapshot.upload({api_url: "<your CamCard url>"})
.done(function(response) {
  response_container.innerHTML = response; // display your response
  this.discard(); // discard snapshot and show video stream again
}).fail(function(status_code, error_message, response) {
  alert("Upload failed with status " + status_code);
});```

Body:
You can use Jpeg_Camera library to take a picture from the webcam.

And you can post the output using ajax post to the required destination and can use the ajax response as per your need.

Load Jpeg_camera

<script src="/jpeg_camera/jpeg_camera_with_dependencies.min.js" type="text/javascript"></script>

var camera = new JpegCamera("#camera");

var snapshot = camera.capture();

snapshot.show(); // Display the snapshot

snapshot.upload({api_url: "<your CamCard url>"})
.done(function(response) {
  response_container.innerHTML = response; // display your response
  this.discard(); // discard snapshot and show video stream again
}).fail(function(status_code, error_message, response) {
  alert("Upload failed with status " + status_code);
});


问:
Communication between 2 projects in Node.js
I am a very beginner in NodeJS so my question can appear very simple but I've downloaded 2 kinds of programs (basically a first program that generate data and something that displays in another way the information) and I want to "connect them".
The first works using client/server JS/Node.js and the display program works using client/server JS/Node.js but I launch them separately. But I want informations extracted from the first program are sent to the other program.
It is surely possible but I don't know how to pass information from a program to another simultaneously when Node is used ?
Can you give me a piece of advice of what concept I should study to do it.
Thanks</p>

答:
Web apps consist of a client (code send to the user's browser) and an API which is how the client communicates with the server.  </p>

<p>The code you downloaded probably uses a REST API. Most node projects are built using an existing web server framework line Express, which will hold the API information in some top level file under the server directory. To get the two servers to communicate, you can make requests (a standard library to use would be axios) from one server to the other server. </p>

Body:
Web apps consist of a client (code send to the user's browser) and an API which is how the client communicates with the server.

The code you downloaded probably uses a REST API. Most node projects are built using an existing web server framework line Express, which will hold the API information in some top level file under the server directory. To get the two servers to communicate, you can make requests (a standard library to use would be axios) from one server to the other server.


问:
rails can't migrate: "don't know how to build task VERSION:0"
First post on here so apologies for any noobity.
I'm working through the Lynda.com Ruby on Rails 5 Essential training on C9 and encountered a problem trying to migrate back down to 'VERSION:0' with this error message:

rails aborted!
Don't know how to build task 'VERSION:0' (see --tasks)
/usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.1.2/lib/rails/commands/rake/rake_command.rb:21:in block in perform'
/usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.1.2/lib/rails/commands/rake/rake_command.rb:18:inperform'
/usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.1.2/lib/rails/command.rb:46:in invoke'
/usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.1.2/lib/rails/commands.rb:16:in'
/home/ubuntu/workspace/bin/rails:9:in require'
/home/ubuntu/workspace/bin/rails:9:in'
/usr/local/rvm/gems/ruby-2.3.1/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in load'
/usr/local/rvm/gems/ruby-2.3.1/gems/spring-2.0.2/lib/spring/client/rails.rb:28:incall'
/usr/local/rvm/gems/ruby-2.3.1/gems/spring-2.0.2/lib/spring/client/command.rb:7:in call'
/usr/local/rvm/gems/ruby-2.3.1/gems/spring-2.0.2/lib/spring/client.rb:30:inrun'
/usr/local/rvm/gems/ruby-2.3.1/gems/spring-2.0.2/bin/spring:49:in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/spring-2.0.2/lib/spring/binstub.rb:31:inload'
/usr/local/rvm/gems/ruby-2.3.1/gems/spring-2.0.2/lib/spring/binstub.rb:31:in <top (required)>'
/home/ubuntu/workspace/bin/spring:15:inrequire'
/home/ubuntu/workspace/bin/spring:15:in <top (required)>'
bin/rails:3:inload'
bin/rails:3:in `'

Any help or advice much appreciated

答:
When doing migration in Rails, you can do:

rake db:migrate, which will migrate your new migration to database and add them to scheme.rb.

You can also do rake db:rollback, which will rollback your last migration.

For rollback you can also do rake db:rollback STEP=n, which will roll you back n migrations where n is the number of recent migrations you want to rollback.

IF you want to rollback version of your migration you would apply the migration version as: rake db:migrate VERSION=0 (as @sjudge said in comments)

You can also do rake db:migrate:redo.

There also some other migrations like:

```<code>rake db:migrate:redo STEP=n
rake db:migrate:up VERSION=20080906120000
rake db:migrate:down VERSION=20080906120000
</code>```

Body:
When doing migration in Rails, you can do:

rake db:migrate, which will migrate your new migration to database and add them to scheme.rb.

You can also do rake db:rollback, which will rollback your last migration.

For rollback you can also do rake db:rollback STEP=n, which will roll you back n migrations where n is the number of recent migrations you want to rollback.

IF you want to rollback version of your migration you would apply the migration version as: rake db:migrate VERSION=0 (as @sjudge said in comments)

You can also do rake db:migrate:redo.

There also some other migrations like:

rake db:migrate:redo STEP=n
rake db:migrate:up VERSION=20080906120000
rake db:migrate:down VERSION=20080906120000


问:
Uploading large files to web service
Good morning everyone:

I've been searching the internet and have not found what to do on this.

I'm currently trying to upload a file bigger than 100 MB to the UCM (Universal Content Management of Oracle 10g) web service. It works fine on files smaller than 100 MB but with bigger files I get the 10055 socket error saying that there is not avaiable buffer space or queue is full.

So I have no way to chage the UCM Web service but I would like to know if I change my code somehow to upload this big files.
The WS offers a method that receives the byte array (byte[]) containing the file contents, no chunks...

Any help, hints, tips or tricks will be appreciated.
Thanks!

答: Depending on what webserver you're running it might just need configuring to allow large requests. For IIS try here.</p>

Title: Uploading large files to web service


问:
Neural network gives different output for same input
What are the potential reasons for a NN to output different values for the same input? Especially when there isn't any random or stochastic processes?</p>

答:
This is a very broad and general question, might be even too broad to even be on here, but there are several things you should know about neural networks:

They are NOT methods for finding one prefect optimal solution. A neural network usually learn examples that it is given and "figures out" a way to predict results reasonably well. Reasonable is relative, and for some models may mean 50% success and for others anything short of 99.9% will be considered failure.

They're outcome is very dependent on the data that was trained on. The order of data matters, and it's usually a good idea to shuffle data during training, but that can lead to wildly different results. Also, the quality of data matters - if the training data is very different in nature to the test data for example.

The best analogy of neural networks in computing is of course - the brain. Even with the same information and same basic underlying biology, we could all evolve different opinions on matters based on endless other variables. Same thing with computer learning to some extent.

Some types of neural networks use dropout layers, that are specifically designed to shut off random parts of the network during training. This should not affect the final prediction process, because for predictions that layer is usually set to allow all the parts of the network to operate, but if you are inputting data and telling the model it is "training" instead of asking it to predict, the results may vary significantly.

The sum of all this is just to say: The training of neural networks should be expected to yield different results from similar starting conditions, and so must be tested multiple times for every condition to determine what parts of it are inevitable and what parts are not.


问:
How to customize Nihilo.css?
One of the available themes in Dijit  is Nihilo.  I am using dijit/layout/.. for displaying  some charts and graphs . I want to change some of the styles being used. Can any one tell me how to customize Nihilo.css and use the customized version?</p>

答:
Don't change nihilo.css, create another CSS file and put the link tag for the second file after the link tag for nihilo.css.

This way, if you upgrade Dojo, you will not have to merge your changes back in.

Title: How to customize Nihilo.css?


问:
Why do parenthesis make such a difference?
I wrote a code that returns the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. Here's my code:

```<code>def duplicate_count(text):
    sum_low = 0
    dic_low = []
    sum_up = 0
    dic_up = []
    sum_num = 0
    dic_num = []
    total = 0
    for i in text:
    if i.isalpha():
        if i.islower() and text.count(i) > 1 and i not in dic_low:
            dic_low.append(i)
            sum_low = sum_low + 1
        elif i.isupper() and text.count(i) > 1 and i not in dic_up:
            dic_up.append(i)
            sum_up = sum_up + 1
    elif i.isdigit() and text.count(i) > 1 and i not in dic_num:
        dic_num.append(i)
        sum_num = sum_num + 1
    total = sum_low + sum_up + sum_num
    print (total)
</code>```

The problem is, I noticed that when I missed parenthesis after "if i.isalpha()" this code worked perfectly with alphabetic characters but appeared to ignore digits, so for instance if I passed "aabbcdeBBAA" it printed "4", but if the argument was "11336" it printed "0". Later I found out that the parenthesis had been missed and corrected it, and the code started to work normally, but I still don't understand what the problem was. There was no any TraceBack, so I guess the problem was in missing parenthesis. Why does it make such a big difference?

PS: sorry if the code is too weird, I'm new to programming and just started to learn coding.
Thank you!

答:
If you write i.isalpha means you are referring to the function, not actually calling the function, you need to add () at the end to call the function

```<code>>>> i = 'some text'
>>> obj = i.isalpha   # just reference not actually call
>>> obj
<function str.isalpha>
>>> obj()    # adding '()' executes the function
False
>>> i.isalpha()
False
</code>```

Body:
I wrote a code that returns the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. Here's my code:

def duplicate_count(text):
    sum_low = 0
    dic_low = []
    sum_up = 0
    dic_up = []
    sum_num = 0
    dic_num = []
    total = 0
    for i in text:
    if i.isalpha():
        if i.islower() and text.count(i) > 1 and i not in dic_low:
            dic_low.append(i)
            sum_low = sum_low + 1
        elif i.isupper() and text.count(i) > 1 and i not in dic_up:
            dic_up.append(i)
            sum_up = sum_up + 1
    elif i.isdigit() and text.count(i) > 1 and i not in dic_num:
        dic_num.append(i)
        sum_num = sum_num + 1
    total = sum_low + sum_up + sum_num
    print (total)

The problem is, I noticed that when I missed parenthesis after "if i.isalpha()" this code worked perfectly with alphabetic characters but appeared to ignore digits, so for instance if I passed "aabbcdeBBAA" it printed "4", but if the argument was "11336" it printed "0". Later I found out that the parenthesis had been missed and corrected it, and the code started to work normally, but I still don't understand what the problem was. There was no any TraceBack, so I guess the problem was in missing parenthesis. Why does it make such a big difference?

PS: sorry if the code is too weird, I'm new to programming and just started to learn coding.
Thank you!

Body:
If you write i.isalpha means you are referring to the function, not actually calling the function, you need to add () at the end to call the function

>>> i = 'some text'
>>> obj = i.isalpha   # just reference not actually call
>>> obj
<function str.isalpha>
>>> obj()    # adding '()' executes the function
False
>>> i.isalpha()
False


问:
How To Prevent Query String but use routes in Html.BeginForm (GET)?
I have a search page. I a search-panel I filled a model like this:

```<code>public class SearchVm
{
    public long? CategoryId { get; set; }
    public long? ProductId { get; set; }
    public DateTime? FromDate { get; set; }
    public DateTime? ToDate { get; set; }
    public string Text { get; set; }
}
</code>```

And as we are interested in SEO,So I want use GET Method, to get search result. so my form is like this:

```<code>@using (@Html.BeginForm("Search", "Products", FormMethod.Get))
{...}
</code>```

And here is action signature:

```<code> public ActionResult Search(SearchVM esm){...}
</code>```

But my URL is so ugly and if I don't fill property "IT IS" in URL as a query string:

http://localhost:8080/Products/Search?CategoryId=2&ProductId=&Text=&FromDate=&ToDate=

Here in this URL,I just filled "CategoryId"!
But how can I have a dynamic route for my searches like this:

```<code>"Products/Search/cat{CategoryId}/prod{ProductId}/{Text}/{FromDate}/{ToDate}"
"Products/Search/prod{ProductId}/{Text}/{FromDate}/{ToDate}"
"Products/Search/prod{ProductId}"
"Products/Search/cat{CategoryId}"
"Products/Search/{FromDate}/{ToDate}"
"Products/Search/{FromDate}"
</code>```

Actually How Can I have all of these combination to be redirected to same action

答:
Actually, you should use the query param for your search fields and not path param. But if you insist, use route attribute(System.Web.Mvc.Route) on your action like this:

```<code>Route("Products/Search/{FromDate}")
</code>```

use all of the routes you would like to fire the related "ActionResult" method

Body:
I have a search page. I a search-panel I filled a model like this:

public class SearchVm
{
    public long? CategoryId { get; set; }
    public long? ProductId { get; set; }
    public DateTime? FromDate { get; set; }
    public DateTime? ToDate { get; set; }
    public string Text { get; set; }
}

And as we are interested in SEO,So I want use GET Method, to get search result. so my form is like this:

@using (@Html.BeginForm("Search", "Products", FormMethod.Get))
{...}

And here is action signature:

 public ActionResult Search(SearchVM esm){...}

But my URL is so ugly and if I don't fill property "IT IS" in URL as a query string:

http://localhost:8080/Products/Search?CategoryId=2&ProductId=&Text=&FromDate=&ToDate=

Here in this URL,I just filled "CategoryId"!
But how can I have a dynamic route for my searches like this:

"Products/Search/cat{CategoryId}/prod{ProductId}/{Text}/{FromDate}/{ToDate}"
"Products/Search/prod{ProductId}/{Text}/{FromDate}/{ToDate}"
"Products/Search/prod{ProductId}"
"Products/Search/cat{CategoryId}"
"Products/Search/{FromDate}/{ToDate}"
"Products/Search/{FromDate}"

Actually How Can I have all of these combination to be redirected to same action

Body:
Actually, you should use the query param for your search fields and not path param. But if you insist, use route attribute(System.Web.Mvc.Route) on your action like this:

Route("Products/Search/{FromDate}")

use all of the routes you would like to fire the related "ActionResult" method


问:
cakephp $uses or request action
i am in a situation where i need to fetch data from 6 models. i can't use associations as they are not related. So what should i use $uses or request action or any other solution

答: If you are going to need those models for only one find call with associtaions needed, I recommend using bindModel, see Creating-and-Destroying-Associations-on-the-Fly.

Title: cakephp $uses or request action


问:
Prepend DISTINCT ON in select statement in an active record scope
I am trying to use distinct on in rails with a scope, I've created a method in my model like this:

```<code>def self.fetch_most_recent_by_user(scope)
  scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) user_id, eld_logs.guid").order("user_id, eld_logs.created_at desc").map(&:guid))
end
</code>```

When I execute this I get and error like:

```<code>TestModel.fetch_most_recent_by_user(TestModel.includes(:user))

ERROR:  syntax error at or near "DISTINCT"
LINE 1: SELECT guid, DISTINCT ON (user_id) user_id...
</code>```

On searching on DISTINCT ON I found out that it should be the first element in a select statement for postgres to make it work.

I want to prepend the DISTINCT ON in the select statement. I have tried clearing the old select statements using except(:select) which I got from here, but it doesn't work because the includes(:user) prepends users attributes first while doing a left join.

I am using Rails 4.0.13 and Postgres 9.4.12. Any help is appreciated.

答:
I found that if the includes was meddling with the distinct my sub query, because which DISTINCT ON failed. I modified my method to this and it works:

```<code>  def self.fetch_most_recent_eld_log_by_user(scope, include_associations = { })
    scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) eld_logs.user_id, eld_logs.guid").order("eld_logs.user_id, eld_logs.created_at desc").map(&:guid))
        .includes(include_associations)
  end
</code>```

Still it'll be good if someone can provide a way to prepend something in the select statement of active record scope.

Body:
I am trying to use distinct on in rails with a scope, I've created a method in my model like this:

def self.fetch_most_recent_by_user(scope)
  scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) user_id, eld_logs.guid").order("user_id, eld_logs.created_at desc").map(&:guid))
end

When I execute this I get and error like:

TestModel.fetch_most_recent_by_user(TestModel.includes(:user))

ERROR:  syntax error at or near "DISTINCT"
LINE 1: SELECT guid, DISTINCT ON (user_id) user_id...

On searching on DISTINCT ON I found out that it should be the first element in a select statement for postgres to make it work.

I want to prepend the DISTINCT ON in the select statement. I have tried clearing the old select statements using except(:select) which I got from here, but it doesn't work because the includes(:user) prepends users attributes first while doing a left join.

I am using Rails 4.0.13 and Postgres 9.4.12. Any help is appreciated.

Body:
I found that if the includes was meddling with the distinct my sub query, because which DISTINCT ON failed. I modified my method to this and it works:

  def self.fetch_most_recent_eld_log_by_user(scope, include_associations = { })
    scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) eld_logs.user_id, eld_logs.guid").order("eld_logs.user_id, eld_logs.created_at desc").map(&:guid))
        .includes(include_associations)
  end

Still it'll be good if someone can provide a way to prepend something in the select statement of active record scope.