问:
How to generate code using jooq code generator with maven
Hi I am trying to generate jooq code files without success. I am using intellij and maven to generate code. When I try an d generate the code nothing happens. I get this message: [INFO] Generating catalogs : Total: 0. I am using Sql server express with Jooq trial. Here is my pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>service</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.groupid</groupId>
            <artifactId>entities</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>6.1.0.jre8</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jooq.trial</groupId>
            <artifactId>jooq</artifactId>
            <version>3.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.jooq.trial</groupId>
            <artifactId>jooq-meta</artifactId>
            <version>3.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.jooq.trial</groupId>
            <artifactId>jooq-codegen</artifactId>
            <version>3.9.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jooq.trial</groupId>
                <artifactId>jooq-codegen-maven</artifactId>
                <version>3.9.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

                <!-- Manage the plugin's dependency. In this example, we'll use a PostgreSQL database -->
                <dependencies>
                    <dependency>
                        <groupId>com.microsoft.sqlserver</groupId>
                        <artifactId>mssql-jdbc</artifactId>
                        <version>6.1.0.jre8</version>
                    </dependency>
                </dependencies>

                <!-- Specify the plugin configuration.
                     The configuration format is the same as for the standalone code generator -->
                <configuration>
                    <!--<logging>WARN</logging>-->
                    <!-- JDBC connection parameters -->
                    <jdbc>
                        <driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver>
                        <url>jdbc:sqlserver://localhost;databaseName=test</url>
                        <user>sa</user>
                        <password>test</password>
                    </jdbc>

                    <!-- Generator parameters -->
                    <generator>
                        <database>
                            <includes>.*</includes>
                            <excludes></excludes>
                            <!--<inputCatalog>public</inputCatalog>-->
                            <inputSchema>dbo</inputSchema>
                        </database>
                        <target>
                            <packageName>mypackage</packageName>
                            <directory>mypath</directory>
                        </target>
                    </generator>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Here is the output I get when trying to generate the files.

```<code>"C:\Program Files\Java\jdk1.8.0_131\bin\java" -Dmaven.multiModuleProjectDirectory=C:\projects\service "-Dmaven.home=C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\plugins\maven\lib\maven3" "-Dclassworlds.conf=C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\plugins\maven\lib\maven3\bin\m2.conf" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\lib\idea_rt.jar=59337:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\plugins\maven\lib\maven3\boot\plexus-classworlds-2.5.2.jar" org.codehaus.classworlds.Launcher -Didea.version=2017.1.4 jooq-codegen:generate
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building service 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- jooq-codegen-maven:3.9.3:generate (default-cli) @ service ---
[INFO] Database                 : Inferring database org.jooq.util.sqlserver.SQLServerDatabase from URL jdbc:sqlserver://localhost:1433;authentication=NotSpecified;authenticationScheme=nativeAuthentication;xopenStates=false;sendTimeAsDatetime=true;trustServerCertificate=false;TransparentNetworkIPResolution=true;serverNameAsACE=false;sendStringParametersAsUnicode=true;selectMethod=direct;responseBuffering=adaptive;packetSize=8000;multiSubnetFailover=false;loginTimeout=15;lockTimeout=-1;lastUpdateCount=true;encrypt=false;disableStatementPooling=true;databaseName=test;columnEncryptionSetting=Disabled;applicationName=Microsoft JDBC Driver for SQL Server;applicationIntent=readwrite;
[INFO] No <inputCatalog/> was provided. Generating ALL available catalogs instead.
[INFO] License parameters
[INFO] ----------------------------------------------------------
[INFO]   Thank you for using jOOQ and jOOQ's code generator
[INFO]
[INFO] Database parameters
[INFO] ----------------------------------------------------------
[INFO]   dialect                : SQLSERVER
[INFO]   URL                    : jdbc:sqlserver://localhost:1433;authentication=NotSpecified;authenticationScheme=nativeAuthentication;xopenStates=false;sendTimeAsDatetime=true;trustServerCertificate=false;TransparentNetworkIPResolution=true;serverNameAsACE=false;sendStringParametersAsUnicode=true;selectMethod=direct;responseBuffering=adaptive;packetSize=8000;multiSubnetFailover=false;loginTimeout=15;lockTimeout=-1;lastUpdateCount=true;encrypt=false;disableStatementPooling=true;databaseName=test;columnEncryptionSetting=Disabled;applicationName=Microsoft JDBC Driver for SQL Server;applicationIntent=readwrite;
[INFO]   target dir             : [target dir]
[INFO]   target package         : com.test
[INFO]   includes               : [.*]
[INFO]   excludes               : []
[INFO]   includeExcludeColumns  : false
[INFO] ----------------------------------------------------------
[INFO]
[INFO] JavaGenerator parameters
[INFO] ----------------------------------------------------------
[INFO]   strategy               : class org.jooq.util.DefaultGeneratorStrategy
[INFO]   deprecated             : true
[INFO]   generated annotation   : true
[INFO]   JPA annotations        : false
[INFO]   validation annotations : false
[INFO]   instance fields        : true
[INFO]   sequences              : true
[INFO]   udts                   : true
[INFO]   routines               : true
[INFO]   tables                 : true
[INFO]   records                : true
[INFO]   pojos                  : false
[INFO]   immutable pojos        : false
[INFO]   interfaces             : false
[INFO]   immutable interfaces   : false
[INFO]   daos                   : false
[INFO]   relations              : true
[INFO]   table-valued functions : true
[INFO]   global references      : true
[INFO] ----------------------------------------------------------
[INFO]
[INFO] Generation remarks
[INFO] ----------------------------------------------------------
[INFO]
[INFO] ----------------------------------------------------------
[INFO]

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@  @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@        @@@@@@@@@@
@@@@@@@@@@@@@@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@  @@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@        @@  @  @  @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@  @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  Thank you for using the 30 day free jOOQ 3.9.3 trial edition

[INFO] Generating catalogs      : Total: 0
[INFO] Removing excess files
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.214 s
[INFO] Finished at: 2017-07-04T18:10:46-05:00
[INFO] Final Memory: 23M/217M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0
</code>```

Here is how I am running the generator tool;

答:
This is a known issue in jOOQ 3.9.3: https://github.com/jOOQ/jOOQ/issues/6064

You have to specify an <inputCatalog/> if you want to specify an <inputSchema/> as well. The catalog is the name of your database.

Body:
Hi I am trying to generate jooq code files without success. I am using intellij and maven to generate code. When I try an d generate the code nothing happens. I get this message: [INFO] Generating catalogs : Total: 0. I am using Sql server express with Jooq trial. Here is my pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>service</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.groupid</groupId>
            <artifactId>entities</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>6.1.0.jre8</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jooq.trial</groupId>
            <artifactId>jooq</artifactId>
            <version>3.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.jooq.trial</groupId>
            <artifactId>jooq-meta</artifactId>
            <version>3.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.jooq.trial</groupId>
            <artifactId>jooq-codegen</artifactId>
            <version>3.9.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jooq.trial</groupId>
                <artifactId>jooq-codegen-maven</artifactId>
                <version>3.9.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

                <dependencies>
                    <dependency>
                        <groupId>com.microsoft.sqlserver</groupId>
                        <artifactId>mssql-jdbc</artifactId>
                        <version>6.1.0.jre8</version>
                    </dependency>
                </dependencies>

                <configuration>

                    <jdbc>
                        <driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver>
                        <url>jdbc:sqlserver://localhost;databaseName=test</url>
                        <user>sa</user>
                        <password>test</password>
                    </jdbc>

                    <generator>
                        <database>
                            <includes>.*</includes>
                            <excludes></excludes>

                            <inputSchema>dbo</inputSchema>
                        </database>
                        <target>
                            <packageName>mypackage</packageName>
                            <directory>mypath</directory>
                        </target>
                    </generator>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Here is the output I get when trying to generate the files.

