答:
If i understood well you want only the record from Prices which has the minimum max_pers value.If so you can first find the minimum max person which is above the minimum,for each house_id and corresponding dates,  and then JOIN.Something like this should do it

```<code> SELECT h.id AS house_id, p.price, p.add_per_pers
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
       INNER JOIN prices p
       ON h.id = p.house_id
       INNER JOIN (
                  SELECT MIN(max_pers) AS max_pers
                  FROM `Prices` WHERE  from_date = '2017-07-08'
                  AND to_date = '2017-07-14' AND max_pers>=6
                  GROUP BY house_id) temp
      ON p.`max_pers` = temp.`max_pers`
      WHERE h.max_pers >= 6
      AND (a.from_date <= '2017-07-08'
      AND a.to_date >= '2017-07-14')
      AND p.from_date = '2017-07-08'
      AND p.to_date = '2017-07-14'
      AND p.max_pers >= 6
</code>```

Title: SQL JOIN three tables, one with LIMIT 1

Body:
I am working on a project for rental houses in MySQL. In a simplified view I have three tables. One holding the house data, one having the availability, the third one holding the prices.

The prices are the tricky part here as there may be different prices for different amount of people. E.g. renting house 1 (Blue house) with up to four persons is cheaper than with between 5 and 10 persons. Next to the price for the house, there often is an additional price per person.

Houses table:

+----+--------------+----------+
| id | name         | max_pers |
+----+--------------+----------+
|  1 | Blue house   |       10 |
|  2 | Red house    |        8 |
|  3 | Yellow house |        8 |
|  4 | Grey house   |        4 |
+----+--------------+----------+

Availability table:

+----+----------+------------+------------+
| id | house_id | from_date  | to_date    |
+----+----------+------------+------------+
|  1 |        1 | 2017-07-01 | 2017-07-14 |
|  2 |        1 | 2017-08-05 | 2017-08-19 |
|  3 |        2 | 2017-09-02 | 2017-09-16 |
|  4 |        3 | 2017-07-08 | 2017-07-14 |
|  5 |        4 | 2017-08-05 | 2017-08-12 |
|  6 |        4 | 2017-08-26 | 2017-09-02 |
+----+----------+------------+------------+

Prices table:

+----+----------+------------+------------+----------+--------+--------------+
| id | house_id | from_date  | to_date    | max_pers | price  | add_per_pers |
+----+----------+------------+------------+----------+--------+--------------+
|  1 |        1 | 2017-07-01 | 2017-07-08 |        4 | 110.00 |        15.00 |
|  2 |        1 | 2017-07-01 | 2017-07-08 |       10 | 140.00 |        10.00 |
|  3 |        1 | 2017-07-08 | 2017-07-14 |        4 | 120.00 |        15.00 |
|  4 |        1 | 2017-07-08 | 2017-07-14 |       10 | 150.00 |        10.00 |
|  5 |        1 | 2017-08-05 | 2017-08-12 |        4 | 130.00 |        20.00 |
|  6 |        1 | 2017-08-12 | 2017-08-19 |       10 | 180.00 |        15.00 |
|  7 |        2 | 2017-09-02 | 2017-09-09 |        8 | 210.00 |        30.00 |
|  8 |        2 | 2017-09-09 | 2017-09-16 |        8 | 220.00 |        30.00 |
|  9 |        3 | 2017-07-08 | 2017-07-14 |        6 | 300.00 |        40.00 |
| 10 |        3 | 2017-07-08 | 2017-07-14 |        8 | 360.00 |        50.00 |
| 11 |        4 | 2017-08-05 | 2017-08-12 |        4 |  80.00 |         null |
| 12 |        4 | 2018-08-26 | 2017-09-02 |        4 |  90.00 |         null |
+----+----------+------------+------------+----------+--------+--------------+

SQL dump of this test database can be downloaded here.

The goal

The query that I am trying to compose, should select houses where persons <= max_pers and where the house is available, then grab the ONE price from the prices table that has the lowest amount of allowed max_pers. E.g. when looking up the price for house 1 (Blue house) for 4 persons in the week of 2017-07-01, it should give 110 as the price. The query should return the house id, the price and the additional cost per person.

My efforts

I got as far as returning the house id and the price, grabbing only the correct price.

SELECT h.id AS house_id,
       (SELECT price
           FROM prices AS p
          WHERE p.house_id = h.id
            AND p.from_date = '2017-07-08'
            AND p.to_date = '2017-07-14'
            AND p.max_pers >= 6
         ORDER BY p.max_pers
         LIMIT 1) AS price
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
 WHERE h.max_pers >= 6
   AND (a.from_date <= '2017-07-08'
       AND a.to_date >= '2017-07-14');

Which returns:

+----------+--------+
| house_id | price  |
+----------+--------+
|        1 | 150.00 |
|        3 | 360.00 |
+----------+--------+

So that works, but... I am stuck now on how to add the add_per_pers column from the prices table. I tried to add a JOIN instead of a select ... as. That way I can add the field, but then I cannot limit the data from prices to just the first one.

My best try:

SELECT h.id AS house_id, p.price, p.add_per_pers
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
       INNER JOIN prices p
       ON h.id = p.house_id
 WHERE h.max_pers >= 6
   AND (a.from_date <= '2017-07-08'
       AND a.to_date >= '2017-07-14')
   AND p.from_date = '2017-07-08'
   AND p.to_date = '2017-07-14'
   AND p.max_pers >= 6;

Results in (the third row should not be there)

+----------+--------+--------------+
| house_id | price  | add_per_pers |
+----------+--------+--------------+
|        1 | 150.00 |        10.00 |
|        3 | 300.00 |        40.00 |
|        3 | 360.00 |        50.00 |
+----------+--------+--------------+

Desired result

Please help me to get this desired result:

+----------+--------+--------------+
| house_id | price  | add_per_pers |
+----------+--------+--------------+
|        1 | 150.00 |        10.00 |
|        3 | 360.00 |        40.00 |
+----------+--------+--------------+

SQL Fiddle available here

Body:
If i understood well you want only the record from Prices which has the minimum max_pers value.If so you can first find the minimum max person which is above the minimum,for each house_id and corresponding dates,  and then JOIN.Something like this should do it

 SELECT h.id AS house_id, p.price, p.add_per_pers
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
       INNER JOIN prices p
       ON h.id = p.house_id
       INNER JOIN (
                  SELECT MIN(max_pers) AS max_pers
                  FROM `Prices` WHERE  from_date = '2017-07-08'
                  AND to_date = '2017-07-14' AND max_pers>=6
                  GROUP BY house_id) temp
      ON p.`max_pers` = temp.`max_pers`
      WHERE h.max_pers >= 6
      AND (a.from_date <= '2017-07-08'
      AND a.to_date >= '2017-07-14')
      AND p.from_date = '2017-07-08'
      AND p.to_date = '2017-07-14'
      AND p.max_pers >= 6


来源: stackexchange

问:
Regex to get string inside apostrophe in wider string
I have this string:

```<code>$config['website'] = 'Devloooo';
</code>```

And I need to get only the Devloooo (without apostrophes).

Only this text inside apostrophes.

I'm searching and looking for other regex on net and trying by http://regexr.com/ by I can't figure out how it should look like

All I got for now is \$config\['website'] = '(.*?)';

答:
Regex would be \].*'(.*)'

Here is your program to find it

```<code>    Matcher m = (Pattern.compile("\\].*'(.*)'")).matcher("$config['website'] = 'Devloooo';");
    while(m.find()) {
        System.out.println(m.group(1));
    }
</code>```

Console output:

```<code>Devloooo
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this string:

$config['website'] = 'Devloooo';

And I need to get only the Devloooo (without apostrophes).

Only this text inside apostrophes.

I'm searching and looking for other regex on net and trying by http://regexr.com/ by I can't figure out how it should look like

All I got for now is \$config\['website'] = '(.*?)';

Body:
Regex would be \].*'(.*)'

Here is your program to find it

    Matcher m = (Pattern.compile("\\].*'(.*)'")).matcher("$config['website'] = 'Devloooo';");
    while(m.find()) {
        System.out.println(m.group(1));
    }

Console output:

Devloooo


问:
cucumber.runtime.CucumberException: Couldn't load plugin class: com.CustomHtmlFormatter
I am new to cucumber parallel execution. I need to do the parallel execution of cucumber TestCases  with cucumber plugin "cucumber-jvm-parallel-plugin".
When I run a pom.xml file It throws an error. Please let me know my mistake.

```<code>[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.127 s <<< FAILURE! - in TestRunner.Parallel01IT
[ERROR] initializationError(TestRunner.Parallel01IT)  Time elapsed: 0.009 s  <<< ERROR!
cucumber.runtime.CucumberException: Couldn't load plugin class: com.project.CustomHtmlFormatter
Caused by: java.lang.ClassNotFoundException: com.project.CustomHtmlFormatter
</code>```

Below are the project structure.

POM.xml file

```<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.project</groupId>
    <artifactId>Steps</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
    .....
    </dependencies>
    <build>
        <!-- COPY RESOURCES TO TARGET/ -->

            <resource>
                <directory>../../Cucumber5/src/test/resources/features</directory>

            </resource>
        </resources>
        <!-- RUN EACH CUCUMBER FEATURE FILE AS A FORK -->
        <plugins>
            <plugin>
                <groupId>com.github.temyers</groupId>
                <artifactId>cucumber-jvm-parallel-plugin</artifactId>
                <version>4.1.0</version>
                <executions>
                    <execution>
                        <id>generateRunners</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>generateRunners</goal>
                        </goals>
                        <configuration>

                            <glue>
                                <package>com.project.Steps</package>
                            </glue>

                            <outputDirectory>../../Cucumber5/src/target/generatedTestSources/</outputDirectory>
                        <featuresDirectory>../../Cucumber5/src/target/classes/</featuresDirectory>
                        <cucumberOutputDir>../../Cucumber5/src/target</cucumberOutputDir>

                            <plugins>
                                <plugin>
                                    <name>json</name>
                                </plugin>
                                <plugin>
                                    <name>com.project.CustomHtmlFormatter</name>
                                    <extension>html</extension>
                                </plugin>
                            </plugins>
                            <!-- CucumberOptions.strict property -->
                            <strict>true</strict>

                            <monochrome>true</monochrome>

                            <useTestNG>false</useTestNG>
                            <namingScheme>pattern</namingScheme>
                            <namingPattern>Parallel{c}IT</namingPattern>
                            <parallelScheme>FEATURE</parallelScheme>

                            <!-- Specify a custom package name for generated sources. Default
                                is no package. -->
                            <packageName>TestRunner</packageName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

               <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
<!-- RUN ALL CLASSES CREATED BY cucumber-jvm-parallel-plugin IN PARALLEL -->
        <executions>
         <execution>
             <id>acceptance-test</id>
             <phase>integration-test</phase>
             <goals>
                 <goal>test</goal>
             </goals>
             <configuration>
                 <forkCount>5</forkCount>
                 <reuseForks>true</reuseForks>
                 <includes>
                    <include>**/Parallel*IT.class</include>
                 </includes>
             </configuration>
        </execution>
        </executions>
         </plugin>

        </plugins>
    </build>
</project>
</code>```

After running the pom.xml file below Parallel01IT.java file

generated.

```<code>package TestRunner;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        strict = true,
        features = {"E:/workspaceTAAP/Cucumber5/src/target/classes/tester.feature"},
        plugin = {"json:E:/workspaceTAAP/Cucumber5/src/target/1.json", "com.project.CustomHtmlFormatter:E:/workspaceTAAP/Cucumber5/src/target/1.html"},
        monochrome = true,
        tags = {},
        glue = {"com.project.Steps"})
public class Parallel01IT {
}
</code>```

答: error occurring because class CustomHtmlFormatter is not into com.project package. and package com.project is not present into you project. create the proper package and classes first.

Body:
I am new to cucumber parallel execution. I need to do the parallel execution of cucumber TestCases  with cucumber plugin "cucumber-jvm-parallel-plugin".
When I run a pom.xml file It throws an error. Please let me know my mistake.

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.127 s <<< FAILURE! - in TestRunner.Parallel01IT
[ERROR] initializationError(TestRunner.Parallel01IT)  Time elapsed: 0.009 s  <<< ERROR!
cucumber.runtime.CucumberException: Couldn't load plugin class: com.project.CustomHtmlFormatter
Caused by: java.lang.ClassNotFoundException: com.project.CustomHtmlFormatter

Below are the project structure.

POM.xml file

<?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.project</groupId>
    <artifactId>Steps</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
    .....
    </dependencies>
    <build>

            <resource>
                <directory>../../Cucumber5/src/test/resources/features</directory>

            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>com.github.temyers</groupId>
                <artifactId>cucumber-jvm-parallel-plugin</artifactId>
                <version>4.1.0</version>
                <executions>
                    <execution>
                        <id>generateRunners</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>generateRunners</goal>
                        </goals>
                        <configuration>

                            <glue>
                                <package>com.project.Steps</package>
                            </glue>

                            <outputDirectory>../../Cucumber5/src/target/generatedTestSources/</outputDirectory>
                        <featuresDirectory>../../Cucumber5/src/target/classes/</featuresDirectory>
                        <cucumberOutputDir>../../Cucumber5/src/target</cucumberOutputDir>

                            <plugins>
                                <plugin>
                                    <name>json</name>
                                </plugin>
                                <plugin>
                                    <name>com.project.CustomHtmlFormatter</name>
                                    <extension>html</extension>
                                </plugin>
                            </plugins>

                            <strict>true</strict>

                            <monochrome>true</monochrome>

                            <useTestNG>false</useTestNG>
                            <namingScheme>pattern</namingScheme>
                            <namingPattern>Parallel{c}IT</namingPattern>
                            <parallelScheme>FEATURE</parallelScheme>

                            <packageName>TestRunner</packageName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

               <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>

        <executions>
         <execution>
             <id>acceptance-test</id>
             <phase>integration-test</phase>
             <goals>
                 <goal>test</goal>
             </goals>
             <configuration>
                 <forkCount>5</forkCount>
                 <reuseForks>true</reuseForks>
                 <includes>
                    <include>**/Parallel*IT.class</include>
                 </includes>
             </configuration>
        </execution>
        </executions>
         </plugin>

        </plugins>
    </build>
</project>

After running the pom.xml file below Parallel01IT.java file

generated.

package TestRunner;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        strict = true,
        features = {"E:/workspaceTAAP/Cucumber5/src/target/classes/tester.feature"},
        plugin = {"json:E:/workspaceTAAP/Cucumber5/src/target/1.json", "com.project.CustomHtmlFormatter:E:/workspaceTAAP/Cucumber5/src/target/1.html"},
        monochrome = true,
        tags = {},
        glue = {"com.project.Steps"})
public class Parallel01IT {
}


问:
SQL - all patients who had only dental visits in 2010
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

```<code>AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )
</code>```

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)

答:
The clue is to use where not exists</p>

```<code>AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName LIKE '%Dental%'
    )
and not exists ( Select 1 from   PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)

Body:
The clue is to use where not exists

AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName LIKE '%Dental%'
    )
and not exists ( Select 1 from   PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )


问:
Store objects of different types in a container
I have two objects QColor, QFont and there's a possibility of adding more.

I want to store that objects in a container for instance QList but this container needs one type of data.

```<code>QFont font = QFontDialog::getFont(&fontDlgRet, initFont, parent);
QColor color = QColorDialog::getColor(initColor, parent);
</code>```

Is there a container accepts adding different types of objects?

答:
Is there a container accepts adding different types of objects?

Yes: QVariantList, QVariantMap, QVariantHash.

You can also roll your own manually, like std::vector<QVariant> for instance.

See http://doc.qt.io/qt-5/qvariant.html

Also, note that loosing type information like this is frowned upon and bad practice. If you have a finite set of types you can use std::variant instead.

Body:
I have two objects QColor, QFont and there's a possibility of adding more.

I want to store that objects in a container for instance QList but this container needs one type of data.

QFont font = QFontDialog::getFont(&fontDlgRet, initFont, parent);
QColor color = QColorDialog::getColor(initColor, parent);

Is there a container accepts adding different types of objects?


问:
specify .so files in build.gradle file android studio
This is my Directory Structure

```<code>src -main

    -java

    -jniLibs

            -armeabi

                     -lib1.so
                     -lib2.so
</code>```

Need to understand what piece of code should be written in build gradle file for these files to be included in the build.
Right now, i am getting the error of not finding the .so file.

```<code>  java.lang.UnsatisfiedLinkError: nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libFPEComponent.so"
</code>```

Following solution by H.Brooks

I have got to add here

My Git repository:

My bUild.gradle file

```<code> apply plugin: 'com.android.application'

android {
    productFlavors {
        arm {
            ndk {
                abiFilters "armeabi-v7a", "armeabi"
            }
        }

    }

    sourceSets
            {
                main
                        {

                            jniLibs.srcDirs = ['src/main/jnilibs']

                        }

//Another code

            }

    compileSdkVersion 26
    buildToolsVersion '26.0.0'
    defaultConfig {
        applicationId "com.goambee.biometricziqitza"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }
    splits {

        // Configures multiple APKs based on ABI.
        abi {

            // Enables building multiple APKs per ABI.
            enable true

            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86, armeabi-v7a, and mips.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "armeabi-v7a"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk false
        }
    }
}

dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')
//    compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
}

//task native-libstiveLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
//    destinationDir file("$buildDir/native-libs")
//    baseName 'native-libs'
//    from fileTree(dir: 'src/main/jnilibs', include: '**/*.so')
//    into 'lib/'
//}
//
//tasks.withType(JavaCompile)
//        {
//            compileTask -> compileTask.dependsOn(nativeLibsToJar)
//        }
</code>```

Here i have included source set block, i also had tested without that block.
So still build isn't able to access .so files.

答:
If you want to use it you can call it in your class like this:

```<code>static {
    System.loadLibrary("libSONAME");
}
</code>```

Add the following in your gradle:

```<code>jniLibs.srcDirs = ['libs']
</code>```

Edit:

Adding .so Library in Android Studio

Create Folder "jniLibs" inside "src/main/"

Put all your .so libraries inside "src/main/jniLibs" folder

Folder structure looks like,

|--app:

|--|--src:

|--|--|--main

|--|--|--|--jniLibs

|--|--|--|--|--armeabi

|--|--|--|--|--|--.so Files

|--|--|--|--|--x86

|--|--|--|--|--|--.so Files

No extra code requires just sync your project and run your
application.

Reference

https://github.com/commonsguy/sqlcipher-gradle/tree/master/src/main

Not sure what files you exactly have, if you only have .so?

Have a look at the image below:

This is a 'project/library' within my project and this is how the load the .so files get loaded/added:

I compile the project like this:

```<code>compile project(':videokit')
</code>```

Body:
This is my Directory Structure

src -main

    -java

    -jniLibs

            -armeabi

                     -lib1.so
                     -lib2.so