"C:\Program Files\Java\jdk1.8.0_131\bin\java" -Dmaven.multiModuleProjectDirectory=C:\projects\service "-Dmaven.home=C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\plugins\maven\lib\maven3" "-Dclassworlds.conf=C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\plugins\maven\lib\maven3\bin\m2.conf" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\lib\idea_rt.jar=59337:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.2\plugins\maven\lib\maven3\boot\plexus-classworlds-2.5.2.jar" org.codehaus.classworlds.Launcher -Didea.version=2017.1.4 jooq-codegen:generate
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building service 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- jooq-codegen-maven:3.9.3:generate (default-cli) @ service ---
[INFO] Database                 : Inferring database org.jooq.util.sqlserver.SQLServerDatabase from URL jdbc:sqlserver://localhost:1433;authentication=NotSpecified;authenticationScheme=nativeAuthentication;xopenStates=false;sendTimeAsDatetime=true;trustServerCertificate=false;TransparentNetworkIPResolution=true;serverNameAsACE=false;sendStringParametersAsUnicode=true;selectMethod=direct;responseBuffering=adaptive;packetSize=8000;multiSubnetFailover=false;loginTimeout=15;lockTimeout=-1;lastUpdateCount=true;encrypt=false;disableStatementPooling=true;databaseName=test;columnEncryptionSetting=Disabled;applicationName=Microsoft JDBC Driver for SQL Server;applicationIntent=readwrite;
[INFO] No <inputCatalog/> was provided. Generating ALL available catalogs instead.
[INFO] License parameters
[INFO] ----------------------------------------------------------
[INFO]   Thank you for using jOOQ and jOOQ's code generator
[INFO]
[INFO] Database parameters
[INFO] ----------------------------------------------------------
[INFO]   dialect                : SQLSERVER
[INFO]   URL                    : jdbc:sqlserver://localhost:1433;authentication=NotSpecified;authenticationScheme=nativeAuthentication;xopenStates=false;sendTimeAsDatetime=true;trustServerCertificate=false;TransparentNetworkIPResolution=true;serverNameAsACE=false;sendStringParametersAsUnicode=true;selectMethod=direct;responseBuffering=adaptive;packetSize=8000;multiSubnetFailover=false;loginTimeout=15;lockTimeout=-1;lastUpdateCount=true;encrypt=false;disableStatementPooling=true;databaseName=test;columnEncryptionSetting=Disabled;applicationName=Microsoft JDBC Driver for SQL Server;applicationIntent=readwrite;
[INFO]   target dir             : [target dir]
[INFO]   target package         : com.test
[INFO]   includes               : [.*]
[INFO]   excludes               : []
[INFO]   includeExcludeColumns  : false
[INFO] ----------------------------------------------------------
[INFO]
[INFO] JavaGenerator parameters
[INFO] ----------------------------------------------------------
[INFO]   strategy               : class org.jooq.util.DefaultGeneratorStrategy
[INFO]   deprecated             : true
[INFO]   generated annotation   : true
[INFO]   JPA annotations        : false
[INFO]   validation annotations : false
[INFO]   instance fields        : true
[INFO]   sequences              : true
[INFO]   udts                   : true
[INFO]   routines               : true
[INFO]   tables                 : true
[INFO]   records                : true
[INFO]   pojos                  : false
[INFO]   immutable pojos        : false
[INFO]   interfaces             : false
[INFO]   immutable interfaces   : false
[INFO]   daos                   : false
[INFO]   relations              : true
[INFO]   table-valued functions : true
[INFO]   global references      : true
[INFO] ----------------------------------------------------------
[INFO]
[INFO] Generation remarks
[INFO] ----------------------------------------------------------
[INFO]
[INFO] ----------------------------------------------------------
[INFO]

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@  @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@        @@@@@@@@@@
@@@@@@@@@@@@@@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@  @@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@        @@  @  @  @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@  @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  Thank you for using the 30 day free jOOQ 3.9.3 trial edition

[INFO] Generating catalogs      : Total: 0
[INFO] Removing excess files
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.214 s
[INFO] Finished at: 2017-07-04T18:10:46-05:00
[INFO] Final Memory: 23M/217M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0

Here is how I am running the generator tool;


来源: stackexchange

问:
Embed PDF file in the html from /var/www/pdf/ directory
I want to embed pdf file in my website from /var/www/pdf/ directory. I have hosted my webpage at /var/www/html/portal/index.php. I tried following ways

1) using embed

2) using iframe

```<code><iframe src="../../pdf/ebook.pdf" width="900" height="750" frameborder="0" allowfullscreen></iframe>
</code>```

3) using object

```<code><object data="../../pdf/ebook.pdf#scrollbar=0&toolbar=0&navpanes=0" width="900" height="750" type="application/pdf">
    <p>PDF cannot be displayed</p>
</object>
</code>```

None of them working, but if I place the pdf file /var/www/html/pdf/ folder it is working fine.

For my requirement, I cannot keep the file in the web directory because public can access the PDF file directly using URL without login in to my web portal. And Also google also can index my PDF file from public search

Please help me to embed pdf

Thanks in advance

答:
I found solution using php script</p>

```<code>header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=filename.pdf");
@readfile('../../pdf/ebook.pdf');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to embed pdf file in my website from /var/www/pdf/ directory. I have hosted my webpage at /var/www/html/portal/index.php. I tried following ways

1) using embed

2) using iframe

3) using object

<object data="../../pdf/ebook.pdf#scrollbar=0&toolbar=0&navpanes=0" width="900" height="750" type="application/pdf">

PDF cannot be displayed

</object>

None of them working, but if I place the pdf file /var/www/html/pdf/ folder it is working fine.

For my requirement, I cannot keep the file in the web directory because public can access the PDF file directly using URL without login in to my web portal. And Also google also can index my PDF file from public search

Please help me to embed pdf

Thanks in advance

Body:
I found solution using php script

header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=filename.pdf");
@readfile('../../pdf/ebook.pdf');


问:
OpenCV Watershed segmentation miss some objects
My code is the same as this tutorial.
When I see the result image after using cv::watershed(), there is a object(upper-right) that I want to find out, but it's missing.
There are indeed six marks in image after using cv::drawContours().
Is this normal because the inaccuracy of the watershed algorithm exist?

Here is part of my code:

```<code>Mat src = imread("result01.png");

Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);

Mat thresh;
threshold(gray, thresh, 0, 255, THRESH_BINARY | THRESH_OTSU);

// noise removal
Mat kernel = Mat::ones(3, 3, CV_8UC1);
Mat opening;
morphologyEx(thresh, opening, MORPH_OPEN, kernel, Point(-1, -1), 2);

// Perform the distance transform algorithm
Mat dist_transform;
distanceTransform(opening, dist_transform, CV_DIST_L2, 5);

// Normalize the distance image for range = {0.0, 1.0}
// so we can visualize and threshold it
normalize(dist_transform, dist_transform, 0, 1., NORM_MINMAX);

// Threshold to obtain the peaks
// This will be the markers for the foreground objects
Mat dist_thresh;
threshold(dist_transform, dist_thresh, 0.5, 1., CV_THRESH_BINARY);

Mat dist_8u;
dist_thresh.convertTo(dist_8u, CV_8U);

// Find total markers
vector<vector<Point> > contours;
findContours(dist_8u, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

// Create the marker image for the watershed algorithm
Mat markers = Mat::zeros(dist_thresh.size(), CV_32SC1);

// Draw the foreground markers
for (size_t i = 0; i < contours.size(); i++)
    drawContours(markers, contours, static_cast<int>(i), Scalar::all(static_cast<int>(i)+1), -1);

// Perform the watershed algorithm
watershed(src, markers);
</code>```

Original image:

Result after watershed:

You can find original, intermediate and result image here:

Result images after specific process

答:
there is very  little emgu cv data on watershed.
here is my translation to this problem using c#. i know it is not the right forum but this answer kips popping up so to all the searchers:

```<code>//Mat3b src = imread("path_to_image");

//cvtColor(src, gray, COLOR_BGR2GRAY);
Image<Gray, byte> gray = smallImage.Convert<Gray, byte>();

//threshold(gray, thresh, 0, 255, THRESH_BINARY | THRESH_OTSU);
Image<Gray, byte> thresh = gray.ThresholdBinaryInv(new Gray(55), new Gray(255));

// noise removal
Mat kernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3), new Point(-1, -1));

//Mat1b opening;
//morphologyEx(thresh, opening, MORPH_OPEN, kernel, Point(-1, -1), 2);
Image<Gray, byte> opening = thresh.MorphologyEx(MorphOp.Open, kernel, new Point(-1, -1), 2, BorderType.Default, new MCvScalar(255));

//Mat1b kernelb = getStructuringElement(MORPH_RECT, Size(21, 21));
Mat kernel1 = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3), new Point(-1, -1));
//Mat1b background;
//morphologyEx(thresh, background, MORPH_DILATE, kernelb);
Image<Gray, byte> background = thresh.MorphologyEx(MorphOp.Dilate, kernel, new Point(-1, -1), 2, BorderType.Default, new MCvScalar(255));
background = ~background;

//// Perform the distance transform algorithm
//Mat1f dist_transform;
//distanceTransform(opening, dist_transform, CV_DIST_L2, 5);
Image<Gray, float> dist_transform = new Image<Gray, float>(opening.Width, opening.Height);
CvInvoke.DistanceTransform(opening, dist_transform, null, DistType.L2, 5);

//// Normalize the distance image for range = {0.0, 1.0}
//// so we can visualize and threshold it
//normalize(dist_transform, dist_transform, 0, 1., NORM_MINMAX);
CvInvoke.Normalize(dist_transform, dist_transform, 0, 1.0, NormType.MinMax, DepthType.Default);

//// Threshold to obtain the peaks
//// This will be the markers for the foreground objects
//Mat1f dist_thresh;
//threshold(dist_transform, dist_thresh, 0.5, 1., CV_THRESH_BINARY);
Image<Gray, float> dist_thresh = new Image<Gray, float>(opening.Width, opening.Height);
CvInvoke.Threshold(dist_transform, dist_thresh, 0.5, 1.0, ThresholdType.Binary);

//Mat1b dist_8u;
//dist_thresh.convertTo(dist_8u, CV_8U);
Image<Gray, Byte> dist_8u = dist_thresh.Convert<Gray, Byte>();

//// Find total markers
//vector<vector<Point>> contours;
//findContours(dist_8u, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
CvInvoke.FindContours(dist_8u, contours, null, RetrType.External, ChainApproxMethod.ChainApproxSimple);

//// Create the marker image for the watershed algorithm
//Mat1i markers(dist_thresh.rows, dist_thresh.cols, int(0));
Image<Gray, int> markers = new Image<Gray, int>(dist_thresh.Width, dist_thresh.Height, new Gray(0));

//// Background as 1
//Mat1i one(markers.rows, markers.cols, int(1));
//bitwise_or(one, markers, markers, background);
Image<Gray, int> one = new Image<Gray, int>(markers.Cols, markers.Rows, new Gray(1));
CvInvoke.BitwiseOr(one, markers, markers, background);

//// Draw the foreground markers (from 2 up)
for (int i = 0; i < contours.Size; i++)
//  drawContours(markers, contours, i, Scalar(i + 2), -1);
    CvInvoke.DrawContours(markers, contours, i, new MCvScalar(i + 2));

//// Perform the watershed algorithm
//Mat3b dbg;
//cvtColor(opening, dbg, COLOR_GRAY2BGR);
//watershed(dbg, markers);
Image<Bgr, byte> dbg = new Image<Bgr, byte>(markers.Cols, markers.Rows);
CvInvoke.CvtColor(opening, dbg, ColorConversion.Gray2Bgr);
CvInvoke.Watershed(dbg, markers);

//Mat res;
//markers.convertTo(res, CV_8U);
//normalize(res, res, 0, 255, NORM_MINMAX);
CvInvoke.Normalize(markers, markers, 0, 255, NormType.MinMax);