Need to understand what piece of code should be written in build gradle file for these files to be included in the build.
Right now, i am getting the error of not finding the .so file.

  java.lang.UnsatisfiedLinkError: nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libFPEComponent.so"

Following solution by H.Brooks

I have got to add here

My Git repository:

My bUild.gradle file

 apply plugin: 'com.android.application'

android {
    productFlavors {
        arm {
            ndk {
                abiFilters "armeabi-v7a", "armeabi"
            }
        }

    }

    sourceSets
            {
                main
                        {

                            jniLibs.srcDirs = ['src/main/jnilibs']

                        }

//Another code

            }

    compileSdkVersion 26
    buildToolsVersion '26.0.0'
    defaultConfig {
        applicationId "com.goambee.biometricziqitza"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }
    splits {

        // Configures multiple APKs based on ABI.
        abi {

            // Enables building multiple APKs per ABI.
            enable true

            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86, armeabi-v7a, and mips.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "armeabi-v7a"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk false
        }
    }
}

dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')
//    compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
}

//task native-libstiveLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
//    destinationDir file("$buildDir/native-libs")
//    baseName 'native-libs'
//    from fileTree(dir: 'src/main/jnilibs', include: '**/*.so')
//    into 'lib/'
//}
//
//tasks.withType(JavaCompile)
//        {
//            compileTask -> compileTask.dependsOn(nativeLibsToJar)
//        }

Here i have included source set block, i also had tested without that block.
So still build isn't able to access .so files.

Body:
If you want to use it you can call it in your class like this:

static {
    System.loadLibrary("libSONAME");
}

Add the following in your gradle:

jniLibs.srcDirs = ['libs']

Edit:

Adding .so Library in Android Studio

Create Folder "jniLibs" inside "src/main/"

Put all your .so libraries inside "src/main/jniLibs" folder

Folder structure looks like,

|--app:

|--|--src:

|--|--|--main

|--|--|--|--jniLibs

|--|--|--|--|--armeabi

|--|--|--|--|--|--.so Files

|--|--|--|--|--x86

|--|--|--|--|--|--.so Files

No extra code requires just sync your project and run your
application.

Reference

https://github.com/commonsguy/sqlcipher-gradle/tree/master/src/main

Not sure what files you exactly have, if you only have .so?

Have a look at the image below:

This is a 'project/library' within my project and this is how the load the .so files get loaded/added:

I compile the project like this:

compile project(':videokit')


问:
<meta charset=“utf-8”> or <meta http-equiv=“Content-Type”>, which should I use?
In order to define charset for HTML 5 doctype, which notation should I use?

Short:

```<code>meta charset="utf-8"
</code>```

Long:

```<code>meta http-equiv="Content-Type" content="text/html; charset=utf-8"
</code>```

答:
See the section Specifying the document’s character encoding in the HTML 5.1 spec:

[…] using a meta element with a charset attribute or a meta element with an http-equiv attribute in the encoding declaration state.

So both ways are fine. (But don’t use both in the same document.)

Body:
In order to define charset for HTML 5 doctype, which notation should I use?

Short:

meta charset="utf-8"

Long:

meta http-equiv="Content-Type" content="text/html; charset=utf-8"


问:
Are string literals const?
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

```<code>char *foo = "bar";
</code>```

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?

答:
Johannes' answer is correct concerning the type and contents. But in addition to that, yes, it is undefined behavior to modify contents of a string literal.

Concerning your question about argv:

The parameters argc and argv and the
  strings pointed to by the argv array
  shall be modifiable by the program,
  and retain their last-stored values
  between program startup and program
  termination.

Title: Are string literals const?

Body:
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

char *foo = "bar";

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?


问:
Symfony 3.3.2 Doctrine EntityRepository constructor argument
I'm newbie on Symfony. I am trying to update an old project under symfony 2.6 to symfony 3.3.

After multiple bug fixes I am stuck on a point: I have an Error in my EntityRepository.php file with the constructor.

```<code>Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 1 passed in /Users/.../var/cache/dev/appDevDebugProjectContainer.php on line 3434 and exactly 2 expected
</code>```

I understand the error, but my EntityRepository file not contain any __construct method. Should I fix something between Symfony 2 and 3 for the consructor to work?

Thanks a lot.

Here is my MilestoneRepository.php file:

```<code>namespace MilestonesBundle\Entity\Repository;

use DateTime;

use Doctrine\ORM\EntityRepository;

use Milestones\Entity\Factory\MilestoneFactoryInterface;
use Milestones\Entity\Repository\MilestoneRepositoryInterface;

class MilestoneRepository extends EntityRepository implements MilestoneFactoryInterface, MilestoneRepositoryInterface
{
    protected $current = false;

    /**
     * @see MilestoneFactoryInterface
     */
    public function create()
    {
        $class = $this->getClassName();

        return new $class;
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        if (!$orderBy) {
            $orderBy['startsAt'] = 'ASC';
        }

        return parent::findBy($criteria, $orderBy, $limit, $offset);
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function findCurrent()
    {
        $now = new DateTime;

        if ($this->current === false) {
            $this->current = $this->createQueryBuilder('m')
                ->where('m.startsAt <= :now')
                ->andWhere('(m.endsAt IS NULL OR :now < m.endsAt)')
                ->setParameter('now', $now->format('Y-m-d'))
                ->orderBy('m.startsAt', 'ASC')
                ->setMaxResults(1)
                ->getQuery()
                ->getOneOrNullResult()
            ;
        }

        return $this->current;
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function isOpen()
    {
        $current = $this->findCurrent();

        return $current && $current->isStart();
    }
}
</code>```

And here is my EntityRepository.php file:

```<code>namespace Common\Doctrine\ORM;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;

class EntityRepository extends BaseEntityRepository
{
    protected $alias = 'x';

    public function add($entity)
    {
        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    public function remove($entity)
    {
        $em = $this->getEntityManager();
        $em->remove($entity);
        $em->flush();
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);
        $this->applyLimit($builder, $limit);
        $this->applyOffset($builder, $offset);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getResult();
    }

    public function findOneBy(array $criteria, array $orderBy = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getOneOrNullResult();
    }

    protected function applyCriteria(QueryBuilder $builder, $alias, array $criteria)
    {
        $map = $this->getCriteriaMap();

        foreach ($criteria as $property => $value) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $value]);
            } else {
                $this->applyDefaultCriterion($builder, $alias, $property, $value);
            }
        }
    }

    protected function getCriteriaMap()
    {
        return [];
    }

    protected function applyDefaultCriterion($builder, $alias, $property, $value)
    {
        if (null === $value) {
            $builder->andWhere($alias.'.'.$property.' IS NULL');
        } else {
            $parameter = 'p_' . uniqid();
            $builder->andWhere($alias.'.'.$property.' = :'.$parameter);
            $builder->setParameter($parameter, $value);
        }
    }

    /**
     * Apply order by
     *
     * @param  QueryBuilder $builder
     * @param  string       $alias
     * @param  array|null   $orderBy
     * @return void
     */
    protected function applyOrderBy(QueryBuilder $builder, $alias, array $orderBy = null)
    {
        if (empty($orderBy)) {
            $orderBy = $this->getDefaultOrder();
        }

        $map = $this->getOrderingMap();

        foreach ($orderBy as $property => $direction) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $direction]);
            } else {
                $this->applyDefaultOrder($builder, $alias, $property, $direction);
            }
        }
    }

    protected function getDefaultOrder()
    {
        return [];
    }

    protected function getOrderingMap()
    {
        return [];
    }

    protected function applyDefaultOrder(QueryBuilder $builder, $alias, $property, $direction)
    {
        $builder->orderBy($alias.'.'.$property, $direction);
    }

    protected function applyLimit(QueryBuilder $builder, $limit = null)
    {
        if ($limit) {
            $builder->setMaxResults($limit);
        }
    }

    protected function applyOffset(QueryBuilder $builder, $offset = null)
    {
        if ($offset) {
            $builder->setFirstResult($offset);
        }
    }
}
</code>```

I think I'm accessing through a service, with this:

```<code>services:

# Factories

milestones.factory.milestone:
    alias: milestones.repository.milestone
    arguments: [ MilestonesBundle\Entity\Milestone ]

# Repositories

milestones.repository.milestone:
    class: MilestonesBundle\Entity\Repository\MilestoneRepository
    factory_service: doctrine.orm.default_entity_manager
    factory_method: getRepository
    arguments: [ MilestonesBundle\Entity\Milestone ]
</code>```

答:
I think somewhere in jour code this method is called:

```<code>    public function create()
    {
        $class = $this->getClassName();

        return new $class;
    }
</code>```

And this is calling the constructor of Doctrine\ORM\EntityRepository:

```<code>        public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class)
{
    $this->_entityName = $class->name;
    $this->_em         = $em;
    $this->_class      = $class;
}
</code>```

therefore you will have to inject the arguments if you want to use your create method... I think it should be something like new $class($entityManager, Entity::class)

Body:
I'm newbie on Symfony. I am trying to update an old project under symfony 2.6 to symfony 3.3.

After multiple bug fixes I am stuck on a point: I have an Error in my EntityRepository.php file with the constructor.

Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 1 passed in /Users/.../var/cache/dev/appDevDebugProjectContainer.php on line 3434 and exactly 2 expected

I understand the error, but my EntityRepository file not contain any __construct method. Should I fix something between Symfony 2 and 3 for the consructor to work?

Thanks a lot.

Here is my MilestoneRepository.php file:

namespace MilestonesBundle\Entity\Repository;

use DateTime;

use Doctrine\ORM\EntityRepository;

use Milestones\Entity\Factory\MilestoneFactoryInterface;
use Milestones\Entity\Repository\MilestoneRepositoryInterface;