//return 0;
</code>```

to find light objects on dark background replace ThresholdBinaryInv with ThresholdBinary

Body:
My code is the same as this tutorial.
When I see the result image after using cv::watershed(), there is a object(upper-right) that I want to find out, but it's missing.
There are indeed six marks in image after using cv::drawContours().
Is this normal because the inaccuracy of the watershed algorithm exist?

Here is part of my code:

Mat src = imread("result01.png");

Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);

Mat thresh;
threshold(gray, thresh, 0, 255, THRESH_BINARY | THRESH_OTSU);

// noise removal
Mat kernel = Mat::ones(3, 3, CV_8UC1);
Mat opening;
morphologyEx(thresh, opening, MORPH_OPEN, kernel, Point(-1, -1), 2);

// Perform the distance transform algorithm
Mat dist_transform;
distanceTransform(opening, dist_transform, CV_DIST_L2, 5);

// Normalize the distance image for range = {0.0, 1.0}
// so we can visualize and threshold it
normalize(dist_transform, dist_transform, 0, 1., NORM_MINMAX);

// Threshold to obtain the peaks
// This will be the markers for the foreground objects
Mat dist_thresh;
threshold(dist_transform, dist_thresh, 0.5, 1., CV_THRESH_BINARY);

Mat dist_8u;
dist_thresh.convertTo(dist_8u, CV_8U);

// Find total markers
vector<vector<Point> > contours;
findContours(dist_8u, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

// Create the marker image for the watershed algorithm
Mat markers = Mat::zeros(dist_thresh.size(), CV_32SC1);

// Draw the foreground markers
for (size_t i = 0; i < contours.size(); i++)
    drawContours(markers, contours, static_cast<int>(i), Scalar::all(static_cast<int>(i)+1), -1);

// Perform the watershed algorithm
watershed(src, markers);

Original image:

Result after watershed:

You can find original, intermediate and result image here:

Result images after specific process

Body:
there is very  little emgu cv data on watershed.
here is my translation to this problem using c#. i know it is not the right forum but this answer kips popping up so to all the searchers:

//Mat3b src = imread("path_to_image");

//cvtColor(src, gray, COLOR_BGR2GRAY);
Image<Gray, byte> gray = smallImage.Convert<Gray, byte>();

//threshold(gray, thresh, 0, 255, THRESH_BINARY | THRESH_OTSU);
Image<Gray, byte> thresh = gray.ThresholdBinaryInv(new Gray(55), new Gray(255));

// noise removal
Mat kernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3), new Point(-1, -1));

//Mat1b opening;
//morphologyEx(thresh, opening, MORPH_OPEN, kernel, Point(-1, -1), 2);
Image<Gray, byte> opening = thresh.MorphologyEx(MorphOp.Open, kernel, new Point(-1, -1), 2, BorderType.Default, new MCvScalar(255));

//Mat1b kernelb = getStructuringElement(MORPH_RECT, Size(21, 21));
Mat kernel1 = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3), new Point(-1, -1));
//Mat1b background;
//morphologyEx(thresh, background, MORPH_DILATE, kernelb);
Image<Gray, byte> background = thresh.MorphologyEx(MorphOp.Dilate, kernel, new Point(-1, -1), 2, BorderType.Default, new MCvScalar(255));
background = ~background;

//// Perform the distance transform algorithm
//Mat1f dist_transform;
//distanceTransform(opening, dist_transform, CV_DIST_L2, 5);
Image<Gray, float> dist_transform = new Image<Gray, float>(opening.Width, opening.Height);
CvInvoke.DistanceTransform(opening, dist_transform, null, DistType.L2, 5);

//// Normalize the distance image for range = {0.0, 1.0}
//// so we can visualize and threshold it
//normalize(dist_transform, dist_transform, 0, 1., NORM_MINMAX);
CvInvoke.Normalize(dist_transform, dist_transform, 0, 1.0, NormType.MinMax, DepthType.Default);

//// Threshold to obtain the peaks
//// This will be the markers for the foreground objects
//Mat1f dist_thresh;
//threshold(dist_transform, dist_thresh, 0.5, 1., CV_THRESH_BINARY);
Image<Gray, float> dist_thresh = new Image<Gray, float>(opening.Width, opening.Height);
CvInvoke.Threshold(dist_transform, dist_thresh, 0.5, 1.0, ThresholdType.Binary);

//Mat1b dist_8u;
//dist_thresh.convertTo(dist_8u, CV_8U);
Image<Gray, Byte> dist_8u = dist_thresh.Convert<Gray, Byte>();

//// Find total markers
//vector<vector<Point>> contours;
//findContours(dist_8u, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
CvInvoke.FindContours(dist_8u, contours, null, RetrType.External, ChainApproxMethod.ChainApproxSimple);

//// Create the marker image for the watershed algorithm
//Mat1i markers(dist_thresh.rows, dist_thresh.cols, int(0));
Image<Gray, int> markers = new Image<Gray, int>(dist_thresh.Width, dist_thresh.Height, new Gray(0));

//// Background as 1
//Mat1i one(markers.rows, markers.cols, int(1));
//bitwise_or(one, markers, markers, background);
Image<Gray, int> one = new Image<Gray, int>(markers.Cols, markers.Rows, new Gray(1));
CvInvoke.BitwiseOr(one, markers, markers, background);

//// Draw the foreground markers (from 2 up)
for (int i = 0; i < contours.Size; i++)
//  drawContours(markers, contours, i, Scalar(i + 2), -1);
    CvInvoke.DrawContours(markers, contours, i, new MCvScalar(i + 2));

//// Perform the watershed algorithm
//Mat3b dbg;
//cvtColor(opening, dbg, COLOR_GRAY2BGR);
//watershed(dbg, markers);
Image<Bgr, byte> dbg = new Image<Bgr, byte>(markers.Cols, markers.Rows);
CvInvoke.CvtColor(opening, dbg, ColorConversion.Gray2Bgr);
CvInvoke.Watershed(dbg, markers);

//Mat res;
//markers.convertTo(res, CV_8U);
//normalize(res, res, 0, 255, NORM_MINMAX);
CvInvoke.Normalize(markers, markers, 0, 255, NormType.MinMax);

//return 0;

to find light objects on dark background replace ThresholdBinaryInv with ThresholdBinary


问:
UITextView with clickable links but no text highlighting
I have a UITextView displaying non-editable text. I want the text to automatically parse links, phone numbers, etc for the user, and for those to be clickable.

I don't want the user to be able to highlight text, though, because I want to override those long press and double-tap interactions to do something different.

In order for links to be parsed in iOS7, the Selectable switch needs to be turned on for the UITextView, but Selectable also enables highlighting, which I don't want.

I tried overriding the LongPress gesture to prevent highlighting, but that seems to have disabled ordinary taps on links as well...

```<code>for (UIGestureRecognizer *recognizer in cell.messageTextView.gestureRecognizers) {
    if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
        recognizer.enabled = NO;
    }
    if ([recognizer isKindOfClass:[UITapGestureRecognizer class]]){
        recognizer.enabled = YES;
    }
}
</code>```

There are lots of similar threads out there but none seem to address this specific question of links enabled, text not highlightable.

答:
This pretty much addresses the issue as text selection is disabled and hides magnifying glass -- links will still work.

```<code>func textViewDidChangeSelection(_ textView: UITextView) {
    if let gestureRecognizers = textView.gestureRecognizers {
        for recognizer in gestureRecognizers {
            if recognizer is UILongPressGestureRecognizer {
                if let index = textView.gestureRecognizers?.index(of: recognizer) {
                    textView.gestureRecognizers?.remove(at: index)
                }
            }
        }
    }
}
</code>```

Note: Instead of removing, you can replace the recognizer with your desired one.

Body:
I have a UITextView displaying non-editable text. I want the text to automatically parse links, phone numbers, etc for the user, and for those to be clickable.

I don't want the user to be able to highlight text, though, because I want to override those long press and double-tap interactions to do something different.

In order for links to be parsed in iOS7, the Selectable switch needs to be turned on for the UITextView, but Selectable also enables highlighting, which I don't want.

I tried overriding the LongPress gesture to prevent highlighting, but that seems to have disabled ordinary taps on links as well...

for (UIGestureRecognizer *recognizer in cell.messageTextView.gestureRecognizers) {
    if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
        recognizer.enabled = NO;
    }
    if ([recognizer isKindOfClass:[UITapGestureRecognizer class]]){
        recognizer.enabled = YES;
    }
}

There are lots of similar threads out there but none seem to address this specific question of links enabled, text not highlightable.

Body:
This pretty much addresses the issue as text selection is disabled and hides magnifying glass -- links will still work.

func textViewDidChangeSelection(_ textView: UITextView) {
    if let gestureRecognizers = textView.gestureRecognizers {
        for recognizer in gestureRecognizers {
            if recognizer is UILongPressGestureRecognizer {
                if let index = textView.gestureRecognizers?.index(of: recognizer) {
                    textView.gestureRecognizers?.remove(at: index)
                }
            }
        }
    }
}

Note: Instead of removing, you can replace the recognizer with your desired one.


问:
version control practice
In my current job the supervisor's practice is to only check in production ready code.  Most recently the project I was on involved work by 3 different developers with some file overlap.  This meant manually integrating changes despite the fact that some changes took a day and then it was done.  I wanted to see if this was a common practice and get suggestions on how to change this practice with the knowledge that many times my opinion means little in the grand scheme of things.</p>

答:
An approach I particularly like is to have different life cycle versions in the depot. That is,for example, have a dev version of the code that is where the developers check in code that is in being worked on; then you could have a beta version, where you could add beta fixes to your code; and then a production version.

There is obvious overhead in this approach, such as the fact that you will have a larger workspace on you local machine, the fact that you will need need to have a migration process into place to move code from one stage to the next (which means a code freeze when doing the integration testing that goes with the migration), and that depending on the complexity of the project(s) you might need to have tools that change settings, environment variables, registry entries, etc.

All of this is a pain to set up, but you only do it once, and once you have it all in place, makes working on different stages of the code a breeze.

ContentLicense: CC BY-SA 2.5

Title: version control practice


问:
How to get date time format from javascript?
I want to display date of today according the current datetime format without displaying the seconds

Thanks for help

答:
You have to write some code yourself to do it, or you could use a library like Date.js.

JavaScript "Date" object instances have methods like .getFullYear(), .getMonth(), .getDate(), and so on. (Be aware that .getMonth() returns numbers from 0 through 11, not 1 through 12.)


问:
Pandas Assign Lambda Function
I have a DataFrame which has an open time and a close time and I am trying to calculate the difference in milliseconds.

My code is currently like this

```<code>df = df.assign(Latency=lambda d: d.CloseTimeStamp - d.CreationTimeStamp)
df.Latency = df.apply(lambda d: d.Latency.total_seconds() * 1000., axis=1)
</code>```

However, I'd like to know why I can't do as a one-liner like so

```<code>df = df.assign(Latency=lambda d: (d.CloseTimeStamp - d.CreationTimeStamp).total_seconds() * 1000.)
</code>```

When I try the latter I get AttributeError: 'Series' object has no attribute 'total_seconds'

答:
Need .dt accessor, because working with datetime Series, .dt is omit if DatetimeIndex:

```<code>df = df.assign(Latency=lambda d: (d.CloseTimeStamp -  d.CreationTimeStamp).dt.total_seconds() * 1000.)
</code>```

Solution without lambda:

```<code>df = df.assign(Latency=(df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.)
</code>```

...and solution without assign:

```<code>df['Latency'] = (df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.
</code>```

Title: Pandas Assign Lambda Function

Body:
I have a DataFrame which has an open time and a close time and I am trying to calculate the difference in milliseconds.

My code is currently like this

df = df.assign(Latency=lambda d: d.CloseTimeStamp - d.CreationTimeStamp)
df.Latency = df.apply(lambda d: d.Latency.total_seconds() * 1000., axis=1)

However, I'd like to know why I can't do as a one-liner like so

df = df.assign(Latency=lambda d: (d.CloseTimeStamp - d.CreationTimeStamp).total_seconds() * 1000.)

When I try the latter I get AttributeError: 'Series' object has no attribute 'total_seconds'

Body:
Need .dt accessor, because working with datetime Series, .dt is omit if DatetimeIndex:

df = df.assign(Latency=lambda d: (d.CloseTimeStamp -  d.CreationTimeStamp).dt.total_seconds() * 1000.)

Solution without lambda:

df = df.assign(Latency=(df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.)

...and solution without assign:

df['Latency'] = (df.CloseTimeStamp - df.CreationTimeStamp).dt.total_seconds() * 1000.


问:
Using Jest with Jquery
A Jest unit test that tests a React component which calls certain Jquery functions is not passing. I'm receiving the following error: Error Snapshot

What can I do to solve this?

答: Would require more information about how you ran the test and whether or not you exposed Jquery correctly. This seems to be a problem of not having Jquery either 'imported' or 'required' properly in the test file.

Title: Using Jest with Jquery


问:
MAMP mysql server won't start. No mysql processes are running
My MAMP mysql server won't start. All of the suggestions I've seen on the web say to check for other mysqld processes running and kill them if they exist, and that it should fix the problem, but it has not for me.

Here's the error log:

```<code>130415 13:42:12 mysqld_safe Starting mysqld daemon with databases from /Library/Application Support/appsolute/MAMP PRO/db/mysql
130415 13:42:12 [Warning] Setting lower_case_table_names=2 because file system for /Library/Application Support/appsolute/MAMP PRO/db/mysql/ is case insensitive
130415 13:42:12 [Note] Plugin 'FEDERATED' is disabled.
130415 13:42:12 InnoDB: The InnoDB memory heap is disabled
130415 13:42:12 InnoDB: Mutexes and rw_locks use GCC atomic builtins
130415 13:42:12 InnoDB: Compressed tables use zlib 1.2.3
130415 13:42:12 InnoDB: Initializing buffer pool, size = 128.0M
130415 13:42:12 InnoDB: Completed initialization of buffer pool
130415 13:42:12 InnoDB: highest supported file format is Barracuda.
130415 13:42:13  InnoDB: Waiting for the background threads to start
130415 13:42:14 InnoDB: 1.1.8 started; log sequence number 1707549
130415 13:42:14 [Note] Event Scheduler: Loaded 0 events
130415 13:42:14 [Note] /Applications/MAMP/Library/bin/mysqld: ready for connections.
Version: '5.5.25'  socket: '/Applications/MAMP/tmp/mysql/mysql.sock'  port: 0  Source distribution
</code>```

It looks like the connection is open to me, but MAMP stil errors out with this message: "MySQL wasn't able to start. Please check log for more information."

Any suggestions?

答:
Stop MAMP server.

Then go in following folder:

Applications/MAMP/db/mysql56/

In this folder, please remove all direct files except folders.
This means that you have to remove only auto.cnf, ibdata, ib_logfile, not any folders.

Restart MAMP server.

It should work.

Thank you.

Body:
My MAMP mysql server won't start. All of the suggestions I've seen on the web say to check for other mysqld processes running and kill them if they exist, and that it should fix the problem, but it has not for me.

Here's the error log:

130415 13:42:12 mysqld_safe Starting mysqld daemon with databases from /Library/Application Support/appsolute/MAMP PRO/db/mysql
130415 13:42:12 [Warning] Setting lower_case_table_names=2 because file system for /Library/Application Support/appsolute/MAMP PRO/db/mysql/ is case insensitive
130415 13:42:12 [Note] Plugin 'FEDERATED' is disabled.
130415 13:42:12 InnoDB: The InnoDB memory heap is disabled
130415 13:42:12 InnoDB: Mutexes and rw_locks use GCC atomic builtins
130415 13:42:12 InnoDB: Compressed tables use zlib 1.2.3
130415 13:42:12 InnoDB: Initializing buffer pool, size = 128.0M
130415 13:42:12 InnoDB: Completed initialization of buffer pool
130415 13:42:12 InnoDB: highest supported file format is Barracuda.
130415 13:42:13  InnoDB: Waiting for the background threads to start
130415 13:42:14 InnoDB: 1.1.8 started; log sequence number 1707549
130415 13:42:14 [Note] Event Scheduler: Loaded 0 events
130415 13:42:14 [Note] /Applications/MAMP/Library/bin/mysqld: ready for connections.
Version: '5.5.25'  socket: '/Applications/MAMP/tmp/mysql/mysql.sock'  port: 0  Source distribution

It looks like the connection is open to me, but MAMP stil errors out with this message: "MySQL wasn't able to start. Please check log for more information."

Any suggestions?


问:
Break lines in <input> tag HTML + CSS
I have  tag with type "text", with limit to 2,000 characters.
I want to break lines, but " word-wrap: break-word;" not working because its not a div..

here is the css :

```<code>  background: #ffffff;
  -moz-box-sizing: border-box;
  border: 1px solid #CBD5DD;
  border-radius: 2px;
  height: 70px;
  max-width: 450px;
  word-wrap: break-word;
  margin: 0;
  min-height: 33px;
  overflow: visible;
  position: relative;
  width: 450px;
  padding-left:5px;
  vertical-align:top;
  box-sizing: border-box;
</code>```

any suggestions ?
thanks

答: You can't have line breaks in a input[type="text"] as it does not support multiple lines, use a textarea instead.

Title: Break lines in <input> tag HTML + CSS

Body:
I have  tag with type "text", with limit to 2,000 characters.
I want to break lines, but " word-wrap: break-word;" not working because its not a div..

here is the css :

  background: #ffffff;
  -moz-box-sizing: border-box;
  border: 1px solid #CBD5DD;
  border-radius: 2px;
  height: 70px;
  max-width: 450px;
  word-wrap: break-word;
  margin: 0;
  min-height: 33px;
  overflow: visible;
  position: relative;
  width: 450px;
  padding-left:5px;
  vertical-align:top;
  box-sizing: border-box;

any suggestions ?
thanks


问:
if statement inside while that depends on the same variable that while depends on
consider the below programs.
I would like to know why this codes behave in different way.Thankyou in advance.

this doesnot print any

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

int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d", i++);
    }
}
</code>```

while this does

```<code>#include <stdio.h>
int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d\n", i++);
    }
}
</code>```

答:
Please read this.

For example simply including a "\n" in the printed stuff will typically flush it (because stdout is by default line-buffered when attached to a terminal).

```<code>#include<stdio.h>
int main() {
    int i=0;
    while(i<10) {
        if(i<7)
            printf("value is%d",i++);
        fflush(stdout);
    }
}
</code>```

Body:
consider the below programs.
I would like to know why this codes behave in different way.Thankyou in advance.

this doesnot print any

#include <stdio.h>

int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d", i++);
    }
}

while this does

#include <stdio.h>
int main() {
    int i = 0;

    while(i < 10) {
        if(i < 7)
            printf("value is%d\n", i++);
    }
}

Body:
Please read this.

For example simply including a "\n" in the printed stuff will typically flush it (because stdout is by default line-buffered when attached to a terminal).

#include<stdio.h>
int main() {
    int i=0;
    while(i<10) {
        if(i<7)
            printf("value is%d",i++);
        fflush(stdout);
    }
}


问:
fortran read statement not stopping
program not stopping to read "ar". help please. even after allocating that it has definite number of elements. what may be the reason? is there something a could have missed?</p>

```<code>program summer_a39
    implicit none
    integer:: n, i, l, k
    integer, allocatable, dimension(:)::ar
    print*, 'Enter size of array:'
    read*, n
    allocate (ar(n))
    print*, 'Enter values:'
    read*, ar
    l=1
    3 do i=l,n-1
        if (l==n) then
        goto 4
        end if
        if (ar(i)<=ar(i+1)) then
        goto 1
        else
        goto 2
        end if
    end do
    1 do i=l,n-1
        do while (ar(i)<=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Increases to', l
    goto 3
    2 do i=l,n
        do while (ar(i)>=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Decreases to', l
    goto 3
    4 print*, 'The End'
    deallocate(ar)
    end program
</code>```

答:
After your comments to my previous answer, I got a better idea of your situation.

Here's what I understand so far:

You have an exercise for a Fortran training/lessons/etc.

The exercise is to create a program that takes as input an array of arbitrary length, and then prints out the final values of each monotonic sequence in that array. So for example, if the input were 4 3 7 2 1 4 6 3 5 10, then the output should be something like:

```<code>Starts with 4
Decreases to 3
Increases to 7
Decreases to 1
Increases to 6
Decreases to 3
Increases to 10
The end
</code>```

Part of the exercise is that you should make use of the GOTO command.

So here's my updated answer:

This is not a homework service, we won't solve the issue for you. Then again, you didn't ask for that, so that's okay.

Your issue is not the read*, ar command. You can test this out easily by just adding a print*, ar right below it, it will print.

Your issue is that there is an infinite loop inside your code (actually, there are several), some because you use DO WHILE loops where the condition never changes in the iteration, some because you jump out of one loop to the beginning of another, which resets the initial conditions.

Here are some hints for your exercise:

Create a single variable for the index of the array that you're currently looking at.

Create two loops, one for increasing this index as long as the next value in the array is larger, and one as long as the next value is smaller. Check that you don't increase the index beyond the range of the array.