class MilestoneRepository extends EntityRepository implements MilestoneFactoryInterface, MilestoneRepositoryInterface
{
    protected $current = false;

    /**
     * @see MilestoneFactoryInterface
     */
    public function create()
    {
        $class = $this->getClassName();

        return new $class;
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        if (!$orderBy) {
            $orderBy['startsAt'] = 'ASC';
        }

        return parent::findBy($criteria, $orderBy, $limit, $offset);
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function findCurrent()
    {
        $now = new DateTime;

        if ($this->current === false) {
            $this->current = $this->createQueryBuilder('m')
                ->where('m.startsAt <= :now')
                ->andWhere('(m.endsAt IS NULL OR :now < m.endsAt)')
                ->setParameter('now', $now->format('Y-m-d'))
                ->orderBy('m.startsAt', 'ASC')
                ->setMaxResults(1)
                ->getQuery()
                ->getOneOrNullResult()
            ;
        }

        return $this->current;
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function isOpen()
    {
        $current = $this->findCurrent();

        return $current && $current->isStart();
    }
}

And here is my EntityRepository.php file:

namespace Common\Doctrine\ORM;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;

class EntityRepository extends BaseEntityRepository
{
    protected $alias = 'x';

    public function add($entity)
    {
        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    public function remove($entity)
    {
        $em = $this->getEntityManager();
        $em->remove($entity);
        $em->flush();
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);
        $this->applyLimit($builder, $limit);
        $this->applyOffset($builder, $offset);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getResult();
    }

    public function findOneBy(array $criteria, array $orderBy = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getOneOrNullResult();
    }

    protected function applyCriteria(QueryBuilder $builder, $alias, array $criteria)
    {
        $map = $this->getCriteriaMap();

        foreach ($criteria as $property => $value) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $value]);
            } else {
                $this->applyDefaultCriterion($builder, $alias, $property, $value);
            }
        }
    }

    protected function getCriteriaMap()
    {
        return [];
    }

    protected function applyDefaultCriterion($builder, $alias, $property, $value)
    {
        if (null === $value) {
            $builder->andWhere($alias.'.'.$property.' IS NULL');
        } else {
            $parameter = 'p_' . uniqid();
            $builder->andWhere($alias.'.'.$property.' = :'.$parameter);
            $builder->setParameter($parameter, $value);
        }
    }

    /**
     * Apply order by
     *
     * @param  QueryBuilder $builder
     * @param  string       $alias
     * @param  array|null   $orderBy
     * @return void
     */
    protected function applyOrderBy(QueryBuilder $builder, $alias, array $orderBy = null)
    {
        if (empty($orderBy)) {
            $orderBy = $this->getDefaultOrder();
        }

        $map = $this->getOrderingMap();

        foreach ($orderBy as $property => $direction) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $direction]);
            } else {
                $this->applyDefaultOrder($builder, $alias, $property, $direction);
            }
        }
    }

    protected function getDefaultOrder()
    {
        return [];
    }

    protected function getOrderingMap()
    {
        return [];
    }

    protected function applyDefaultOrder(QueryBuilder $builder, $alias, $property, $direction)
    {
        $builder->orderBy($alias.'.'.$property, $direction);
    }

    protected function applyLimit(QueryBuilder $builder, $limit = null)
    {
        if ($limit) {
            $builder->setMaxResults($limit);
        }
    }

    protected function applyOffset(QueryBuilder $builder, $offset = null)
    {
        if ($offset) {
            $builder->setFirstResult($offset);
        }
    }
}

I think I'm accessing through a service, with this:

services:

# Factories

milestones.factory.milestone:
    alias: milestones.repository.milestone
    arguments: [ MilestonesBundle\Entity\Milestone ]

# Repositories

milestones.repository.milestone:
    class: MilestonesBundle\Entity\Repository\MilestoneRepository
    factory_service: doctrine.orm.default_entity_manager
    factory_method: getRepository
    arguments: [ MilestonesBundle\Entity\Milestone ]

Body:
I think somewhere in jour code this method is called:

    public function create()
    {
        $class = $this->getClassName();

        return new $class;
    }

And this is calling the constructor of Doctrine\ORM\EntityRepository:

        public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class)
{
    $this->_entityName = $class->name;
    $this->_em         = $em;
    $this->_class      = $class;
}

therefore you will have to inject the arguments if you want to use your create method... I think it should be something like new $class($entityManager, Entity::class)


问:
Loading an image from ms-access to VB.net application
I know this has been frequently asked by many here, but I wouldn't have asked if I haven't tried most of the solutions given on this website.

I'm having trouble reading images of receipts from ms-access to a picturebox in vb.net.

Here's the code I currently have.

```<code>    Dim i = DataGridView1.CurrentRow.Index
    Dim Dir As String = Path.GetDirectoryName(Application.ExecutablePath) & "\"
    Dim Connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Dir & "DB1.accdb")
    Dim SQL As String = "SELECT Receipt FROM [Inventory] WHERE ID=@DID"
    Dim command As New OleDbCommand(SQL, Connection)
    command.Parameters.AddWithValue("@DID", DataGridView1.Item(0, i).Value)

    Connection.Open()
    Using oleDBCmd As OleDb.OleDbCommand = Connection.CreateCommand()
        oleDBCmd.CommandType = CommandType.Text
        oleDBCmd.CommandText = SQL
        Using oleDbReader As OleDb.OleDbDataReader = oleDBCmd.ExecuteReader()
            oleDbReader.Read()
            Dim ImageBytes As Byte() = CType(oleDbReader(0), Byte())
            Dim ms As New MemoryStream(ImageBytes)
            FormReciept.Show()
            FormReceipt.PictureBox1.Image = Image.FromStream(ms)
        End Using
    End Using
    Connection.Close()
</code>```

Based on the selected field of a specific item, it will retrieve its receipt based on the ID number, and preview it in another form where the picture box is.

Here's the error I'm getting.

```<code>An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred
in System.Data.dll
Additional information: No value given for one or more required parameters.
</code>```

Any help would be appreciated. Thank you.

答:
You are creating a command "command" with parameters, and then not using it...and instead creating a new command "oleDBCmd" which has no parameters added to it, which is the one you're actually executing. That's why you get the "No value given" error.

Try the following changes and see if you still get the error, or get a new error:

```<code>    Dim i = DataGridView1.CurrentRow.Index
    Dim Dir As String = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) & "\"
    Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Dir & "DB1.accdb")
    Dim SQL As String = "SELECT Receipt FROM [Inventory] WHERE ID=@DID"
    'Dim command As New OleDb.OleDbCommand(SQL, Connection)
    'command.Parameters.AddWithValue("@DID", DataGridView1.Item(0, i).Value)

    Connection.Open()
    Using oleDBCmd As OleDb.OleDbCommand = Connection.CreateCommand()
        oleDBCmd.CommandType = CommandType.Text
        oleDBCmd.CommandText = SQL
        'add parameter to the command you will actually be executing
        oleDBCmd.Parameters.AddWithValue("@DID", DataGridView1.Item(0, i).Value)
        Using oleDbReader As OleDb.OleDbDataReader = oleDBCmd.ExecuteReader()
            oleDbReader.Read()
            Dim ImageBytes As Byte() = CType(oleDbReader(0), Byte())
            Dim ms As New MemoryStream(ImageBytes)
            FormReciept.Show()
            FormReceipt.PictureBox1.Image = Image.FromStream(ms)
        End Using
    End Using
    Connection.Close()
</code>```

Just commented out the "command" oledb command since it doesn't get executed, and added the parameter to "oleDBCmd".

Body:
I know this has been frequently asked by many here, but I wouldn't have asked if I haven't tried most of the solutions given on this website.

I'm having trouble reading images of receipts from ms-access to a picturebox in vb.net.

Here's the code I currently have.

    Dim i = DataGridView1.CurrentRow.Index
    Dim Dir As String = Path.GetDirectoryName(Application.ExecutablePath) & "\"
    Dim Connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Dir & "DB1.accdb")
    Dim SQL As String = "SELECT Receipt FROM [Inventory] WHERE ID=@DID"
    Dim command As New OleDbCommand(SQL, Connection)
    command.Parameters.AddWithValue("@DID", DataGridView1.Item(0, i).Value)

    Connection.Open()
    Using oleDBCmd As OleDb.OleDbCommand = Connection.CreateCommand()
        oleDBCmd.CommandType = CommandType.Text
        oleDBCmd.CommandText = SQL
        Using oleDbReader As OleDb.OleDbDataReader = oleDBCmd.ExecuteReader()
            oleDbReader.Read()
            Dim ImageBytes As Byte() = CType(oleDbReader(0), Byte())
            Dim ms As New MemoryStream(ImageBytes)
            FormReciept.Show()
            FormReceipt.PictureBox1.Image = Image.FromStream(ms)
        End Using
    End Using
    Connection.Close()

Based on the selected field of a specific item, it will retrieve its receipt based on the ID number, and preview it in another form where the picture box is.

Here's the error I'm getting.

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred
in System.Data.dll
Additional information: No value given for one or more required parameters.

Any help would be appreciated. Thank you.

Body:
You are creating a command "command" with parameters, and then not using it...and instead creating a new command "oleDBCmd" which has no parameters added to it, which is the one you're actually executing. That's why you get the "No value given" error.