Do not jump from inside of any loop

Do not jump into the middle any loop.

At the end of either loop, think about what you learned about the array, and were to jump to from there.

Make sure that you know that the algorithm will eventually stop.

And finally, there's no harm in using lots of print* statements during debugging to make you understand what the program is actually doing.

Title: fortran read statement not stopping

Body:
program not stopping to read "ar". help please. even after allocating that it has definite number of elements. what may be the reason? is there something a could have missed?

program summer_a39
    implicit none
    integer:: n, i, l, k
    integer, allocatable, dimension(:)::ar
    print*, 'Enter size of array:'
    read*, n
    allocate (ar(n))
    print*, 'Enter values:'
    read*, ar
    l=1
    3 do i=l,n-1
        if (l==n) then
        goto 4
        end if
        if (ar(i)<=ar(i+1)) then
        goto 1
        else
        goto 2
        end if
    end do
    1 do i=l,n-1
        do while (ar(i)<=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Increases to', l
    goto 3
    2 do i=l,n
        do while (ar(i)>=ar(i+1))
        k=k+1
        end do
        l=k
    end do
    print*, 'Decreases to', l
    goto 3
    4 print*, 'The End'
    deallocate(ar)
    end program

Body:
After your comments to my previous answer, I got a better idea of your situation.

Here's what I understand so far:

You have an exercise for a Fortran training/lessons/etc.

The exercise is to create a program that takes as input an array of arbitrary length, and then prints out the final values of each monotonic sequence in that array. So for example, if the input were 4 3 7 2 1 4 6 3 5 10, then the output should be something like:

Starts with 4
Decreases to 3
Increases to 7
Decreases to 1
Increases to 6
Decreases to 3
Increases to 10
The end

Part of the exercise is that you should make use of the GOTO command.

So here's my updated answer:

This is not a homework service, we won't solve the issue for you. Then again, you didn't ask for that, so that's okay.

Your issue is not the read*, ar command. You can test this out easily by just adding a print*, ar right below it, it will print.

Your issue is that there is an infinite loop inside your code (actually, there are several), some because you use DO WHILE loops where the condition never changes in the iteration, some because you jump out of one loop to the beginning of another, which resets the initial conditions.

Here are some hints for your exercise:

Create a single variable for the index of the array that you're currently looking at.

Create two loops, one for increasing this index as long as the next value in the array is larger, and one as long as the next value is smaller. Check that you don't increase the index beyond the range of the array.

Do not jump from inside of any loop

Do not jump into the middle any loop.

At the end of either loop, think about what you learned about the array, and were to jump to from there.

Make sure that you know that the algorithm will eventually stop.

And finally, there's no harm in using lots of print* statements during debugging to make you understand what the program is actually doing.


问:
AspectJ pointcut on method variable, is it possible?
I have been using AspectJ for a while and it works great on object scope fields containing annotations. I just ran into a situation where I want to annotate a variable of method scope that will work with my pointcut but I am having trouble with it.

Here is the pointcut that I am using. It works fine if my variable is a field for the object, but if I reduce the scope to a method (variable declared inside the method), then it doesn't work anymore and I am not sure why. Let me know what I can do, thanks.

```<code> after(final Trigger trigger): set(@Triggereable * *) && args(trigger)
 {
  System.out.println("trigger flush");
 }
</code>```

Also, here is an exmaple of what I want to work. That System.out.println above should fire when the Trigger is instantiated:

```<code>public void foo()
{
   @Triggereable
   private Trigger trigger = new Trigger();
}
</code>```

答:
AspectJ does not currently support pointcuts on local variables (read the FAQ entry).

I seem to recall a recent discussion about such a feature possibly added soon, but I could not find it in the AspectJ issue tracker nor in the Mailing List archives

Body:
I have been using AspectJ for a while and it works great on object scope fields containing annotations. I just ran into a situation where I want to annotate a variable of method scope that will work with my pointcut but I am having trouble with it.

Here is the pointcut that I am using. It works fine if my variable is a field for the object, but if I reduce the scope to a method (variable declared inside the method), then it doesn't work anymore and I am not sure why. Let me know what I can do, thanks.

 after(final Trigger trigger): set(@Triggereable * *) && args(trigger)
 {
  System.out.println("trigger flush");
 }

Also, here is an exmaple of what I want to work. That System.out.println above should fire when the Trigger is instantiated:

public void foo()
{
   @Triggereable
   private Trigger trigger = new Trigger();
}


答:
When you use printf() it just puts your data into STDOUT buffer, its purpose is not to display onto screen. but when you use \n inside the printf() if flushes the STDOUT buffer on screen. you can also use fflush() if you are not using \n.
From fflush() man page

For  output streams, fflush() forces a write of all user-space buffered
         data for the given output or update stream via the stream's  underlying
         write function.  For input streams, fflush() discards any buffered data
         that has been fetched from the underlying file, but has not  been  con-
         sumed by the application.  The open status of the stream is unaffected.

Title: if statement inside while that depends on the same variable that while depends on


问:
CSS 3 : Image doesn't get 100% of div
I have a div in which I am displaying an image. The image is bigger than its contained div.

somehow I get space to top and bottom of the image.

.image_contain_div {
  height: 130px;
  padding: 5px;
  width: 180px;
  border: thin black solid;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div {
  background: #000;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
  height: 100%;
  width: 100%;
  position: relative;
}
.image_contain_div .image_div .custom_website_default_image_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div .custom_website_default_image_div svg {
  width: 26px;
  height: 26px;
}
.image_contain_div .image_div img {
  max-width: 100%;
  max-height: 100%;
}
.image_contain_div .image_div .custom_website_image_overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none;
}
.image_contain_div .image_div .custom_website_image_overlay_div svg {
  width: 30px;
  height: 30px;
}
.image_contain_div .image_div:hover .custom_website_image_overlay_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image_contain_div b">
    <div class="image_div ">

        <img src="https://d28hsb6vkzynsw.cloudfront.net/banner/2877/500/99041_banner_testfile.jpeg" alt="">

        <div class="custom_website_image_overlay_div">
            <span class="cursor_pointer">
                <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                    <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                </svg>
            </span>
        </div>

    </div>
</div></code>```

I want to cover the image to the black background div.

Note : If image is smaller than the div then it should be in the middle of the div.

Any help would be great.

Thank You.

答:
There are savrel ways to do it :  Here is one another solution by replacing the img tag with css :

                                              <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                                                <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                                              </svg>

```

Title: CSS 3 : Image doesn't get 100% of div

Body:
I have a div in which I am displaying an image. The image is bigger than its contained div.

somehow I get space to top and bottom of the image.

.image_contain_div {
  height: 130px;
  padding: 5px;
  width: 180px;
  border: thin black solid;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div {
  background: #000;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
  height: 100%;
  width: 100%;
  position: relative;
}
.image_contain_div .image_div .custom_website_default_image_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div .custom_website_default_image_div svg {
  width: 26px;
  height: 26px;
}
.image_contain_div .image_div img {
  max-width: 100%;
  max-height: 100%;
}
.image_contain_div .image_div .custom_website_image_overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none;
}
.image_contain_div .image_div .custom_website_image_overlay_div svg {
  width: 30px;
  height: 30px;
}
.image_contain_div .image_div:hover .custom_website_image_overlay_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}

                <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                    <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                </svg>

I want to cover the image to the black background div.

Note : If image is smaller than the div then it should be in the middle of the div.

Any help would be great.

Thank You.

Body:
There are savrel ways to do it :  Here is one another solution by replacing the img tag with css :

<style> .image_contain_div {
  height: 130px;
  padding: 5px;
  width: 180px;
  background-size:180px 130px;
  border: thin black solid;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div {
  background: #000;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
  height: 100%;
  width: 100%;
  position: relative;
  background:url(https://d28hsb6vkzynsw.cloudfront.net/banner/2877/500/99041_banner_testfile.jpeg);
  background-size:180px 130px;
}
.image_contain_div .image_div .custom_website_default_image_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div .custom_website_default_image_div svg {
  width: 26px;
  height: 26px;
}
.image_contain_div .image_div img {
  max-width: 100%;
  max-height: 100%;
}
.image_contain_div .image_div .custom_website_image_overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none;
}
.image_contain_div .image_div .custom_website_image_overlay_div svg {
  width: 30px;
  height: 30px;
}
.image_contain_div .image_div:hover .custom_website_image_overlay_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}

</style>
<div class="image_contain_div b">
                                        <div class="image_div">

                                          <div class="custom_website_image_overlay_div">
                                            <span class="cursor_pointer">
                                              <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                                                <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                                              </svg>
                                            </span>

                                          </div>

                                        </div>
                                      </div>


问:
Django 301 and 403 forbidden errors on my static files in production
I'm trying to deploy a django website on a ubuntu 14.04 vps using nginx and gunicorn but my css files and js files are not getting loaded.i developed it on the default django development server and it worked very well, but when i deploy my site and collectstatic and try to access it through the browser only the HTML text gets loaded and on checking on my browser console i find 301 and 403 forbidden errors on my static folder. i a newbie to ubuntu and django as well and all the threads and forums i've found online simply point to permissions and ownership of files and haven't had any luck when i correct my permissions.

screenshot of my browser error when i try to access django admin

here is my settings.py

```<code>import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['mysite.com','www.mysite.com']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'powerlineapp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'powerlineproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'powerlineproject.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

if not DEBUG:
    STATIC_ROOT = '/var/www/powerline/powerlineproject/static/'

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
</code>```

here is my main urls.py

```<code>from django.conf.urls import include,url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',include('powerlineapp.urls')),

]
</code>```

nginx.conf

```<code>user www-data www-data;
pid /var/run/nginx.pid;
worker_processes 1;
worker_rlimit_nofile 100000;

events {
    worker_connections  4096;
    include /etc/nginx.custom.events.d/*.conf;
}

http {
    default_type application/octet-stream;

    access_log off;
    error_log  /var/log/nginx/error.log crit;

    sendfile on;
    tcp_nopush on;

    keepalive_timeout 20;
    client_header_timeout 20;
    client_body_timeout 20;
    reset_timedout_connection on;
    send_timeout 20;

    types_hash_max_size 2048;

    gzip on;
    gzip_disable "msie6";
    gzip_proxied any;
    gzip_min_length 256;
    gzip_comp_level 4;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;

    server_names_hash_bucket_size 128;

    include mime.conf;
    charset UTF-8;

    open_file_cache max=100000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    server_tokens off;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    include proxy.conf;
    include fcgi.conf;

    include conf.d/*.conf;
    include /etc/nginx.custom.d/*.conf;
}

include /etc/nginx.custom.global.d/*.conf;
</code>```

my site conf file

```<code>server {
    listen *:80;

    server_name powerlineagencies.co.ke;

    access_log /var/log/nginx/powerline-agencies.access.log;
    error_log /var/log/nginx/powerline-agencies.error.log;

    root /var/www/powerline/powerlineproject;
    index index.html index.htm index.php;

    location  / {

        proxy_pass http://unix:/var/run/ajenti-v-gunicorn-powerline-agencies-python-wsgi-0.sock;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    }

    location ~ /static/.* {
        alias /var/www/powerline/powerlineproject;

    }
</code>```

}

here is my directories structure

screenshot of my directory structure

Can someone please help me solve this problem?

答:
```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

in ngix

```<code>location /static/ {

            alias /var/www/powerline/powerlineproject/static/;
         }