Try the following changes and see if you still get the error, or get a new error:

    Dim i = DataGridView1.CurrentRow.Index
    Dim Dir As String = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) & "\"
    Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Dir & "DB1.accdb")
    Dim SQL As String = "SELECT Receipt FROM [Inventory] WHERE ID=@DID"
    'Dim command As New OleDb.OleDbCommand(SQL, Connection)
    'command.Parameters.AddWithValue("@DID", DataGridView1.Item(0, i).Value)

    Connection.Open()
    Using oleDBCmd As OleDb.OleDbCommand = Connection.CreateCommand()
        oleDBCmd.CommandType = CommandType.Text
        oleDBCmd.CommandText = SQL
        'add parameter to the command you will actually be executing
        oleDBCmd.Parameters.AddWithValue("@DID", DataGridView1.Item(0, i).Value)
        Using oleDbReader As OleDb.OleDbDataReader = oleDBCmd.ExecuteReader()
            oleDbReader.Read()
            Dim ImageBytes As Byte() = CType(oleDbReader(0), Byte())
            Dim ms As New MemoryStream(ImageBytes)
            FormReciept.Show()
            FormReceipt.PictureBox1.Image = Image.FromStream(ms)
        End Using
    End Using
    Connection.Close()

Just commented out the "command" oledb command since it doesn't get executed, and added the parameter to "oleDBCmd".


问:
Postgresql - update or delete a value from a nested jsonb element
Is there a way to delete/update a nested json key object (not array)
for example the following json:

```<code>{
  "top": {
    "nested": {
       "leaf": 1
    }
  }
}
</code>```

how would I delete/update the leaf element?

I tried

SELECT jsonb '{"top": {"nested": {"leaf" : 1}}' - '{top,nested,leaf}'

but no luck

答:
You need to use the #- operator, not -:

```<code>SELECT jsonb '{"top": {"nested": {"leaf" : 1}}}' #- '{top,nested,leaf}';
┌─────────────────────────┐
│        ?column?         │
├─────────────────────────┤
│ {"top": {"nested": {}}} │
└─────────────────────────┘
(1 row)
</code>```

From the documentation:

- (given a text argument): Delete key/value pair or string element from left operand. Key/value pairs are matched based on their key value.

- (given an int argument): Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.

#-: Delete the field or element with specified path (for JSON arrays, negative integers count from the end)

Body:
Is there a way to delete/update a nested json key object (not array)
for example the following json:

{
  "top": {
    "nested": {
       "leaf": 1
    }
  }
}

how would I delete/update the leaf element?

I tried

SELECT jsonb '{"top": {"nested": {"leaf" : 1}}' - '{top,nested,leaf}'

but no luck

Body:
You need to use the #- operator, not -:

SELECT jsonb '{"top": {"nested": {"leaf" : 1}}}' #- '{top,nested,leaf}';
┌─────────────────────────┐
│        ?column?         │
├─────────────────────────┤
│ {"top": {"nested": {}}} │
└─────────────────────────┘
(1 row)

From the documentation:

- (given a text argument): Delete key/value pair or string element from left operand. Key/value pairs are matched based on their key value.

- (given an int argument): Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.

#-: Delete the field or element with specified path (for JSON arrays, negative integers count from the end)


问:
gsoap memory leak C applications
We are using gsoap for C client and server webservices implemented for blackfin running Linux.

We don't use any malloc in the application. But we see memory usage climbs over time. We are using soap_end to do a cleanup at the end of the call. But when the calls are invoked repeatedly memory usage slowly increasing, may be because of memory fragmentation. This is also impacting performance of the system

What's the preferred usage of gsoap where soap_malloc is not used much. For eg: If we use static arrays etc will it help?

Thanks,

nkr

答:
I would not recommend using static data, there is no need for that.

To debug memory use, compile all your sources files with -DDEBUG. When you run your application you will see three files:

SENT.log the messages sent

RECV.log the messages received

TEST.log the debug log

The TEST.log is useful to check on messaging issues.

The other valuable information produced at runtime are error messages related to memory leaks or heap memory that is damaged (e.g. overruns) in your code. It is unlikely these will happen in the gSOAP engine, but better check.

To ensure proper allocation and deallocation of managed data:

```<code>soap_destroy(soap);
soap_end(soap);
</code>```

I am using the auto-generated functions to allocate managed data:

```<code>SomeClass *obj = soap_new_SomeClass(soap);
</code>```

and sporadically use soap_malloc for raw managed allocation, or to allocate an array of pointers, or a C string:

```<code>const char *s = soap_malloc(soap, 100);
</code>```

but better is to allocate strings with:

```<code>std::string *s = soap_new_std__string(soap);
</code>```

and arrays can be allocated with the second parameter, e.g. an array of 10 strings:

```<code>std::string *s = soap_new_std__string(soap, 10);
</code>```

All managed allocations are deleted with soap_destroy() followed by soap_end(). After that, you can start allocating again and delete again, etc.

If you want to preserve data that otherwise gets deleted with these calls, use:

```<code>soap_unlink(soap, obj);
</code>```

Now obj can be removed later with delete obj. But be aware that all pointer members in obj that point to managed data have become invalid after soap_destroy() and soap_end(). So you may have to invoke soap_unlink() on these members or risk dangling pointers.

A new cool feature of gSOAP is to generate deep copy and delete function for any data structures automatically, which saves a HUGE amount of coding time:

```<code>SomeClass *otherobj = soap_dup_SomeClass(NULL, obj);
</code>```

This duplicates obj to unmanaged heap space. This is a deep copy that checks for cycles in the object graph and removes such cycles to avoid deletion issues. You can also duplicate the whole (cyclic) managed object to another context by using soap instead of NULL for the first argument of soap_dup_SomeClass.

To deep delete:

```<code> soap_del_SomeClass(obj);
</code>```

This deletes obj but also the data pointed to by its members, and so on.

To use the soap_dup_X and soap_del_X functions use soapcpp2 with options -Ec and -Ed, respectively.

In principle, static and stack-allocated data can be serialized just as well. But consider using the managed heap instead.

Hope this helps.

Title: gsoap memory leak C applications

Body:
I would not recommend using static data, there is no need for that.

To debug memory use, compile all your sources files with -DDEBUG. When you run your application you will see three files:

SENT.log the messages sent

RECV.log the messages received

TEST.log the debug log

The TEST.log is useful to check on messaging issues.

The other valuable information produced at runtime are error messages related to memory leaks or heap memory that is damaged (e.g. overruns) in your code. It is unlikely these will happen in the gSOAP engine, but better check.

To ensure proper allocation and deallocation of managed data:

soap_destroy(soap);
soap_end(soap);

I am using the auto-generated functions to allocate managed data:

SomeClass *obj = soap_new_SomeClass(soap);

and sporadically use soap_malloc for raw managed allocation, or to allocate an array of pointers, or a C string:

const char *s = soap_malloc(soap, 100);

but better is to allocate strings with:

std::string *s = soap_new_std__string(soap);

and arrays can be allocated with the second parameter, e.g. an array of 10 strings:

std::string *s = soap_new_std__string(soap, 10);

All managed allocations are deleted with soap_destroy() followed by soap_end(). After that, you can start allocating again and delete again, etc.

If you want to preserve data that otherwise gets deleted with these calls, use:

soap_unlink(soap, obj);

Now obj can be removed later with delete obj. But be aware that all pointer members in obj that point to managed data have become invalid after soap_destroy() and soap_end(). So you may have to invoke soap_unlink() on these members or risk dangling pointers.

A new cool feature of gSOAP is to generate deep copy and delete function for any data structures automatically, which saves a HUGE amount of coding time:

SomeClass *otherobj = soap_dup_SomeClass(NULL, obj);

This duplicates obj to unmanaged heap space. This is a deep copy that checks for cycles in the object graph and removes such cycles to avoid deletion issues. You can also duplicate the whole (cyclic) managed object to another context by using soap instead of NULL for the first argument of soap_dup_SomeClass.

To deep delete:

 soap_del_SomeClass(obj);

This deletes obj but also the data pointed to by its members, and so on.

To use the soap_dup_X and soap_del_X functions use soapcpp2 with options -Ec and -Ed, respectively.

In principle, static and stack-allocated data can be serialized just as well. But consider using the managed heap instead.

Hope this helps.


问:
Check if received more or less than one message
I need to make simple chat application using QTcpSocket and QTcpServer. I understand I should put message size in the beginning of the message to check message bounds. But how should I handle the cases when application receives only part of the message or more than one message?

Or there could be the case when application at first receives incomplete message and after that receives another message. In that situation both messages would be combined in one and only part of second message would be recognized.

答:
If your messages have a defined data type (or a series of defined types) and you use Qt >=5.7 then you can use transactions.

The typical example is if your message is a QString (imagine a JSON or XML) you can write it using QDataStream as always, then you read it you can use:

```<code> QString messageString;
 QDataStream stream(socket);
 stream.startTransaction();
 stream >> messageString;
 if(stream.commitTransaction()){
 // The message was received in full
 }
</code>```

Body:
If your messages have a defined data type (or a series of defined types) and you use Qt >=5.7 then you can use transactions.

The typical example is if your message is a QString (imagine a JSON or XML) you can write it using QDataStream as always, then you read it you can use:

 QString messageString;
 QDataStream stream(socket);
 stream.startTransaction();
 stream >> messageString;
 if(stream.commitTransaction()){
 // The message was received in full
 }


问:
Transaction isolation - INSERTS dependant on previous records values
This question is related/came from discussion about another thing:
What is the correct isolation level for Order header - Order lines transactions?

Imagine scenario where we have usual Orders_Headers and Orders_LineItems tables. Lets say also that we have a special business rules that say:

Each order has Discount field which is calculated based on time passed from last order entered

Each next order Discount field is calculated specially if there has been more than X order in last Y hours.

Each next order Discount field is calculated specially if average frequency of last 10 orders was higher than x per minute.