</code>```

add this lines to urls.py and collectstatic and then check

Body:
I'm trying to deploy a django website on a ubuntu 14.04 vps using nginx and gunicorn but my css files and js files are not getting loaded.i developed it on the default django development server and it worked very well, but when i deploy my site and collectstatic and try to access it through the browser only the HTML text gets loaded and on checking on my browser console i find 301 and 403 forbidden errors on my static folder. i a newbie to ubuntu and django as well and all the threads and forums i've found online simply point to permissions and ownership of files and haven't had any luck when i correct my permissions.

screenshot of my browser error when i try to access django admin

here is my settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['mysite.com','www.mysite.com']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'powerlineapp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'powerlineproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'powerlineproject.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

if not DEBUG:
    STATIC_ROOT = '/var/www/powerline/powerlineproject/static/'

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

here is my main urls.py

from django.conf.urls import include,url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',include('powerlineapp.urls')),

]

nginx.conf

user www-data www-data;
pid /var/run/nginx.pid;
worker_processes 1;
worker_rlimit_nofile 100000;

events {
    worker_connections  4096;
    include /etc/nginx.custom.events.d/*.conf;
}

http {
    default_type application/octet-stream;

    access_log off;
    error_log  /var/log/nginx/error.log crit;

    sendfile on;
    tcp_nopush on;

    keepalive_timeout 20;
    client_header_timeout 20;
    client_body_timeout 20;
    reset_timedout_connection on;
    send_timeout 20;

    types_hash_max_size 2048;

    gzip on;
    gzip_disable "msie6";
    gzip_proxied any;
    gzip_min_length 256;
    gzip_comp_level 4;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;

    server_names_hash_bucket_size 128;

    include mime.conf;
    charset UTF-8;

    open_file_cache max=100000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    server_tokens off;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    include proxy.conf;
    include fcgi.conf;

    include conf.d/*.conf;
    include /etc/nginx.custom.d/*.conf;
}

include /etc/nginx.custom.global.d/*.conf;

my site conf file

server {
    listen *:80;

    server_name powerlineagencies.co.ke;

    access_log /var/log/nginx/powerline-agencies.access.log;
    error_log /var/log/nginx/powerline-agencies.error.log;

    root /var/www/powerline/powerlineproject;
    index index.html index.htm index.php;

    location  / {

        proxy_pass http://unix:/var/run/ajenti-v-gunicorn-powerline-agencies-python-wsgi-0.sock;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    }

    location ~ /static/.* {
        alias /var/www/powerline/powerlineproject;

    }

}

here is my directories structure

screenshot of my directory structure

Can someone please help me solve this problem?

Body:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

in ngix

location /static/ {

            alias /var/www/powerline/powerlineproject/static/;
         }

add this lines to urls.py and collectstatic and then check


问:
Android Internet connectivity check better method
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

答:
ConnectivityManager will not be able to tell you if you have active connection on WIFI.

The only option to check if we have active Internet connection is to ping the URL. But you don't need to do that with every HTTP request you made from your App.

What you can do:

Use below code to check connectivity

```<code>private boolean checkInternetConnection()
{
    ConnectivityManager cm = (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null
        && cm.getActiveNetworkInfo().isAvailable()
        && cm.getActiveNetworkInfo().isConnected())
    {
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

And while making rest call using HTTP client set timeout like 10 seconds. If you don't get response in 10 seconds means you donot have active internet connection and exception will be thrown (Mostly you get response within 10 seconds). No need to check active connection by pinging everytime (if you are not making Chat or VOIP app)

Body:
ConnectivityManager will not be able to tell you if you have active connection on WIFI.

The only option to check if we have active Internet connection is to ping the URL. But you don't need to do that with every HTTP request you made from your App.

What you can do:

Use below code to check connectivity

private boolean checkInternetConnection()
{
    ConnectivityManager cm = (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null
        && cm.getActiveNetworkInfo().isAvailable()
        && cm.getActiveNetworkInfo().isConnected())
    {
        return true;
    }
    else
    {
        return false;
    }
}

And while making rest call using HTTP client set timeout like 10 seconds. If you don't get response in 10 seconds means you donot have active internet connection and exception will be thrown (Mostly you get response within 10 seconds). No need to check active connection by pinging everytime (if you are not making Chat or VOIP app)


问:
Opening a specific Excel instance in VBA
Hope somebody knows how to do this, i'm none too good with VBA.

I have Excel 2016 (64bit) and Excel 2010 (32bit) installed on my machine. This is because i have some older excel based tools that only function in 2010.
One of these tools contains the following code:

```<code>Start:

            ThisWorkbook.Activate
            strOutputsFilePath = gStrOutputsPath
            strDMfilename = [DMFilePath]

   '2. Refresh the PowerPivot model with the new data

            'Create a new instance of excel
            Application.StatusBar = "Opening a new instance of MS Excel"

            Set appExcelApp = New Excel.Application

            'Disconnect and Re-connect to the PowerPivot Add-in (in case it has been disconnected)

            For Each comAddin In appExcelApp.COMAddIns

                If comAddin.Description = "PowerPivot for Excel" Then
                        Set comAddinPPVT = comAddin
                End If

            Next

            If Not comAddinPPVT Is Nothing Then

                comAddinPPVT.Connect = False
                comAddinPPVT.Connect = True

            End If

            'Apply the settings for the Excel application

            With appExcelApp
                    .Visible = False
                    .ScreenUpdating = False
                    .DisplayAlerts = False
                    .EnableEvents = False
            End With
</code>```

What the app is supposed to do is run a new instance of Excel 2010 and open certain files in it.
However, after installing 2016, the New Excel.Application command defaults to opening Excel 2016 instead of 2010. This produces an error with the PowerPivot addin because of incompatibility between data models.

Question is: Is there a way to specify in the VBA code that i want an instance of Excel 2010?

Tried to make Excel 2010 default on my system however the code still opens 2016 and errors out :\

Any help is greatly appreciated!

Thanks

答:
There is no easy fix for this. Using two different versions and two different bit-ness varieties of Excel on one computer is not recommended or supported. It's rather unusual, so there is no out of the box fix.

My advice is if you don't want Excel 2016 (64 bit) to interfere with your Excel 2013 (32 bit) stuff, don't install the two versions on the same computer.

Consider using a Virtual Machine (VM) to run one version and keep the other version on the main machine. That will ensure that they don't interfere.

Body:
Hope somebody knows how to do this, i'm none too good with VBA.

I have Excel 2016 (64bit) and Excel 2010 (32bit) installed on my machine. This is because i have some older excel based tools that only function in 2010.
One of these tools contains the following code:

Start:

            ThisWorkbook.Activate
            strOutputsFilePath = gStrOutputsPath
            strDMfilename = [DMFilePath]

   '2. Refresh the PowerPivot model with the new data

            'Create a new instance of excel
            Application.StatusBar = "Opening a new instance of MS Excel"

            Set appExcelApp = New Excel.Application

            'Disconnect and Re-connect to the PowerPivot Add-in (in case it has been disconnected)

            For Each comAddin In appExcelApp.COMAddIns

                If comAddin.Description = "PowerPivot for Excel" Then
                        Set comAddinPPVT = comAddin
                End If

            Next

            If Not comAddinPPVT Is Nothing Then

                comAddinPPVT.Connect = False
                comAddinPPVT.Connect = True

            End If

            'Apply the settings for the Excel application

            With appExcelApp
                    .Visible = False
                    .ScreenUpdating = False
                    .DisplayAlerts = False
                    .EnableEvents = False
            End With

What the app is supposed to do is run a new instance of Excel 2010 and open certain files in it.
However, after installing 2016, the New Excel.Application command defaults to opening Excel 2016 instead of 2010. This produces an error with the PowerPivot addin because of incompatibility between data models.

Question is: Is there a way to specify in the VBA code that i want an instance of Excel 2010?

Tried to make Excel 2010 default on my system however the code still opens 2016 and errors out :\

Any help is greatly appreciated!

Thanks


问:
Difference when casting a datetime to a decimal on different SQL servers
On two different sql servers I run the following query:

```<code> declare @myDatetime as datetime = '2017-07-04 23:42:32.400'
 select CAST(@myDatetime AS DECIMAL(20,5))
</code>```

I get two different results:
42918.98788 and 42918.98787

If I cast to a DECIMAL(20,6) it works fine (42918.987875) but let's say I need to put it in a decimal(20,5).

Where can I found the source of this difference in behaviour when rounding? Is it an option somewhere that rounds the final 5 up or down? Is it a sort of locale, international setting, collation or else?
Is it the different verions of SQL (12.0.5000.0 vs 13.0.4202.2)?

答:
According to this document:
https://support.microsoft.com/en-us/help/4010261/sql-server-2016-improvements-in-handling-some-data-types-and-uncommon

Microsoft have made some changes to how it handles some "uncommon" conversions:

```<code>SQL Server 2016 includes improvements to the precision of the following operations under compatibility level 130:

    Uncommon data type conversions. These include the following:
        float/integer to/from datetime/smalldatetime
        real/float to/from numeric/money/smallmoney
        float to real
</code>```

So I would suspect that might be what we see for the different rounding, in this specific situation.

Body:
On two different sql servers I run the following query:

 declare @myDatetime as datetime = '2017-07-04 23:42:32.400'
 select CAST(@myDatetime AS DECIMAL(20,5))

I get two different results:
42918.98788 and 42918.98787

If I cast to a DECIMAL(20,6) it works fine (42918.987875) but let's say I need to put it in a decimal(20,5).

Where can I found the source of this difference in behaviour when rounding? Is it an option somewhere that rounds the final 5 up or down? Is it a sort of locale, international setting, collation or else?
Is it the different verions of SQL (12.0.5000.0 vs 13.0.4202.2)?

Body:
According to this document:
https://support.microsoft.com/en-us/help/4010261/sql-server-2016-improvements-in-handling-some-data-types-and-uncommon

Microsoft have made some changes to how it handles some "uncommon" conversions:

SQL Server 2016 includes improvements to the precision of the following operations under compatibility level 130:

    Uncommon data type conversions. These include the following:
        float/integer to/from datetime/smalldatetime
        real/float to/from numeric/money/smallmoney
        float to real

So I would suspect that might be what we see for the different rounding, in this specific situation.


问:
Converting SVG image from Url to PNG in C#
I am converting svg image to png format. I am getting image from url. I am getting exception Parameter is not valid. Following is my code:

```<code>string svgFileName = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Chicago_Cubs_Logo.svg";
using (WebClient webClient = new WebClient())
{
    byte[] data = webClient.DownloadData(svgFileName);

    ImageConverter imageConverter = new System.Drawing.ImageConverter();
    Image image = imageConverter.ConvertFrom(data) as Image;
    image.Save("c:\\hello", ImageFormat.Png);
}
</code>```

I am getting the following exception:

Following is my StackTrace:

```<code>at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
at System.Drawing.ImageConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFrom(Object value)
</code>```

What am I missing?

答:
SVG is file not a plain image, you need to download svg as a file not a image.

```<code>string svgFileName = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Chicago_Cubs_Logo.svg";
using (WebClient webClient = new WebClient())
{
   webClient.DownloadFile(svgFileName, "hello.svg");
}
</code>```

Once you download the file you need to convert this svg file into image, for that you can use SVG Nuget Gallery.

you can visit this links for svg file conversion.
https://stackoverflow.com/a/58912/2745294
https://stackoverflow.com/a/12884409/2745294

Body:
I am converting svg image to png format. I am getting image from url. I am getting exception Parameter is not valid. Following is my code:

string svgFileName = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Chicago_Cubs_Logo.svg";
using (WebClient webClient = new WebClient())
{
    byte[] data = webClient.DownloadData(svgFileName);

    ImageConverter imageConverter = new System.Drawing.ImageConverter();
    Image image = imageConverter.ConvertFrom(data) as Image;
    image.Save("c:\\hello", ImageFormat.Png);
}

I am getting the following exception:

Following is my StackTrace:

at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
at System.Drawing.ImageConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFrom(Object value)

What am I missing?

Body:
SVG is file not a plain image, you need to download svg as a file not a image.

string svgFileName = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Chicago_Cubs_Logo.svg";
using (WebClient webClient = new WebClient())
{
   webClient.DownloadFile(svgFileName, "hello.svg");
}

Once you download the file you need to convert this svg file into image, for that you can use SVG Nuget Gallery.

you can visit this links for svg file conversion.
https://stackoverflow.com/a/58912/2745294
https://stackoverflow.com/a/12884409/2745294


问:
how to put a text field on top of google maps iOS
My goal is to put a text field on top of google maps iOS but seems like it doesn't work

When I run the app, the text field doesn't exist on top of Google Maps

The code

```<code>import UIKit
import GoogleMaps

class ViewController: UIViewController {

    @IBOutlet var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

答:
Here is the super easy solution to do the same with storyboard.

Add Constraints

Note : if you have issues to view GIF, please download and separate frame

Output

<img src="https://i.stack.imgur.com/SdMin.png" alt="enter image description here">

Body:
My goal is to put a text field on top of google maps iOS but seems like it doesn't work

When I run the app, the text field doesn't exist on top of Google Maps

The code

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    @IBOutlet var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}