Each next order Discount field is calculated specially

Point here is to show that every Order is dependant on previous ones and isolation level is crucial.

We have a transaction (just logic of the code shown):

```<code>BEGIN TRANSACTION

INSERT INTO Order_Headers...

SET @Id = SCOPE_IDENTITY()

INSERT INTO Order_LineItems...(using @Id)

DECLARE @SomeVar INT

--just example to show selecting previous x orders
--needed to calculate Discount value for new Order
SELECT @SomeVar = COUNT(*) Order_Headers
WHERE ArbitraryCriteria

UPDATE Order_Headers
SET Discount= UDF(@SomeVar)
WHERE Id = @Id

COMMIT

END TRANSACTION
</code>```

We also have another transaction to read orders:

```<code>SELECT TOP 10 * FROM Order_Headers
ORDER BY Id DESC
</code>```

QUESTIONS

Is SNAPSHOT isolation level for first transaction and READ COMMITED for second appropriate levels?

Is there a better way of approaching CREATE/UPDATE transaction or is this the way to do it?

答:
The serializable option:

Using a pessimistic locking strategy by way of the updlock and serializable table hints to acquire a key range lock specified by the where criteria (backed by a supporting index to lock only the range necessary for the query):

```<code>declare @Id int, @SomeVar int;
begin tran;

  select @SomeVar = count(OrderDate)
  from Order_Headers with (updlock,serializable)
  where OrderDate >= '20170101';

  insert into Order_Headers (OrderDate, SomeVar)
    select sysdatetime(), @SomeVar;

  set @Id = scope_identity();

  insert into Order_LineItems (id,cols)
    select @Id, cols
    from @TableValuedParameter;

commit tran;
</code>```

A good guide to the why and how of using the updlock and serializable table hints to lock a key range with a select, and why you need both, is covered in Sam Saffron''s upsert (update/insert) patterns.

Reference:

Documentation on serializable and other Table Hints - MSDN

Key-Range Locking - MSDN

SQL Server Isolation Levels: A Series - Paul White

Questions About T-SQL Transaction Isolation Levels You Were Too Shy to Ask - Robert Sheldon

Isolation Level references curated by Brent Ozar

Body:
This question is related/came from discussion about another thing:
What is the correct isolation level for Order header - Order lines transactions?

Imagine scenario where we have usual Orders_Headers and Orders_LineItems tables. Lets say also that we have a special business rules that say:

Each order has Discount field which is calculated based on time passed from last order entered

Each next order Discount field is calculated specially if there has been more than X order in last Y hours.

Each next order Discount field is calculated specially if average frequency of last 10 orders was higher than x per minute.

Each next order Discount field is calculated specially

Point here is to show that every Order is dependant on previous ones and isolation level is crucial.

We have a transaction (just logic of the code shown):

BEGIN TRANSACTION

INSERT INTO Order_Headers...

SET @Id = SCOPE_IDENTITY()

INSERT INTO Order_LineItems...(using @Id)

DECLARE @SomeVar INT

--just example to show selecting previous x orders
--needed to calculate Discount value for new Order
SELECT @SomeVar = COUNT(*) Order_Headers
WHERE ArbitraryCriteria

UPDATE Order_Headers
SET Discount= UDF(@SomeVar)
WHERE Id = @Id

COMMIT

END TRANSACTION

We also have another transaction to read orders:

SELECT TOP 10 * FROM Order_Headers
ORDER BY Id DESC

QUESTIONS

Is SNAPSHOT isolation level for first transaction and READ COMMITED for second appropriate levels?

Is there a better way of approaching CREATE/UPDATE transaction or is this the way to do it?

Body:
The serializable option:

Using a pessimistic locking strategy by way of the updlock and serializable table hints to acquire a key range lock specified by the where criteria (backed by a supporting index to lock only the range necessary for the query):

declare @Id int, @SomeVar int;
begin tran;

  select @SomeVar = count(OrderDate)
  from Order_Headers with (updlock,serializable)
  where OrderDate >= '20170101';

  insert into Order_Headers (OrderDate, SomeVar)
    select sysdatetime(), @SomeVar;

  set @Id = scope_identity();

  insert into Order_LineItems (id,cols)
    select @Id, cols
    from @TableValuedParameter;

commit tran;

A good guide to the why and how of using the updlock and serializable table hints to lock a key range with a select, and why you need both, is covered in Sam Saffron''s upsert (update/insert) patterns.

Reference:

Documentation on serializable and other Table Hints - MSDN

Key-Range Locking - MSDN

SQL Server Isolation Levels: A Series - Paul White

Questions About T-SQL Transaction Isolation Levels You Were Too Shy to Ask - Robert Sheldon

Isolation Level references curated by Brent Ozar


问:
how to avoid python numeric literals beginning with "0" being treated as octal?
I am trying to write a small Python 2.x API to support fetching a
job by jobNumber, where jobNumber is provided as an integer.
Sometimes the users provide ajobNumber as an integer literal
beginning with 0, e.g. 037537.  (This is because they have been
coddled by R, a language that sanely considers 037537==37537.)
Python, however, considers integer literals starting with "0" to
be OCTAL, thus 037537!=37537, instead 037537==16223.  This
strikes me as a blatant affront to the principle of least
surprise, and thankfully it looks like this was fixed in Python
3---see PEP 3127.

But I'm stuck with Python 2.7 at the moment.  So my users do this:

```<code>>>> fetchJob(037537)
</code>```

and silently get the wrong job (16223), or this:

```<code>>>> fetchJob(038537)
File "<stdin>", line 1
 fetchJob(038537)
            ^
SyntaxError: invalid token
</code>```

where Python is rejecting the octal-incompatible digit.

There doesn't seem to be anything provided via __future__ to
allow me to get the Py3K behavior---it would have to be built-in
to Python in some manner, since it requires a change to the lexer
at least.

Is anyone aware of how I could protect my users from getting the
wrong job in cases like this?  At the moment the best I can think
of is to change that API so it take a string instead of an int.

答:
Perhaps you could take the input as a string, strip leading zeros, then convert back to an int?</p>

```<code>test = "001234505"
test = int(test.lstrip("0"))  # 1234505
</code>```

Body:
I am trying to write a small Python 2.x API to support fetching a
job by jobNumber, where jobNumber is provided as an integer.
Sometimes the users provide ajobNumber as an integer literal
beginning with 0, e.g. 037537.  (This is because they have been
coddled by R, a language that sanely considers 037537==37537.)
Python, however, considers integer literals starting with "0" to
be OCTAL, thus 037537!=37537, instead 037537==16223.  This
strikes me as a blatant affront to the principle of least
surprise, and thankfully it looks like this was fixed in Python
3---see PEP 3127.

But I'm stuck with Python 2.7 at the moment.  So my users do this:

>>> fetchJob(037537)

and silently get the wrong job (16223), or this:

>>> fetchJob(038537)
File "<stdin>", line 1
 fetchJob(038537)
            ^
SyntaxError: invalid token

where Python is rejecting the octal-incompatible digit.

There doesn't seem to be anything provided via __future__ to
allow me to get the Py3K behavior---it would have to be built-in
to Python in some manner, since it requires a change to the lexer
at least.

Is anyone aware of how I could protect my users from getting the
wrong job in cases like this?  At the moment the best I can think
of is to change that API so it take a string instead of an int.

Body:
Perhaps you could take the input as a string, strip leading zeros, then convert back to an int?

test = "001234505"
test = int(test.lstrip("0"))  # 1234505


问:
jQuery - Given a DIV with a bunch of
 tags, how to find the first
 that isn't empty
Given a DIV with a lot of paragraph tags:

```<code><div>
 <p></p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
</div>
</code>```

How to magically find the first
 which isn't empty using just jQUery? ideas?

答:
```<code>var emptyP = null;
jQuery('div p').each(function() {
    if (emptyP == null && $(this).text() == '') {
        emptyP = this;
    }
});
</code>```

Edit: tster's solution looks better, I didn't know about the :empty selector.

Title: jQuery - Given a DIV with a bunch of <P> tags, how to find the first <P> that isn't empty

Body:
Given a DIV with a lot of paragraph tags:

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

How to magically find the first
 which isn't empty using just jQUery? ideas?

Body:
var emptyP = null;
jQuery('div p').each(function() {
    if (emptyP == null && $(this).text() == '') {
        emptyP = this;
    }
});

Edit: tster's solution looks better, I didn't know about the :empty selector.


问:
Odd "shaking" effect when animating width with jQuery (only in Chrome!)
I'm animating the width of a li element using jQuery in a simple snippet of code. I'm using hover() as the handler and .animate() to animate the width. Here is my code.

```<code>$('li').each(function() {
    //store the original width of the element in a variable
    var oldWidth = $(this).width();
    $(this).hover(
        function() {
            //when the mouse enters the element, animate width to 900px
            $(this).animate({width: '900px'}, 600, 'linear')
        },
    function() {
            //when the mouse leaves, animate back to the original width
            $(this).animate({width: oldWidth}, 350, 'linear')
        }
   );
});
</code>```

The code is really really simple and works but with one very odd quirk in Chrome. When animating the elements in and out, the li elements "shake" as if they're really cold and were shivering. You can see the behavior here in a live example: http://missmd.org/ (edit: bug is now fixed)

I've animated a bunch of stuff before with jQuery and never seen this behavior. Is there any explanation for why it occurs and how I can get around it? I'm wondering if it's because I've floated the elements to the right and am animating to the left. The bug is maddening and detracts from the overall presentation a lot (at least to me). Anyone else seen this before?

Edit to clarify: it's not the actual li element that "shivers" it's the text within it that shakes slightly but noticeably from left to right very quickly as the animation runs. I'm stumped.

Edit two: after fiddling with the CSS a bit now I can only reproduce the effect in Chrome (21.0.1180.60 beta-m for me). In Firefox it works as intended. It also works great in IE. Very ironic that Chrome (usually great with this stuff) is giving me trouble now. Pulls hair out, checks sanity

Here is my HTML to help get to the bottom of this. We have reproduced the problem in ChrisFrancis' jsFiddle.

```<code><nav>
    <ul class="nav">
        <li class="one">
            <a href="homeandnews/">
                <span class="title">Home and News</span>
                <br/>
                <span class="subtitle">Learn more about me and read general updates!</span>
            </a>
        </li>
    </ul>
<nav>
</code>```

I'm completely stumped. This could also be a bug in Chrome/V8 JS engine and there's nothing we can do about it.

答:
Had similar issue with shaking SVGs when there's a CSS transition applied to parent tag. I tried to apply everything I could randomly, and this fix finally helped:</p>

```<code>svg {
  transform: translate3d(0, 0, 0);
}
</code>```

Body:
I'm animating the width of a li element using jQuery in a simple snippet of code. I'm using hover() as the handler and .animate() to animate the width. Here is my code.

$('li').each(function() {
    //store the original width of the element in a variable
    var oldWidth = $(this).width();
    $(this).hover(
        function() {
            //when the mouse enters the element, animate width to 900px
            $(this).animate({width: '900px'}, 600, 'linear')
        },
    function() {
            //when the mouse leaves, animate back to the original width
            $(this).animate({width: oldWidth}, 350, 'linear')
        }
   );
});

The code is really really simple and works but with one very odd quirk in Chrome. When animating the elements in and out, the li elements "shake" as if they're really cold and were shivering. You can see the behavior here in a live example: http://missmd.org/ (edit: bug is now fixed)

I've animated a bunch of stuff before with jQuery and never seen this behavior. Is there any explanation for why it occurs and how I can get around it? I'm wondering if it's because I've floated the elements to the right and am animating to the left. The bug is maddening and detracts from the overall presentation a lot (at least to me). Anyone else seen this before?

Edit to clarify: it's not the actual li element that "shivers" it's the text within it that shakes slightly but noticeably from left to right very quickly as the animation runs. I'm stumped.

Edit two: after fiddling with the CSS a bit now I can only reproduce the effect in Chrome (21.0.1180.60 beta-m for me). In Firefox it works as intended. It also works great in IE. Very ironic that Chrome (usually great with this stuff) is giving me trouble now. Pulls hair out, checks sanity

Here is my HTML to help get to the bottom of this. We have reproduced the problem in ChrisFrancis' jsFiddle.

                Home and News

                Learn more about me and read general updates!

I'm completely stumped. This could also be a bug in Chrome/V8 JS engine and there's nothing we can do about it.

Body:
Had similar issue with shaking SVGs when there's a CSS transition applied to parent tag. I tried to apply everything I could randomly, and this fix finally helped:

svg {
  transform: translate3d(0, 0, 0);
}


答:
Using -Wwrite-strings option you will get:

```<code>warning: initialization discards qualifiers from pointer target type
</code>```

Irrespective of that option, GCC will put literals into read-only memory section, unless told otherwise by using -fwritable-strings (however this option has been removed from recent GCC versions).

Command line parameters are not const, they typically live on the stack.

Title: Are string literals const?

Body:
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

char *foo = "bar";

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?

Body:
Using -Wwrite-strings option you will get:

warning: initialization discards qualifiers from pointer target type

Irrespective of that option, GCC will put literals into read-only memory section, unless told otherwise by using -fwritable-strings (however this option has been removed from recent GCC versions).

Command line parameters are not const, they typically live on the stack.


问:
Error while validating XML
System.ArgumentNullException: value cannot be undefined

StackTrace:

```<code>   at System.Xml.Linq.XAttribute..ctor(XName name, Object value)
   at System.Xml.Schema.XNodeValidator.ValidateAttributes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateNodes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.Validate(XObject source, XmlSchemaObject partialValidationType, Boolean addSchemaInfo)
   at System.Xml.Schema.Extensions.Validate(XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, Boolean addSchemaInfo)
</code>```

Source code:

```<code>    var xmlPath = @"C:\XSDTEST\test.xml";

    XDocument doc = XDocument.Load(xmlPath);
    XmlSchemaSet xss = new XmlSchemaSet();

    xss.Add("",@"C:\XSDTEST\test.xsd");

    XmlReaderSettings xrs = new XmlReaderSettings();
    xrs.ValidationType = ValidationType.Schema;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
    xrs.Schemas = xss;

    doc.Validate(xss, new ValidationEventHandler((s, args) => { }), true);
</code>```

test.xsd:

```<code><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="Root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="Child1" minOccurs="1" maxOccurs="1"/>
                <xsd:element ref="Child2" minOccurs="1" maxOccurs="1"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="Child2" type="Child2ElemType"/>
    <xsd:complexType name="Child2ElemType">
        <xsd:attribute ref="align" default="left"/>
    </xsd:complexType>
    <xsd:attribute name="align" type="alignAttType"/>
    <xsd:simpleType name="alignAttType">
        <xsd:restriction base="xsd:NMTOKEN">
            <xsd:enumeration value="left"/>
            <xsd:enumeration value="right"/>
            <xsd:enumeration value="center"/>
            <xsd:enumeration value="justify"/>
            <xsd:enumeration value="char"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:schema>
</code>```

test.xml:

```<code><Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/XSDTEST/test.xsd">
    <Child1/>
    <Child2/>
</Root>
</code>```

The problem: default="left":

```<code><xsd:attribute ref="align" default="left"/>
</code>```

I think the validation process tries to create an "align" attribute with a default value, but the XAttribute constructor gets null, not "left".

If I set default value at <xsd:attribute name="align" type="alignAttType" default="left"/> it works fine.

If I set default value at <xsd:attribute ref="align" default="left"/> I will get the error.

Can I disable the creation of attributes with default values during the validation process?

or

What are the settings for correctly handling the default values?

答:
Based on the XSD, the "ref=" must be a "Qualified Name"

https://msdn.microsoft.com/en-us/library/ms256143(v=vs.110).aspx

The ref value must be a qualified name (QName)

Since you have an XSD without a namespace, it looks like the validator is not able to find the referenced attribute.

Also, take a look at this related SO question:
How to reference an attribute in xsd

in XML Schemas all global element, attribute or type definitions must be qualified

The following is the relevant Standard extract:
https://www.w3.org/TR/REC-xml-names/#defaulting

Default namespace declarations do not apply directly to attribute names

The namespace name for an unprefixed attribute name always has no value

The following link talks specifically about the unqualified global attributes
Unqualified XSD global attribute references

Title: Error while validating XML

Body:
System.ArgumentNullException: value cannot be undefined

StackTrace:

   at System.Xml.Linq.XAttribute..ctor(XName name, Object value)
   at System.Xml.Schema.XNodeValidator.ValidateAttributes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateNodes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.Validate(XObject source, XmlSchemaObject partialValidationType, Boolean addSchemaInfo)
   at System.Xml.Schema.Extensions.Validate(XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, Boolean addSchemaInfo)

Source code:

    var xmlPath = @"C:\XSDTEST\test.xml";

    XDocument doc = XDocument.Load(xmlPath);
    XmlSchemaSet xss = new XmlSchemaSet();

    xss.Add("",@"C:\XSDTEST\test.xsd");

    XmlReaderSettings xrs = new XmlReaderSettings();
    xrs.ValidationType = ValidationType.Schema;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
    xrs.Schemas = xss;

    doc.Validate(xss, new ValidationEventHandler((s, args) => { }), true);

test.xsd:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="Root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="Child1" minOccurs="1" maxOccurs="1"/>
                <xsd:element ref="Child2" minOccurs="1" maxOccurs="1"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="Child2" type="Child2ElemType"/>
    <xsd:complexType name="Child2ElemType">
        <xsd:attribute ref="align" default="left"/>
    </xsd:complexType>
    <xsd:attribute name="align" type="alignAttType"/>
    <xsd:simpleType name="alignAttType">
        <xsd:restriction base="xsd:NMTOKEN">
            <xsd:enumeration value="left"/>
            <xsd:enumeration value="right"/>
            <xsd:enumeration value="center"/>
            <xsd:enumeration value="justify"/>
            <xsd:enumeration value="char"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:schema>

test.xml:

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/XSDTEST/test.xsd">
    <Child1/>
    <Child2/>
</Root>

The problem: default="left":

<xsd:attribute ref="align" default="left"/>

I think the validation process tries to create an "align" attribute with a default value, but the XAttribute constructor gets null, not "left".

If I set default value at <xsd:attribute name="align" type="alignAttType" default="left"/> it works fine.

If I set default value at <xsd:attribute ref="align" default="left"/> I will get the error.

Can I disable the creation of attributes with default values during the validation process?

or

What are the settings for correctly handling the default values?


问:
Dynamic store dirs for same models with carrierwave
I am using CarrierWave with fog to upload my images to S3.

I have model Image that can represent images of different sizes and according to that needs to be saved in different folder.

For example, for image.jpg I could have two different uploaded versions that need to be saved as:

```<code>'images/large/image.jpg'
'images/small/image.jpg'
</code>```

There could be arbitrary number of use cases and versions using minimagick can't cover them all.

So far I haven't been able to find solution. Does anyone know how to do this?

答:
in order to change where uploaded files are put, just override the store_dir method:, for your case (reference link)</p>

```<code>class Image < CarrierWave::Uploader::Base
storage :file
  # this if you using use condition for folder location
  def store_dir
    if model.somefield == "somecondition
       "uploads/#{model.somefield}"
    elsif model.somefield == "somecondition
       "uploads/location2"
    else
       "uploads/default_dir"
    end

  end
  # this is if you want to use version_name
  def store_dir
    'images/#{version_name}/'
  end
end
</code>```

Body:
I am using CarrierWave with fog to upload my images to S3.

I have model Image that can represent images of different sizes and according to that needs to be saved in different folder.

For example, for image.jpg I could have two different uploaded versions that need to be saved as:

'images/large/image.jpg'
'images/small/image.jpg'

There could be arbitrary number of use cases and versions using minimagick can't cover them all.

So far I haven't been able to find solution. Does anyone know how to do this?

Body:
in order to change where uploaded files are put, just override the store_dir method:, for your case (reference link)

class Image < CarrierWave::Uploader::Base
storage :file
  # this if you using use condition for folder location
  def store_dir
    if model.somefield == "somecondition
       "uploads/#{model.somefield}"
    elsif model.somefield == "somecondition
       "uploads/location2"
    else
       "uploads/default_dir"
    end

  end
  # this is if you want to use version_name
  def store_dir
    'images/#{version_name}/'
  end
end


问:
Div not showing on hover?
So, I'm trying to make this so when I hover over the image, the div appears. Unfortunately, I am not able to get it to do so, and I'm at a loss as to why it's not working.

Here is my code:

.summary:hover {
  opacity: .6;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
}

.summaryOverlay {
  position: absolute;
  margin-left: 5%;
  margin-top: 3%;
  height: 200px;
  width: 280px;
  z-index: 2;
  background-color: #E7DFDD;
  color: #0E0B16;
  font-family: Verdana;
  font-size: 15px;
  opacity: .9;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
  text-align: center;
  display: none;
}

.summary:hover .summaryOverlay {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="leftAlign" id="lastWish">
  <img class="summary" alt="the last wish" src="lastWish.jpg" style="width: inherit; height: inherit;" />
</div>
<div class="summaryOverlay">
  Geralt is a witcher.
  <br><br>  Yet he is no ordinary killer-for-hire.
  <br><br> His sole purpose: to destroy the monsters that plague the world.
  <br><br> But not everything monstrous-looking is evil and not everything fair is good. . . and in every fairy tale there is a grain of truth.
</div></code>```

答:
Because .summaryOverlay isn't child of .summary, as you stated here:

```<code>.summary:hover .summaryOverlay {
  display: block;
}
</code>```

So you need to hover in .leftAlign (.summary's parent) which is the .summaryOverlay sibling, you need for that to use the adjacent sibling selector +

Note: remove the inline styles, they are a bad practice to use them

.summary:hover {
  opacity: .6;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
}

.summaryOverlay {
  position: absolute;
  margin-left: 5%;
  margin-top: 3%;
  height: 200px;
  width: 280px;
  z-index: 2;
  background-color: #E7DFDD;
  color: #0E0B16;
  font-family: Verdana;
  font-size: 15px;
  opacity: .9;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
  text-align: center;
  display: none;
}

.leftAlign:hover + .summaryOverlay {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="leftAlign" id="lastWish">
  <img class="summary" alt="the last wish" src="//placehold.it/100x100" />
</div>
<div class="summaryOverlay">
  Geralt is a witcher.
  <br><br>  Yet he is no ordinary killer-for-hire.
  <br><br> His sole purpose: to destroy the monsters that plague the world.
  <br><br> But not everything monstrous-looking is evil and not everything fair is good. . . and in every fairy tale there is a grain of truth.
</div></code>```

Title: Div not showing on hover?

Body:
So, I'm trying to make this so when I hover over the image, the div appears. Unfortunately, I am not able to get it to do so, and I'm at a loss as to why it's not working.

Here is my code:

.summary:hover {
  opacity: .6;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
}

.summaryOverlay {
  position: absolute;
  margin-left: 5%;
  margin-top: 3%;
  height: 200px;
  width: 280px;
  z-index: 2;
  background-color: #E7DFDD;
  color: #0E0B16;
  font-family: Verdana;
  font-size: 15px;
  opacity: .9;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
  text-align: center;
  display: none;
}

.summary:hover .summaryOverlay {
  display: block;
}

  Geralt is a witcher.

  Yet he is no ordinary killer-for-hire.

 His sole purpose: to destroy the monsters that plague the world.

 But not everything monstrous-looking is evil and not everything fair is good. . . and in every fairy tale there is a grain of truth.

Body:
Because .summaryOverlay isn't child of .summary, as you stated here:

.summary:hover .summaryOverlay {
  display: block;
}

So you need to hover in .leftAlign (.summary's parent) which is the .summaryOverlay sibling, you need for that to use the adjacent sibling selector +

Note: remove the inline styles, they are a bad practice to use them

.summary:hover {
  opacity: .6;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
}

.summaryOverlay {
  position: absolute;
  margin-left: 5%;
  margin-top: 3%;
  height: 200px;
  width: 280px;
  z-index: 2;
  background-color: #E7DFDD;
  color: #0E0B16;
  font-family: Verdana;
  font-size: 15px;
  opacity: .9;
  -moz-transition: all .1s ease-in-out;
  -o-transition: all .1s ease-in-out;
  -webkit-transition: all .1s ease-in-out;
  transition: all .1s ease-in-out;
  text-align: center;
  display: none;
}

.leftAlign:hover + .summaryOverlay {
  display: block;
}

<div class="leftAlign" id="lastWish">
  <img class="summary" alt="the last wish" src="//placehold.it/100x100" />
</div>
<div class="summaryOverlay">
  Geralt is a witcher.
  <br><br> &nbsp;Yet he is no ordinary killer-for-hire.
  <br><br> His sole purpose: to destroy the monsters that plague the world.
  <br><br> But not everything monstrous-looking is evil and not everything fair is good. . . and in every fairy tale there is a grain of truth.
</div>


问:
Get max value from a map with keys corresponding to a list in Java 7
I have a Map<String, Double> and a List<String>.

The list actually contains possible keys for the map.
Now, I want the max value in the map corresponding to the list of keys.

For eg:

Map

(a, 3),
  (b, 4),
  (c, 5),
  (d, 6),
  (e, 7)

List

b,
  d

Output should be = 6

Current solution:

```<code>public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    Double maxDiscount = 0d;

    for (String key : list) {
        Double discount = map.get(key);
        if (discount > maxDiscount) {
            maxDiscount = discount;
        }
    }
    return maxDiscount;
}
</code>```

How can I do it more efficiently?

答:
Though there are other solutions (Stream API based) but I will tell you the basic algorithm to solve this.

Initilize:  max = Double.MIN_VALUE;

Iterate over the list: for (String key : List)

For each key check: if(Map.contains(key))

If (max < Map.get(key)) is true then assign max = Map.get(key)

At the end of the iteration, the value of max is the maximum value you are looking for.

Body:
I have a Map<String, Double> and a List<String>.

The list actually contains possible keys for the map.
Now, I want the max value in the map corresponding to the list of keys.

For eg:

Map

(a, 3),
  (b, 4),
  (c, 5),
  (d, 6),
  (e, 7)

List

b,
  d

Output should be = 6

Current solution:

public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    Double maxDiscount = 0d;

    for (String key : list) {
        Double discount = map.get(key);
        if (discount > maxDiscount) {
            maxDiscount = discount;
        }
    }
    return maxDiscount;
}

How can I do it more efficiently?

ContentLicense: CC BY-SA 4.0


问:
updating nodejs on ubuntu 16.04
I was recently going through the version of node in my ubuntu 16.04 when node -v command was used it shows me version 6.9.1 but when nodejs -v it shows 6.9.2 previously before using this commands npm update command was used.

Now what's these difference in node -v and nodejs -v? and how to update to the latest LTS version of node/nodejs?

答:
Difference: When I first installed node, it installed as 'nodejs'. When I upgraded it, it created 'node'. By executing node, we are actually executing nodejs. Node is just a reference to nodejs.
From my experience, when I upgraded, it affected both the versions (as it is supposed to). When I do nodejs -v or node -v, I get the new version.

Upgrading: npm update is used to update the packages in the current directory. Check https://docs.npmjs.com/cli/update

To upgrade node version, based on the OS you are using, follow the commands here https://nodejs.org/en/download/package-manager/

Title: updating nodejs on ubuntu 16.04


问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
In complete case of the other answers, you can load the file in matlab an change the string by strjoin:

```<code>[~,~,raw] = xlsread(fileName);
num = length(raw{:,1});
for rawNum = 1:num
    str = raw{rawNum,1};
    raw{rawNum,1} = strjoin(cellstr(str(:)), '>');
end
xlswrite(fileName, raw);
</code>```

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?

Body:
In complete case of the other answers, you can load the file in matlab an change the string by strjoin:

[~,~,raw] = xlsread(fileName);
num = length(raw{:,1});
for rawNum = 1:num
    str = raw{rawNum,1};
    raw{rawNum,1} = strjoin(cellstr(str(:)), '>');
end
xlswrite(fileName, raw);


问:
Quit jQuery $.each loop

Possible Duplicate:

  How do I break out of an $.each in jquery?

How to quit the jquery $.each loop?

答:
http://api.jquery.com/jQuery.each/

We can break the $.each() loop at a
  particular iteration by making the
  callback function return false.
  Returning non-false is the same as a
  continue statement in a for loop; it
  will skip immediately to the next
  iteration.

Title: Quit jQuery $.each loop