问:
Can't get DataNucleus JDO metadata only mapping to work
The DataNucleus JDO Mapping Guide states:

So you can provide the metadata via annotations solely, or via
  annotations plus ORM XML Metadata overrides, or via JDO XML Metadata
  solely, or via JDO XML Metadata plus ORM XML Metadata overrides, or
  finally via a Metadata API.

Emphasis mine.

I took the following class from the JDO tutorial:

```<code>package org.datanucleus.samples.jdo.tutorial;

public class Product
{
    String name = null;
    String description = null;
    double price = 0.0;

    public Product(String name, String desc, double price)
    {
        this.name = name;
        this.description = desc;
        this.price = price;
    }
}
</code>```

And created the following package.jdo:

```<code><?xml version="1.0" encoding="utf-8"?>
<jdo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
     version="3.1">
   <package name="org.datanucleus.samples.jdo.tutorial">
      <class name="Product" identity-type="datastore" table="product">
         <inheritance>
            <discriminator strategy="class-name"/>
         </inheritance>
         <datastore-identity>
            <column name="product_ID"/>
         </datastore-identity>
         <field name="name">
            <column name="name" jdbc-type="STRING" allows-null="true"/>
         </field>
         <field name="description">
            <column name="description" jdbc-type="STRING" allows-null="true"/>
         </field>
         <field name="price">
            <column name="price" jdbc-type="DOUBLE" allows-null="true"/>
         </field>
      </class>
   </package>
</jdo>
</code>```

and put it in src/main/resources/META-INF (as per documentation) in my maven project.

Now I'm unclear whether I need to perform the enhancing step with metadata only as well, but when I do I get the following output:

```<code>DataNucleus Enhancer completed with success for 0 classes. Timings : input=16 ms, enhance=0 ms, total=16 ms. Consult the log for full details

DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details
</code>```

I wrote this test application:

```<code>package org.datanucleus.samples.jdo.tutorial;

import javax.jdo.JDOHelper;
import javax.jdo.Transaction;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

public class Test {

    public static void main(String[] args) {
        PersistenceManagerFactory factory;
        factory = JDOHelper.getPersistenceManagerFactory("Tutorial");
        PersistenceManager manager = factory.getPersistenceManager();
        Transaction t = manager.currentTransaction();
        try {
            t.begin();
            Product obj = new Product("Test Product", "Test Product Description", 9.99);
            manager.makePersistent(obj);
            t.commit();
        } finally {
            if (t.isActive()) {
                t.rollback();
            }
            manager.close();
        }
    }
}
</code>```

and get these errors when I run it with mvn exec:java:

```<code>java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:294)
    at java.lang.Thread.run (Thread.java:748)
Caused by: org.datanucleus.api.jdo.exceptions.ClassNotPersistenceCapableException: The class "org.datanucleus.samples.jdo.tutorial.Product" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found.
    at org.datanucleus.api.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException (NucleusJDOHelper.java:473)
    at org.datanucleus.api.jdo.JDOPersistenceManager.jdoMakePersistent (JDOPersistenceManager.java:717)
    at org.datanucleus.api.jdo.JDOPersistenceManager.makePersistent (JDOPersistenceManager.java:738)
    at org.datanucleus.samples.jdo.tutorial.Test.main (Test.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:294)
    at java.lang.Thread.run (Thread.java:748)
Caused by: org.datanucleus.exceptions.ClassNotPersistableException: The class "org.datanucleus.samples.jdo.tutorial.Product" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found.
    at org.datanucleus.ExecutionContextImpl.assertClassPersistable (ExecutionContextImpl.java:5113)
    at org.datanucleus.ExecutionContextImpl.persistObjectInternal (ExecutionContextImpl.java:1887)
    at org.datanucleus.ExecutionContextImpl.persistObjectWork (ExecutionContextImpl.java:1830)
    at org.datanucleus.ExecutionContextImpl.persistObject (ExecutionContextImpl.java:1685)
    at org.datanucleus.api.jdo.JDOPersistenceManager.jdoMakePersistent (JDOPersistenceManager.java:712)
    at org.datanucleus.api.jdo.JDOPersistenceManager.makePersistent (JDOPersistenceManager.java:738)
    at org.datanucleus.samples.jdo.tutorial.Test.main (Test.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:294)
    at java.lang.Thread.run (Thread.java:748)
</code>```

What am I missing?

Thanks in advance.

EDIT:

Forgot to include my persistence.xml that I put in src/main/resources/META-INF:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">

    <!-- JDO tutorial "unit" -->
    <persistence-unit name="Tutorial">
        <class>org.datanucleus.samples.jdo.tutorial.Inventory</class>
        <class>org.datanucleus.samples.jdo.tutorial.Product</class>
        <class>org.datanucleus.samples.jdo.tutorial.Book</class>
        <exclude-unlisted-classes/>
        <properties>
            <property name="javax.jdo.option.ConnectionDriverName" value="org.postgresql.Driver"/>
            <property name="javax.jdo.option.ConnectionURL" value="jdbc:postgresql://host/postgres"/>
            <property name="javax.jdo.option.ConnectionUserName" value="user"/>
            <property name="javax.jdo.option.ConnectionPassword" value="secret"/>
            <property name="datanucleus.schema.autoCreateAll" value="true"/>
        </properties>
    </persistence-unit>
</persistence>
</code>```

答:
I found the solution.

I discovered in the Persistence Guide that if you plan on using JDO Metadata only you need to specify a package.jdo file for your persistence unit using the mapping-file attribute instead of providing the actual class names.

Body:
The DataNucleus JDO Mapping Guide states:

So you can provide the metadata via annotations solely, or via
  annotations plus ORM XML Metadata overrides, or via JDO XML Metadata
  solely, or via JDO XML Metadata plus ORM XML Metadata overrides, or
  finally via a Metadata API.

Emphasis mine.

I took the following class from the JDO tutorial:

package org.datanucleus.samples.jdo.tutorial;

public class Product
{
    String name = null;
    String description = null;
    double price = 0.0;

    public Product(String name, String desc, double price)
    {
        this.name = name;
        this.description = desc;
        this.price = price;
    }
}

And created the following package.jdo:

<?xml version="1.0" encoding="utf-8"?>
<jdo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
     version="3.1">
   <package name="org.datanucleus.samples.jdo.tutorial">
      <class name="Product" identity-type="datastore" table="product">
         <inheritance>
            <discriminator strategy="class-name"/>
         </inheritance>
         <datastore-identity>
            <column name="product_ID"/>
         </datastore-identity>
         <field name="name">
            <column name="name" jdbc-type="STRING" allows-null="true"/>
         </field>
         <field name="description">
            <column name="description" jdbc-type="STRING" allows-null="true"/>
         </field>
         <field name="price">
            <column name="price" jdbc-type="DOUBLE" allows-null="true"/>
         </field>
      </class>
   </package>
</jdo>

and put it in src/main/resources/META-INF (as per documentation) in my maven project.

Now I'm unclear whether I need to perform the enhancing step with metadata only as well, but when I do I get the following output:

DataNucleus Enhancer completed with success for 0 classes. Timings : input=16 ms, enhance=0 ms, total=16 ms. Consult the log for full details

DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details

I wrote this test application:

package org.datanucleus.samples.jdo.tutorial;

import javax.jdo.JDOHelper;
import javax.jdo.Transaction;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

public class Test {

    public static void main(String[] args) {
        PersistenceManagerFactory factory;
        factory = JDOHelper.getPersistenceManagerFactory("Tutorial");
        PersistenceManager manager = factory.getPersistenceManager();
        Transaction t = manager.currentTransaction();
        try {
            t.begin();
            Product obj = new Product("Test Product", "Test Product Description", 9.99);
            manager.makePersistent(obj);
            t.commit();
        } finally {
            if (t.isActive()) {
                t.rollback();
            }
            manager.close();
        }
    }
}

and get these errors when I run it with mvn exec:java:

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:294)
    at java.lang.Thread.run (Thread.java:748)
Caused by: org.datanucleus.api.jdo.exceptions.ClassNotPersistenceCapableException: The class "org.datanucleus.samples.jdo.tutorial.Product" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found.
    at org.datanucleus.api.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException (NucleusJDOHelper.java:473)
    at org.datanucleus.api.jdo.JDOPersistenceManager.jdoMakePersistent (JDOPersistenceManager.java:717)
    at org.datanucleus.api.jdo.JDOPersistenceManager.makePersistent (JDOPersistenceManager.java:738)
    at org.datanucleus.samples.jdo.tutorial.Test.main (Test.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:294)
    at java.lang.Thread.run (Thread.java:748)
Caused by: org.datanucleus.exceptions.ClassNotPersistableException: The class "org.datanucleus.samples.jdo.tutorial.Product" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found.
    at org.datanucleus.ExecutionContextImpl.assertClassPersistable (ExecutionContextImpl.java:5113)
    at org.datanucleus.ExecutionContextImpl.persistObjectInternal (ExecutionContextImpl.java:1887)
    at org.datanucleus.ExecutionContextImpl.persistObjectWork (ExecutionContextImpl.java:1830)
    at org.datanucleus.ExecutionContextImpl.persistObject (ExecutionContextImpl.java:1685)
    at org.datanucleus.api.jdo.JDOPersistenceManager.jdoMakePersistent (JDOPersistenceManager.java:712)
    at org.datanucleus.api.jdo.JDOPersistenceManager.makePersistent (JDOPersistenceManager.java:738)
    at org.datanucleus.samples.jdo.tutorial.Test.main (Test.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:294)
    at java.lang.Thread.run (Thread.java:748)

What am I missing?

Thanks in advance.

EDIT:

Forgot to include my persistence.xml that I put in src/main/resources/META-INF:

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">

    <persistence-unit name="Tutorial">
        <class>org.datanucleus.samples.jdo.tutorial.Inventory</class>
        <class>org.datanucleus.samples.jdo.tutorial.Product</class>
        <class>org.datanucleus.samples.jdo.tutorial.Book</class>
        <exclude-unlisted-classes/>
        <properties>
            <property name="javax.jdo.option.ConnectionDriverName" value="org.postgresql.Driver"/>
            <property name="javax.jdo.option.ConnectionURL" value="jdbc:postgresql://host/postgres"/>
            <property name="javax.jdo.option.ConnectionUserName" value="user"/>
            <property name="javax.jdo.option.ConnectionPassword" value="secret"/>
            <property name="datanucleus.schema.autoCreateAll" value="true"/>
        </properties>
    </persistence-unit>
</persistence>


来源: stackexchange

问:
The csvtojson converter ignores my file name and just puts undefined
Basically, when I just run csvtojson module on node.js without any code, it works perfectly. But once I put it into the function, it just comes out with undefined even though my file path is still there.

Js code:

```<code>var Converter = require("csvtojson").Converter;
// create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function

var  woops;

var createNewEntries = function(db, woops, callback) {

converter.fromFile("./NTA-SAM-Inventory-List-Security-Management-
                   New_2017.csv",function(err, result){
    // if an error has occured then handle it
    if(err){
        console.log("An Error Has Occured");
        console.log(err);
    }
    // the result of the conversion
        console.log(result);
        console.log('ohhhhh');
        woops=result;
});
console.log(woops);
};
    MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log(err);
        }
        setTimeout(function(){
        createNewEntries(db, woops, function(){
            if(err)
                throw err;
            else{
                console.log(woops);
            }
            db.close();
        });
        },2000);

    });
</code>```

This is just testing out whether it converts inside a function and it just shows

undefined
[]
ohhhhh
without converting at all when in a function. So exactly what did I do wrong. By right it should have convert after calling the function. Does it have to do with my code executing before the function ? I already put a setTimeout just to give it some time to do so I assume it shouldn't have to do with the order of my code. Thanks in advance!

答:
You should try below code for your file name:

```<code>__dirname + "/NTA-SAM-Inventory-List-Security-Management-
                       New_2017.csv"
</code>```

Replace your code for  converter.fromFile() , Now your code would be like that:

```<code>    converter.fromFile(__dirname + "/NTA-SAM-Inventory-List-Security-Management-
                               New_2017.csv" ,function(err, result){
        // if an error has occured then handle it
        if(err){
            console.log("An Error Has Occured");
            console.log(err);
        }
        // the result of the conversion
            console.log(result);
            console.log('ohhhhh');
            woops=result;
 MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log(err);
        }
        setTimeout(function(){
        createNewEntries(db, woops, function(){
            if(err)
                throw err;
            else{
                console.log(woops);
            }
            db.close();
        });
        },2000);

    });

    });
</code>```

Hope it will work for you.

If the above code are not wouking then try below code with fast-csv module:

```<code>var fcsv = require('fast-csv');
var fs = require('fs');

/**
 * Get the records from csv
 */

var writeZipCodes = function () {
var stream = fs.createReadStream(__dirname + "/NTA-SAM-Inventory-List-Security-Management-New_2017.csv");

fcsv
  .fromStream(stream, { headers: true }) // headers for columns
  .on("data", function (data) {
          console.log(data);
          var woops=data;
          MongoClient.connect(url, function(err, db) {
            if(err) {
                console.log(err);
            }
            setTimeout(function(){
            createNewEntries(db, woops, function(){
                if(err)
                    throw err;
                else{
                    console.log(woops);
                }
                db.close();
            });
            },2000);

        });
})
  .on("end", function () {
         console.log("done");
});
}

 writeZipCodes();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Basically, when I just run csvtojson module on node.js without any code, it works perfectly. But once I put it into the function, it just comes out with undefined even though my file path is still there.

Js code:

var Converter = require("csvtojson").Converter;
// create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function

var  woops;

var createNewEntries = function(db, woops, callback) {

converter.fromFile("./NTA-SAM-Inventory-List-Security-Management-
                   New_2017.csv",function(err, result){
    // if an error has occured then handle it
    if(err){
        console.log("An Error Has Occured");
        console.log(err);
    }
    // the result of the conversion
        console.log(result);
        console.log('ohhhhh');
        woops=result;
});
console.log(woops);
};
    MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log(err);
        }
        setTimeout(function(){
        createNewEntries(db, woops, function(){
            if(err)
                throw err;
            else{
                console.log(woops);
            }
            db.close();
        });
        },2000);

    });

This is just testing out whether it converts inside a function and it just shows

undefined
[]
ohhhhh
without converting at all when in a function. So exactly what did I do wrong. By right it should have convert after calling the function. Does it have to do with my code executing before the function ? I already put a setTimeout just to give it some time to do so I assume it shouldn't have to do with the order of my code. Thanks in advance!

Body:
You should try below code for your file name:

__dirname + "/NTA-SAM-Inventory-List-Security-Management-
                       New_2017.csv"

Replace your code for  converter.fromFile() , Now your code would be like that:

    converter.fromFile(__dirname + "/NTA-SAM-Inventory-List-Security-Management-
                               New_2017.csv" ,function(err, result){
        // if an error has occured then handle it
        if(err){
            console.log("An Error Has Occured");
            console.log(err);
        }
        // the result of the conversion
            console.log(result);
            console.log('ohhhhh');
            woops=result;
 MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log(err);
        }
        setTimeout(function(){
        createNewEntries(db, woops, function(){
            if(err)
                throw err;
            else{
                console.log(woops);
            }
            db.close();
        });
        },2000);

    });

    });

Hope it will work for you.

If the above code are not wouking then try below code with fast-csv module:

var fcsv = require('fast-csv');
var fs = require('fs');

/**
 * Get the records from csv
 */

var writeZipCodes = function () {
var stream = fs.createReadStream(__dirname + "/NTA-SAM-Inventory-List-Security-Management-New_2017.csv");

fcsv
  .fromStream(stream, { headers: true }) // headers for columns
  .on("data", function (data) {
          console.log(data);
          var woops=data;
          MongoClient.connect(url, function(err, db) {
            if(err) {
                console.log(err);
            }
            setTimeout(function(){
            createNewEntries(db, woops, function(){
                if(err)
                    throw err;
                else{
                    console.log(woops);
                }
                db.close();
            });
            },2000);

        });
})
  .on("end", function () {
         console.log("done");
});
}

 writeZipCodes();


问:
sizeof(text) not equal to : fp_len + 1
if

```<code>fp_len = ftell(fp);
</code>```

prints 470

shouldn't this be printing "471" ?  ( it prints 8. probably first line only )

```<code>char *text = malloc(sizeof(*text) * fp_len + 1);
int text_len;
text_len = sizeof(text);

printf("text-len: %d --- ",text_len);
</code>```

full:

```<code>FILE *fp;
fp = fopen(path, "r");

fseek(fp, 0, SEEK_END);

int fp_len;
fp_len = ftell(fp);
printf("%d---", fp_len);

fseek(fp, 0, SEEK_SET);

char *text = malloc(sizeof(*text) * fp_len + 1);

int text_len;
text_len = sizeof(text);
printf("text-len: %d --- ",text_len);

fread(text, fp_len, 1, fp);

printf("%s",text);

free(text);
</code>```

答:
The sizeof is an operator in C and not a function. It acts on the type of the expression inside the brackets.

It tells the size of the type. In general cases when you do sizeof of say a char array like,

```<code>char array[] = "Hello";
sizeof(array);
</code>```

you get 6, because the type of array is char[6].

Now in this case you are doing sizeof on text.

text is defined as char* which is a pointer. Pointers on your system are 8 bytes. So it is giving out 8.

Trying to use sizeof which dynamically allocated buffers is not going to work. Instead you can use

```<code>sizeof(*text) * fp_len + 1
</code>```

Because that is what you passed to malloc. That is ACTUALLY the size of the buffer pointed to by text.

Title: sizeof(text) not equal to : fp_len + 1

Body:
if

fp_len = ftell(fp);

prints 470

shouldn't this be printing "471" ?  ( it prints 8. probably first line only )

char *text = malloc(sizeof(*text) * fp_len + 1);
int text_len;
text_len = sizeof(text);

printf("text-len: %d --- ",text_len);

full:

FILE *fp;
fp = fopen(path, "r");

fseek(fp, 0, SEEK_END);

int fp_len;
fp_len = ftell(fp);
printf("%d---", fp_len);

fseek(fp, 0, SEEK_SET);

char *text = malloc(sizeof(*text) * fp_len + 1);

int text_len;
text_len = sizeof(text);
printf("text-len: %d --- ",text_len);

fread(text, fp_len, 1, fp);

printf("%s",text);

free(text);

Body:
The sizeof is an operator in C and not a function. It acts on the type of the expression inside the brackets.

It tells the size of the type. In general cases when you do sizeof of say a char array like,

char array[] = "Hello";
sizeof(array);

you get 6, because the type of array is char[6].

Now in this case you are doing sizeof on text.

text is defined as char* which is a pointer. Pointers on your system are 8 bytes. So it is giving out 8.

Trying to use sizeof which dynamically allocated buffers is not going to work. Instead you can use

sizeof(*text) * fp_len + 1

Because that is what you passed to malloc. That is ACTUALLY the size of the buffer pointed to by text.


问:
Removing background color in the form in IE
Am not able to remove the background color in an IFrame so please help me.Am running out of my precious time :-(</p>

答:
Though this is not PHP related, I think you are seeking for an answer as follows. If you have access to editing the content of the page that is being directed to with the iFrame, then you can use a simple CSS property to remove the background. Try adding this to the head of the document:

```<code><style type="text/css">
     body {
         background-color:transparent;
     }
</style>
</code>```

If this page will be accessed at anytime outside of the iFrame, simply set a PHP (if-statement should work if you set a certain variable) to enable/disable this bit of code if it's being accessed by the iFrame page.

In your iframe add this parameter

```<code>allowtransparency="true"
</code>```

So your iframe should look something like this (copied from your page)

```<code><iframe src="http://www.orangerich.info/crm/freetrialform/form.php" height="360" width="320" frameborder="0" scrolling="No" allowtransparency="true"></iframe>
</code>```

Good luck!

Dennis M.

ContentLicense: CC BY-SA 2.5

Body:
Though this is not PHP related, I think you are seeking for an answer as follows. If you have access to editing the content of the page that is being directed to with the iFrame, then you can use a simple CSS property to remove the background. Try adding this to the head of the document:

<style type="text/css">
     body {
         background-color:transparent;
     }
</style>

If this page will be accessed at anytime outside of the iFrame, simply set a PHP (if-statement should work if you set a certain variable) to enable/disable this bit of code if it's being accessed by the iFrame page.

In your iframe add this parameter

allowtransparency="true"

So your iframe should look something like this (copied from your page)

<iframe src="http://www.orangerich.info/crm/freetrialform/form.php" height="360" width="320" frameborder="0" scrolling="No" allowtransparency="true"></iframe>

Good luck!

Dennis M.


问:
Passing Dropdown list Python FLask
Below my html code

```<code><div class="row">
  <div class="col-sm-2">
    <select class="form-control">
      {% for e in get %}
        <option value=" {{ e }} ">{{ e }}</option>
      {% endfor %}
    </select>
  </div>
</div>
</code>```

model.py code

```<code>from dbconnection import connection
def getall():
try:
    c, conn = connection()
    DICT = c.execute('SELECT prog_name FROM programming_language')
    DICT = c.fetchall()
    return DICT
except Exception as e:
    return (str(e))
</code>```

init.py code

```<code>from model import getall
DICT = getall()
@app.route('/')

def homepage():
    return render_template("main.html", get = DICT)
</code>```

it gives me results like this includes open and close parenthesis, comma and apostrophe, it looks like generate itself instead of this python it give me this ('python',) i aims this python.
https://i.stack.imgur.com/3CcZW.png

答:
The parentheses and commas are the way your database query is returning results: each returned record is being returned as a tuple with only one value.

Try adding this line to your getall() function:

```<code>    (...)

    DICT = c.fetchall()
    return [row[0] for row in DICT if len(row) >= 1]
</code>```

Title: Passing Dropdown list Python FLask

Body:
Below my html code

    <select class="form-control">
      {% for e in get %}
        <option value=" {{ e }} ">{{ e }}</option>
      {% endfor %}
    </select>

model.py code

from dbconnection import connection
def getall():
try:
    c, conn = connection()
    DICT = c.execute('SELECT prog_name FROM programming_language')
    DICT = c.fetchall()
    return DICT
except Exception as e:
    return (str(e))

init.py code

from model import getall
DICT = getall()
@app.route('/')

def homepage():
    return render_template("main.html", get = DICT)

it gives me results like this includes open and close parenthesis, comma and apostrophe, it looks like generate itself instead of this python it give me this ('python',) i aims this python.
https://i.stack.imgur.com/3CcZW.png

Body:
The parentheses and commas are the way your database query is returning results: each returned record is being returned as a tuple with only one value.

Try adding this line to your getall() function:

    (...)

    DICT = c.fetchall()
    return [row[0] for row in DICT if len(row) >= 1]


问:
Memoization of member function of Kotlin data class
In the following Kotlin example, I'd like to "memoize" (cache the result of) the member function matches:

```<code>import java.util.regex.Pattern

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    //TODO memoize this
    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }
}

fun main(args: Array<String>) {
    val myData = MyDataClass()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}
</code>```

As far as I can see, Kotlin <= 1.1 doesn't support memoization. Of course, you can write your own memoization function or use a library like e.g. https://github.com/MarioAriasC/funKTionale

Using funKTionale, I don't have to write my own memoization function and came to this solution. Unfortunately it looks "boilerplatey":

```<code>import org.funktionale.memoization.memoize
import java.util.regex.Pattern

data class MyMemoizedDataClassV1(val name: String = "John Doe",
                                 val description: String = "Famous person") {

    private val memoizedMatches: (String, String, String) -> Boolean =
            { name: String, description: String, searchTerm: String ->
                println("Calculating...")
                name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                        || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
            }.memoize()

    fun matches(searchTerm: String): Boolean {
        return memoizedMatches(name, description, searchTerm)
    }
}

fun main(args: Array<String>) {
    val myData = MyMemoizedDataClassV1()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}
</code>```

I think of a nicer looking solution like

```<code>data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }.memoize() //TODO how?
}
</code>```

But, how to achieve this?

答:
You can remove a lot of the boilerplate from your Funktionale code:

```<code>data class MyMemoizedDataClassV1(val name: String = "John Doe",
                                 val description: String = "Famous person") {

    val matches = { searchTerm: String ->
        println("Calculating...")
        name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
           || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }.memoize()

}
</code>```

You have access to name and description from the data class in your lambda, so you don't have to pass them as parameters. Having them as parameters would make the memoize-function use them in the key to lookup the answer, but this is useless because they never change (as they are defined with val).

Also, because matches has the type (String) -> Boolean, you can just expose the function-property directly in your data class, instead of creating another function that calls it. Finally, I removed some types that the compiler can infer.

Body:
In the following Kotlin example, I'd like to "memoize" (cache the result of) the member function matches:

import java.util.regex.Pattern

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    //TODO memoize this
    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }
}

fun main(args: Array<String>) {
    val myData = MyDataClass()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}

As far as I can see, Kotlin <= 1.1 doesn't support memoization. Of course, you can write your own memoization function or use a library like e.g. https://github.com/MarioAriasC/funKTionale

Using funKTionale, I don't have to write my own memoization function and came to this solution. Unfortunately it looks "boilerplatey":

import org.funktionale.memoization.memoize
import java.util.regex.Pattern

data class MyMemoizedDataClassV1(val name: String = "John Doe",
                                 val description: String = "Famous person") {

    private val memoizedMatches: (String, String, String) -> Boolean =
            { name: String, description: String, searchTerm: String ->
                println("Calculating...")
                name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                        || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
            }.memoize()

    fun matches(searchTerm: String): Boolean {
        return memoizedMatches(name, description, searchTerm)
    }
}

fun main(args: Array<String>) {
    val myData = MyMemoizedDataClassV1()
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("John"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
    println(myData.matches("Famous"))
}

I think of a nicer looking solution like

data class MyDataClass(val name: String = "John Doe",
                       val description: String = "Famous person") {

    fun matches(searchTerm: String): Boolean {
        println("Calculating...")
        return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
                || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }.memoize() //TODO how?
}

But, how to achieve this?

Body:
You can remove a lot of the boilerplate from your Funktionale code:

data class MyMemoizedDataClassV1(val name: String = "John Doe",
                                 val description: String = "Famous person") {

    val matches = { searchTerm: String ->
        println("Calculating...")
        name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
           || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex())
    }.memoize()

}

You have access to name and description from the data class in your lambda, so you don't have to pass them as parameters. Having them as parameters would make the memoize-function use them in the key to lookup the answer, but this is useless because they never change (as they are defined with val).

Also, because matches has the type (String) -> Boolean, you can just expose the function-property directly in your data class, instead of creating another function that calls it. Finally, I removed some types that the compiler can infer.


问:
CSS3 :Iframe not taking 100% height
I have 2 bootstrap columns.

in the first column there is a fixed position div. and in the 2nd column I have an iframe div.
I have given iframe height="100%" but it is not taking 100% of the browser.

.left_side_div{
  width:25%;
  min-height:100%;
  background : #FFFFFF;
  position:fixed;
  top:0;
  left:0;
  bottom:0;
  border:thin black solid;
}

.iframe_div{
  width:100%;
  height:100%;
  border:thin black solid;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="row">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
  <div class="left_side_div"></div>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-9">
  <div class="iframe_div">
    <iframe src="http://google.co.in/" width="100%" height="100%"></iframe>
  </div>
</div>
</div></code>```

Here is JSFiddle

Any help would be great.

Thank You.

答: don't use % for height insted use 100vh. </p>

Title: CSS3 :Iframe not taking 100% height

Body:
I have 2 bootstrap columns.

in the first column there is a fixed position div. and in the 2nd column I have an iframe div.
I have given iframe height="100%" but it is not taking 100% of the browser.

.left_side_div{
  width:25%;
  min-height:100%;
  background : #FFFFFF;
  position:fixed;
  top:0;
  left:0;
  bottom:0;
  border:thin black solid;
}

.iframe_div{
  width:100%;
  height:100%;
  border:thin black solid;

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Here is JSFiddle

Any help would be great.

Thank You.


问:
template for a smartpointer and auto deletion of the pointer
I have come across this simple code in a website. I didn't understand it fully. It would be very helpful for me if someone can breakdown the code line by line and explain.

This is a code for creating a template of a smart pointer (auto deletion of pointer is the main motto to create such a pointer)

```<code>#include <iostream>
using namespace std;

template <class T>
class SmartPtr {
    T* ptr;

public:
    explicit SmartPtr(T* p = NULL) {
        ptr = p;
    }
    ~SmartPtr() {
        delete(ptr);
    }
    T& operator*() {
        return *ptr;
    }
    T* operator->() {
        return ptr;
    }
};

int main() {
    SmartPtr<int> ptr(new int());
    *ptr = 20;

    cout << *ptr;
    return 0;
}
</code>```

答:
Your class SmartPtr encapsulates a pointer of type T and overloads the member access and dereference operators to allow access to the encapsulated pointer. Moreover it frees up the the allocated memory pointed by encapsulated pointer when its descructor is called.

Your class with commens:

```<code>template <class T>
class SmartPtr {
    T* ptr; // encapsulated pointer of type T

public:
    // constructor for SmartPtr class which assigns the specified pointer to the
    // encapsulated pointer
    explicit SmartPtr(T* p = NULL) {
        ptr = p;
    }
    // destructor for SmartPtr class which frees up the the allocated memory
    // pointed by the encapsulated pointer
    ~SmartPtr() {
        delete(ptr);
    }
    // overloads the dereference operator for SmartPtr class to allow syntax
    // like: *instance = value;
    T& operator*() {
        return *ptr;
    }
    // overloads the member access operator for SmartPtr class to allow syntax
    // like: instance->member();
    T* operator->() {
        return ptr;
    }
};
</code>```

Usage of your SmartPtr class is show inside the main function you provided:

```<code>SmartPtr<int> ptr(new int());
*ptr = 20;
</code>```

The first line does a class template instantiation and constructs an object (ptr) by calling the contructor with newly created int as parameter.

The second line calls the overloaded dereference operator and assigns value 20 to the encapsulated pointer. This line is equivalent to:

```<code>ptr.operator*() = 20;
</code>```

Body:
I have come across this simple code in a website. I didn't understand it fully. It would be very helpful for me if someone can breakdown the code line by line and explain.

This is a code for creating a template of a smart pointer (auto deletion of pointer is the main motto to create such a pointer)

#include <iostream>
using namespace std;

template <class T>
class SmartPtr {
    T* ptr;

public:
    explicit SmartPtr(T* p = NULL) {
        ptr = p;
    }
    ~SmartPtr() {
        delete(ptr);
    }
    T& operator*() {
        return *ptr;
    }
    T* operator->() {
        return ptr;
    }
};

int main() {
    SmartPtr<int> ptr(new int());
    *ptr = 20;

    cout << *ptr;
    return 0;
}

Body:
Your class SmartPtr encapsulates a pointer of type T and overloads the member access and dereference operators to allow access to the encapsulated pointer. Moreover it frees up the the allocated memory pointed by encapsulated pointer when its descructor is called.

Your class with commens:

template <class T>
class SmartPtr {
    T* ptr; // encapsulated pointer of type T

public:
    // constructor for SmartPtr class which assigns the specified pointer to the
    // encapsulated pointer
    explicit SmartPtr(T* p = NULL) {
        ptr = p;
    }
    // destructor for SmartPtr class which frees up the the allocated memory
    // pointed by the encapsulated pointer
    ~SmartPtr() {
        delete(ptr);
    }
    // overloads the dereference operator for SmartPtr class to allow syntax
    // like: *instance = value;
    T& operator*() {
        return *ptr;
    }
    // overloads the member access operator for SmartPtr class to allow syntax
    // like: instance->member();
    T* operator->() {
        return ptr;
    }
};

Usage of your SmartPtr class is show inside the main function you provided:

SmartPtr<int> ptr(new int());
*ptr = 20;

The first line does a class template instantiation and constructs an object (ptr) by calling the contructor with newly created int as parameter.

The second line calls the overloaded dereference operator and assigns value 20 to the encapsulated pointer. This line is equivalent to:

ptr.operator*() = 20;


问:
Check if a pointer points to a valid structure
I have N statically allocated structures.

```<code>struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */
</code>```

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

答:
You can only check if pointer is valid by doing pointer != NULL because anything except `NULL' is treated by valid pointer.

In your case, to check if your pointer points to any of your array entry, you can only do this:

```<code>size_t i = 0;
int isValid = 0;
for (i = 0; i < N; i++) {
    if (test_ptr == &array[i]) {
        isValid = 1;
        break;
    }
}

if (isValid) {
    //Pointer points to one of your array entry
}
</code>```

But in general, you cannot just test if pointer points to specific valid location for you. It is up to you to take care of where it points. It can also have NON-NULL value but points to invalid location, for example:

```<code>int* ptr = malloc(10); //Now points to allocated memory
*ptr = 10;
free(ptr);  //Free memory
*ptr = 10;  //Undefined behaviour, it still points to the same address but
            //we don't know what will happen. Depends on implementation
</code>```

Body:
I have N statically allocated structures.

struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

Body:
You can only check if pointer is valid by doing pointer != NULL because anything except `NULL' is treated by valid pointer.

In your case, to check if your pointer points to any of your array entry, you can only do this:

size_t i = 0;
int isValid = 0;
for (i = 0; i < N; i++) {
    if (test_ptr == &array[i]) {
        isValid = 1;
        break;
    }
}

if (isValid) {
    //Pointer points to one of your array entry
}

But in general, you cannot just test if pointer points to specific valid location for you. It is up to you to take care of where it points. It can also have NON-NULL value but points to invalid location, for example:

int* ptr = malloc(10); //Now points to allocated memory
*ptr = 10;
free(ptr);  //Free memory
*ptr = 10;  //Undefined behaviour, it still points to the same address but
            //we don't know what will happen. Depends on implementation


问:
http call not triggering in promise callback angular 2
In my angular 2 project I make this call to get some data:

```<code>this.http.getfromgraphql()
      .map((response: Response) => response.json())
      .subscribe(
        (data) => {
          console.log(data);
        });
</code>```

This triggers the getfromgraphql function shown below, before I make that call though, I have to check if the access token is still valid in checkaccesstokenvalidity, there I set some variables and resolve the function.

the console logs 'in then' but my http post does not trigger.

Why is that?

Also, I am sure there is a better way to do this, but for the life of me I can't figure it out, a better solution is much appreciated

```<code>checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    // if(!this.access_token) {
    return new Promise((resolve, reject) => {
      this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .subscribe(function(response) {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
          },
          error => console.log("Error: ", error),
          function() {
            console.log('resolving');
            resolve();
          });

    });
    // }
  }
  getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity().then(function() {
      console.log('in then');
      //noinspection TypeScriptValidateTypes
      return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    });
  }
</code>```

答:
I dont understand why you are doing this.http.getfromgraphql() but for other
code in reactive way its like this :

```<code>checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    return this.http
               .post(this.URL + 'oauth/token', this.authentication, options)
               .map(response => {
                   this.authObj = response.json();
                   this.expirationDate
                      .setSeconds((new Date())
                      .getSeconds() + this.authObj.expires_in);
               });
      }

getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity()
        .switchMap(token =>  this.http
               .post(this.URL + '/api/v1/graphql', this.query, options)
 }
</code>```

And the way you call this method is

```<code>someService.getfromgraphql()
           .subscribe(response=> {
// ....
});
</code>```

Body:
In my angular 2 project I make this call to get some data:

this.http.getfromgraphql()
      .map((response: Response) => response.json())
      .subscribe(
        (data) => {
          console.log(data);
        });

This triggers the getfromgraphql function shown below, before I make that call though, I have to check if the access token is still valid in checkaccesstokenvalidity, there I set some variables and resolve the function.

the console logs 'in then' but my http post does not trigger.

Why is that?

Also, I am sure there is a better way to do this, but for the life of me I can't figure it out, a better solution is much appreciated

checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    // if(!this.access_token) {
    return new Promise((resolve, reject) => {
      this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .subscribe(function(response) {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
          },
          error => console.log("Error: ", error),
          function() {
            console.log('resolving');
            resolve();
          });

    });
    // }
  }
  getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity().then(function() {
      console.log('in then');
      //noinspection TypeScriptValidateTypes
      return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    });
  }

Body:
I dont understand why you are doing this.http.getfromgraphql() but for other
code in reactive way its like this :

checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    return this.http
               .post(this.URL + 'oauth/token', this.authentication, options)
               .map(response => {
                   this.authObj = response.json();
                   this.expirationDate
                      .setSeconds((new Date())
                      .getSeconds() + this.authObj.expires_in);
               });
      }

getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity()
        .switchMap(token =>  this.http
               .post(this.URL + '/api/v1/graphql', this.query, options)
 }

And the way you call this method is

someService.getfromgraphql()
           .subscribe(response=> {
// ....
});


问:
Reading positional parameters using PHP
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

```<code>#!/usr/bin/php
<?php

$myfile="balexp.xml";
</code>```

The following does not work in this php page and does work in the shell script.

```<code>myvar=$1
</code>```

How do I pass variables to a php page?

答:
```<code>#!/usr/bin/php
<?php

$myfile=$argv[1];
</code>```

See $argv for more.

Title: Reading positional parameters using PHP

Body:
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

#!/usr/bin/php
<?php

$myfile="balexp.xml";

The following does not work in this php page and does work in the shell script.

myvar=$1

How do I pass variables to a php page?

Body:
#!/usr/bin/php
<?php

$myfile=$argv[1];

See $argv for more.


问:
How to configure bean validation programatically?
Codes where i want to use bean validation:

```<code>@Inject
private ValidatorFactory validatorFactory;
....

public Response create(@Context HttpServletRequest request) {
        ...
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}

public Response update(@Context HttpServletRequest request) {
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}
</code>```

UserDTO:

```<code>public class UserDTO {
    private Integer id;
    private String userName;
    @NotNull(message = "is missing")
    private String locked;
    @Email(message = "email is not valid")
    private String email;
    @NotNull(message = "countryCode is missing")
    private String countryCode;
    ...getters-setters more variables...
}
</code>```

So i have a post Http method where i want to create a user...bean validation is working if missing countrycode or locked  ok or if email not valid ok...But when i want to just update for example email the validation is also run on the whole dto class...so the question is can i and how can i configure  not to run on every variable each time?

答: You should use Validator::validateProperty to check specifc properties. You can also group them and check it via Validator::validate (see here for tutorial) if there are more than one property.

Body:
Codes where i want to use bean validation:

@Inject
private ValidatorFactory validatorFactory;
....

public Response create(@Context HttpServletRequest request) {
        ...
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}

public Response update(@Context HttpServletRequest request) {
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}

UserDTO:

public class UserDTO {
    private Integer id;
    private String userName;
    @NotNull(message = "is missing")
    private String locked;
    @Email(message = "email is not valid")
    private String email;
    @NotNull(message = "countryCode is missing")
    private String countryCode;
    ...getters-setters more variables...
}

So i have a post Http method where i want to create a user...bean validation is working if missing countrycode or locked  ok or if email not valid ok...But when i want to just update for example email the validation is also run on the whole dto class...so the question is can i and how can i configure  not to run on every variable each time?


问:
How to check the overlapping time intervals from one type 2 SCD dimension
I have one problem identifying and fixing some records having overlapping time intervals, for one scd type 2 dimension.
   What I have is:

```<code>Bkey   Uid  startDate                       endDate
'John'  1   1990-01-01 (some time stamp)    2017-01-10 (some time stamp)
'John'  2   2016-11=03 (some time stamp)    2016-11-14 (some time stamp)
'John'  3   2016-11-14 (some time stamp)    2016-12-29 (some time stamp)
'John'  4   2016-12-29 (some time stamp)    2017-01-10 (some time stamp)
'John'  5   2017-01-10 (some time stamp)    2017-04-22 (some time stamp)
......
</code>```

I want to find (first) which are all the Johns having overlapping time periods, for a table having lots and lots of Johns and then to figure out a way to correct those overlapping time periods. For the latest I know there are some function LAGG, LEAD, which can handle that, but it eludes me how to find those over lappings.
Any hints?
Regards,

答:
I think the tricky part of your query is being able to articulate the logic for overlapping ranges.  We can self join on the condition that a row on the left overlaps with any row on the right.  All matching rows are those which overlap.

We can think of four possible overlap scenarios:

```<code>|---------|   |---------|    no overlap

|---------|
       |---------|           1st end and 2nd start overlap

       |---------|
 |---------|                 1st start and 2nd end overlap

 |---------|
    |---|                    2nd completely contained inside 1st
                             (could be 1st inside 2nd also)

SELECT DISTINCT
    t.Uid
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.startDate <= t2.endDate AND
       t2.startDate <= t1.endDate
WHERE
    t1.Bkey = 'John' AND t2.Bkey = 'John'
</code>```

This will at least let you identify overlapping records.  Updating and separating them in a meaningful way will probably end up being an ugly gaps and islands problem, perhaps meriting another question.

Body:
I have one problem identifying and fixing some records having overlapping time intervals, for one scd type 2 dimension.
   What I have is:

Bkey   Uid  startDate                       endDate
'John'  1   1990-01-01 (some time stamp)    2017-01-10 (some time stamp)
'John'  2   2016-11=03 (some time stamp)    2016-11-14 (some time stamp)
'John'  3   2016-11-14 (some time stamp)    2016-12-29 (some time stamp)
'John'  4   2016-12-29 (some time stamp)    2017-01-10 (some time stamp)
'John'  5   2017-01-10 (some time stamp)    2017-04-22 (some time stamp)
......

I want to find (first) which are all the Johns having overlapping time periods, for a table having lots and lots of Johns and then to figure out a way to correct those overlapping time periods. For the latest I know there are some function LAGG, LEAD, which can handle that, but it eludes me how to find those over lappings.
Any hints?
Regards,

Body:
I think the tricky part of your query is being able to articulate the logic for overlapping ranges.  We can self join on the condition that a row on the left overlaps with any row on the right.  All matching rows are those which overlap.

We can think of four possible overlap scenarios:

|---------|   |---------|    no overlap

|---------|
       |---------|           1st end and 2nd start overlap

       |---------|
 |---------|                 1st start and 2nd end overlap

 |---------|
    |---|                    2nd completely contained inside 1st
                             (could be 1st inside 2nd also)

SELECT DISTINCT
    t.Uid
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.startDate <= t2.endDate AND
       t2.startDate <= t1.endDate
WHERE
    t1.Bkey = 'John' AND t2.Bkey = 'John'

This will at least let you identify overlapping records.  Updating and separating them in a meaningful way will probably end up being an ugly gaps and islands problem, perhaps meriting another question.


问:
Add ONLY checked items from a checklistbox to a listView control
My situation:

I have a populated checklistbox control on Form1.
Then I have a listView control on Form2.

I would like for the user to be able to check items on the checklistbox on Form1, then click on a button on Form1 to open Form2.

Form2 contains the listView control, that I want to populate with only the checked items from checklistbox on Form1.

I tried

```<code>namespace Boodschappenlijst
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    public static string[] strKruideniersw = new string[] { Boodschappenlijst.producten[0], Boodschappenlijst.producten[1], Boodschappenlijst.producten[2] };
    public static string[] strVerswaren = new string[] { Boodschappenlijst.producten[3], Boodschappenlijst.producten[4], Boodschappenlijst.producten[5] };
    public static string[] strVerzorgingspr = new string[] { Boodschappenlijst.producten[6], Boodschappenlijst.producten[7], Boodschappenlijst.producten[8], Boodschappenlijst.producten[9] };

    public static List<string> kruidenierswList = new List<string>(strKruideniersw);
    public static List<string> verswarenList = new List<string>(strVerswaren);
    public static List<string> verzproductenList = new List<string>(strVerzorgingspr);

    public static string[] strKruidenierswCh;

    public void Form1_Load(object sender, EventArgs e)
    {
        clbKruidenierswaren.Items.AddRange(strKruideniersw);
        clbVerswaren.Items.AddRange(strVerswaren);
        clbVerzproducten.Items.AddRange(strVerzorgingspr);
        strKruidenierswCh = clbKruidenierswaren.CheckedItems;
    }

    // TODO
    // public string kruidenierswChecked = clbKruidenierswaren.CheckedItems;

    private void button1_Click(object sender, EventArgs e)
    {
        // Create a new instance of the Form2 class
        Form2 form2 = new Form2();

        // Show the settings form
        form2.Show();
    }
}

public abstract class Boodschappenlijst : Form1
{
    public static string[] producten = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };

    // Not working.. clbKruidenierswaren is not static.
    List<string> items = clbKruidenierswaren.CheckedItems.Cast<string>().ToList();

    // Make form1 controls accessible for other classes?
    // Form1 form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();

}
}
</code>```

but the I get the error

A field initializer cannot reference the non-static field, method, or property 'Form1.clbKruidenierswaren'.

Can you please direct me to a solution that works?

答:
You should make a constructor in the class like this:

Class itself:

```<code>public class Boodschappenlijst
{
    public static string[] producten { get; set; } = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };
    private List<string> Items { get; set; }

    public Boodschappenlijst(List<string> items)// << Constructor
    {
        Items = items;
    }
}
</code>```

And then make an instance the class like so:

On the place (Form?) you have clbKruidenierswaren:

```<code>Boodschappenlijst boodschappenLijst =
           new Boodschappenlijst(clbKruidenierswaren.CheckedItems.Cast<string>().ToList());
</code>```

Body:
My situation:

I have a populated checklistbox control on Form1.
Then I have a listView control on Form2.

I would like for the user to be able to check items on the checklistbox on Form1, then click on a button on Form1 to open Form2.

Form2 contains the listView control, that I want to populate with only the checked items from checklistbox on Form1.

I tried

namespace Boodschappenlijst
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    public static string[] strKruideniersw = new string[] { Boodschappenlijst.producten[0], Boodschappenlijst.producten[1], Boodschappenlijst.producten[2] };
    public static string[] strVerswaren = new string[] { Boodschappenlijst.producten[3], Boodschappenlijst.producten[4], Boodschappenlijst.producten[5] };
    public static string[] strVerzorgingspr = new string[] { Boodschappenlijst.producten[6], Boodschappenlijst.producten[7], Boodschappenlijst.producten[8], Boodschappenlijst.producten[9] };

    public static List<string> kruidenierswList = new List<string>(strKruideniersw);
    public static List<string> verswarenList = new List<string>(strVerswaren);
    public static List<string> verzproductenList = new List<string>(strVerzorgingspr);

    public static string[] strKruidenierswCh;

    public void Form1_Load(object sender, EventArgs e)
    {
        clbKruidenierswaren.Items.AddRange(strKruideniersw);
        clbVerswaren.Items.AddRange(strVerswaren);
        clbVerzproducten.Items.AddRange(strVerzorgingspr);
        strKruidenierswCh = clbKruidenierswaren.CheckedItems;
    }

    // TODO
    // public string kruidenierswChecked = clbKruidenierswaren.CheckedItems;

    private void button1_Click(object sender, EventArgs e)
    {
        // Create a new instance of the Form2 class
        Form2 form2 = new Form2();

        // Show the settings form
        form2.Show();
    }
}

public abstract class Boodschappenlijst : Form1
{
    public static string[] producten = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };

    // Not working.. clbKruidenierswaren is not static.
    List<string> items = clbKruidenierswaren.CheckedItems.Cast<string>().ToList();

    // Make form1 controls accessible for other classes?
    // Form1 form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();

}
}

but the I get the error

A field initializer cannot reference the non-static field, method, or property 'Form1.clbKruidenierswaren'.

Can you please direct me to a solution that works?

Body:
You should make a constructor in the class like this:

Class itself:

public class Boodschappenlijst
{
    public static string[] producten { get; set; } = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };
    private List<string> Items { get; set; }

    public Boodschappenlijst(List<string> items)// << Constructor
    {
        Items = items;
    }
}

And then make an instance the class like so:

On the place (Form?) you have clbKruidenierswaren:

Boodschappenlijst boodschappenLijst =
           new Boodschappenlijst(clbKruidenierswaren.CheckedItems.Cast<string>().ToList());


问:
Spring Tool Suite error when running as java app
I'm learning Spring Boot using STS and following a tutorial on Udemy. I'm getting the following error when trying to run the app as a java application. I have looked at other similar posts and nothing seems to be new. Most of the questions are from 3-5 years ago. I have attempted putting some dependencies in my pom but it gave me more errors than I began with so i removed them.

The error is:
Failed to load class "org.slf4j.impl.StaticLoggerBinder"

here is my pom.xml:

```<code><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.in28minutes.springboot</groupId>
<artifactId>first-springboot-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>
</code>```

Here is what i was trying to run:

```<code>package com.in28minutes.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(Application.class,
    args);

    }

}
</code>```

Does anyone have a suggestion to what I can do to fix this? Do I bind? The original example code can be found here at the instructor's repo: https://github.com/in28minutes/SpringBootForBeginners/blob/master/Step01.md

答:
I'm not use STS but following from this docs you should run your app as Spring Boot App since you're using Spring Boot.
But your error it's seems because dependency error, if you familiar with command line I suggest you to perform mvn clean install before run your Spring project to make sure all the dependency is downloaded.

Another tips, if you're good with command line try to execute mvn spring-boot:run on your project directory and it will execute your Spring project.

Body:
I'm learning Spring Boot using STS and following a tutorial on Udemy. I'm getting the following error when trying to run the app as a java application. I have looked at other similar posts and nothing seems to be new. Most of the questions are from 3-5 years ago. I have attempted putting some dependencies in my pom but it gave me more errors than I began with so i removed them.

The error is:
Failed to load class "org.slf4j.impl.StaticLoggerBinder"

here is my pom.xml:

<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.in28minutes.springboot</groupId>
<artifactId>first-springboot-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>

Here is what i was trying to run:

package com.in28minutes.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(Application.class,
    args);

    }

}

Does anyone have a suggestion to what I can do to fix this? Do I bind? The original example code can be found here at the instructor's repo: https://github.com/in28minutes/SpringBootForBeginners/blob/master/Step01.md


问:
How to find out if ComboBox item is in dropdown list or inside it
I want selected item in ComboBox look differently from it's instance in drop down list.

```<code>    <ComboBox ItemsSource="{Binding ViewList}" SelectedItem="{Binding SelectedView}">
        <ComboBox.Resources>
            <DataTemplate DataType="{x:Type vm:View}">
                <StackPanel Orientation="Horizontal">
                    <c:Icon x:Name="Icon" IconShape="{DynamicResource z.Users}" Margin="5,0" Background="{Binding Foreground, RelativeSource={RelativeSource Self}}"/>
                    <StackPanel>
                        <StackPanel>
                            <TextBlock x:Name="CurrentView" Text="Current View"
                                       Foreground="{DynamicResource Pallete.Primary.Brighter}"
                                       Visibility="{Binding IsSelected, Converter={StaticResource bool2VisibilityConverter}}"/>
                            <TextBlock x:Name="Title" Text="{Binding Title}"/>
                        </StackPanel>
                    </StackPanel>
                </StackPanel>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding Type}" Value="SeparatorView">
                        <Setter TargetName="Icon" Property="Visibility" Value="Collapsed"/>
                        <Setter TargetName="Title" Property="FontWeight" Value="Bold"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Type}" Value="YearView">
                        <Setter TargetName="Icon" Property="IconShape" Value="{DynamicResource z.Bookmark}"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ComboBox.Resources>
    </ComboBox>
</code>```

Is there something I could use in CurrentView's Visibility Property or in triggers?

答:
Here is an example of your you could modify the Foreground of a TextBlock when it it is selected in the ComboBox using a DataTrigger:

```<code><ComboBox ItemsSource="{Binding ListOfStrings}">
    <ComboBox.Resources>
        <DataTemplate DataType="{x:Type sys:String}">
            <TextBlock x:Name="txt" Text="{Binding}" Foreground="Red" />
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="{x:Null}">
                    <Setter TargetName="txt" Property="Foreground" Value="Green"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ComboBox.Resources>
</ComboBox>
</code>```

I believe that the following is what you are looking for:

```<code><DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="{x:Null}">
</code>```

Body:
I want selected item in ComboBox look differently from it's instance in drop down list.

    <ComboBox ItemsSource="{Binding ViewList}" SelectedItem="{Binding SelectedView}">
        <ComboBox.Resources>
            <DataTemplate DataType="{x:Type vm:View}">
                <StackPanel Orientation="Horizontal">
                    <c:Icon x:Name="Icon" IconShape="{DynamicResource z.Users}" Margin="5,0" Background="{Binding Foreground, RelativeSource={RelativeSource Self}}"/>
                    <StackPanel>
                        <StackPanel>
                            <TextBlock x:Name="CurrentView" Text="Current View"
                                       Foreground="{DynamicResource Pallete.Primary.Brighter}"
                                       Visibility="{Binding IsSelected, Converter={StaticResource bool2VisibilityConverter}}"/>
                            <TextBlock x:Name="Title" Text="{Binding Title}"/>
                        </StackPanel>
                    </StackPanel>
                </StackPanel>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding Type}" Value="SeparatorView">
                        <Setter TargetName="Icon" Property="Visibility" Value="Collapsed"/>
                        <Setter TargetName="Title" Property="FontWeight" Value="Bold"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Type}" Value="YearView">
                        <Setter TargetName="Icon" Property="IconShape" Value="{DynamicResource z.Bookmark}"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ComboBox.Resources>
    </ComboBox>

Is there something I could use in CurrentView's Visibility Property or in triggers?

Body:
Here is an example of your you could modify the Foreground of a TextBlock when it it is selected in the ComboBox using a DataTrigger:

<ComboBox ItemsSource="{Binding ListOfStrings}">
    <ComboBox.Resources>
        <DataTemplate DataType="{x:Type sys:String}">
            <TextBlock x:Name="txt" Text="{Binding}" Foreground="Red" />
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="{x:Null}">
                    <Setter TargetName="txt" Property="Foreground" Value="Green"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ComboBox.Resources>
</ComboBox>

I believe that the following is what you are looking for:

<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="{x:Null}">


问:
Can I host two separate web servers on a LAN to the outside world through 1 IP address?
I am a web programmer with a home web dev operation. I have multiple web servers in my house on a FIOS connection. I have my own domain pointed to my router through dyndns.org's custom domain service.

My ISP gives me ONE static IP address, which at the moment allows me to configure my router to direct outbound web traffic from one server through port 80 and another server through port 8080. This sucks because many companies block port 8080 these days causing some of my corporate clients to not be able to hit my second web server.

Is there any way for me to direct regular old port 80 web traffic to TWO SEPARATE web servers internally on my network using two separate host names?

For instance. I want http://webserver1.mydomain.com to hit one web server on my network, and http://webserver2.mydomain.com to hit another web server and have both sets of traffic served on port 80.

Is this even possible? If not, can I do a hack by programmatically routing traffic from one web server transparently to another?

For the record I run MS Windows Server 2008 IIS 7.0 stack, a D-link DIR-655 router, and use DynDNS for my domain needs.

答:
Some sort of application layer routing could be your option. This article points to how to do it on ISA server (using web rules)

http://www.codinghorror.com/blog/archives/000984.html

OwnerDisplayName: Matias Nino

OwnerDisplayName: Midhat


问:
Issue in generating Oauth Client and requesting access token via code in Laravel Passport
I am using Passport Authentication API in Laravel 5.3. I have created two routes one for generating oauth clients and second for requesting access_token. But I am getting NULL value from /gen_client route and showing login page from /redirect route.

Can anyone please help me in this?

```<code>Route::get('/gen_client', function () {
    $http = new GuzzleHttp\Client();
    $response = $http->post(url('/') . '/oauth/clients', [
        'form_params' => [
            'id' => 'ok@test.com',
            'name' => 'OK',
            'redirect' => url('/') . '/callback'
        ],
    ]);
    $response_body = json_decode((string)$response->getBody(), true);
    var_dump($response_body);
});

Route::get('/redirect', function () {
    $oauth_client = DB::table('oauth_clients')->where('id', '=', 'ok@test.com')->first();
    $query = http_build_query([
        'client_id' => $oauth_client->id,
        'redirect_uri' => $oauth_client->redirect,
        'response_type' => 'code',
        'scope' => '',
    ]);

    return redirect(url('/') . '/oauth/authorize?'.$query);
});

Route::post('callback', function (Request $request) {
    $http = new GuzzleHttp\Client();
    $oauth_client = DB::table('oauth_clients')->where('id', '=', 'ok@test.com')->first();
    $response = $http->post(url('/') . '/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => $oauth_client->id,
            'client_secret' => $oauth_client->secret,
            'redirect_uri' => url('/') . '/callback',
            'code' => $request->code,
        ],
    ]);
    $response_body = json_decode((string)$response->getBody(), true);
    var_dump($response_body);
    $access_token = $response_body['access_token'] ;
    $refresh_token = $response_body['refresh_token'];
}
</code>```

);

答:
Your gen_client route is returning nothing, therefore it will return NULL.

You are also confusing things somewhat by trying to introduce your own ID and use the oauth_clients table directly.

The call to POST /oauth/clients will return a payload which includes the client's ID and Secret.

You then put those values into config somewhere, and use them like this (along with other parameters required for the call you're making):

```<code>[
    'client_id' => config('services.myoauth.client_id'),
    'client_secret' => config('services.myoauth.client_secret'),
]
</code>```

Don't access the oauth_clients tables directly, that's the OAuth server's job.

Creating clients is (usually) a manual thing that is done once when connecting an OAuth client webapp to an OAuth server.

Body:
I am using Passport Authentication API in Laravel 5.3. I have created two routes one for generating oauth clients and second for requesting access_token. But I am getting NULL value from /gen_client route and showing login page from /redirect route.

Can anyone please help me in this?

Route::get('/gen_client', function () {
    $http = new GuzzleHttp\Client();
    $response = $http->post(url('/') . '/oauth/clients', [
        'form_params' => [
            'id' => 'ok@test.com',
            'name' => 'OK',
            'redirect' => url('/') . '/callback'
        ],
    ]);
    $response_body = json_decode((string)$response->getBody(), true);
    var_dump($response_body);
});

Route::get('/redirect', function () {
    $oauth_client = DB::table('oauth_clients')->where('id', '=', 'ok@test.com')->first();
    $query = http_build_query([
        'client_id' => $oauth_client->id,
        'redirect_uri' => $oauth_client->redirect,
        'response_type' => 'code',
        'scope' => '',
    ]);

    return redirect(url('/') . '/oauth/authorize?'.$query);
});

Route::post('callback', function (Request $request) {
    $http = new GuzzleHttp\Client();
    $oauth_client = DB::table('oauth_clients')->where('id', '=', 'ok@test.com')->first();
    $response = $http->post(url('/') . '/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => $oauth_client->id,
            'client_secret' => $oauth_client->secret,
            'redirect_uri' => url('/') . '/callback',
            'code' => $request->code,
        ],
    ]);
    $response_body = json_decode((string)$response->getBody(), true);
    var_dump($response_body);
    $access_token = $response_body['access_token'] ;
    $refresh_token = $response_body['refresh_token'];
}

);

Body:
Your gen_client route is returning nothing, therefore it will return NULL.

You are also confusing things somewhat by trying to introduce your own ID and use the oauth_clients table directly.

The call to POST /oauth/clients will return a payload which includes the client's ID and Secret.

You then put those values into config somewhere, and use them like this (along with other parameters required for the call you're making):

[
    'client_id' => config('services.myoauth.client_id'),
    'client_secret' => config('services.myoauth.client_secret'),
]

Don't access the oauth_clients tables directly, that's the OAuth server's job.

Creating clients is (usually) a manual thing that is done once when connecting an OAuth client webapp to an OAuth server.


问:
Can't see Admob events in Firebase Analytics
I have followed this tutorial: https://support.google.com/firebase/answer/7378163 and tried to integrate Admob and Firebase Analytics but I can't see any events (ad_click, ad_impression) in Debug View (as described in verify section).

I have tried with both 11.0.1 version and 10.2.3 (beta) with no success (for Firebase Analytics SDK and Mobile Ads SDK dependencies).

I have also added exception (keep) to Proguard file for FirebaseAnalytics and AppMeasurement.

Admob is correctly linked with Firebase - I know that because I already can see some data from Admob in Firebase Analytics in production where I use version 10.2.6.

Is there a reason why this still wouldn't work?

答:
Reply from Firebase support regarding missing Admob events in Firebase Analytics:
"I just heard back from our engineers. They've confirmed that you've configured things correctly, but we're still in the midst of rolling out this functionality, which is why you're only seeing a portion of the traffic. In the near term though, we expect the metrics to converge. "

When I specifically asked about why I don't see events at least in DebugView:
"Same cause - not all devices have this functionality enabled at this time and thus ad_click/ad_impression events are not logged."


问:
pip is showing error 'lsb_release -a' returned non-zero exit status 1
I am trying to install packages using pip and it is throwing error.

Command that I have used,

```<code>sudo pip install selenium
</code>```

The error it is showing,

```<code>Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 272, in run
    with self._build_session(options) as session:
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 72, in _build_session
    insecure_hosts=options.trusted_hosts,
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 329, in __init__
    self.headers["User-Agent"] = user_agent()
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 93, in user_agent
    from pip._vendor import distro
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 1050, in <module>
    _distro = LinuxDistribution()
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 594, in __init__
    if include_lsb else {}
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info
    raise subprocess.CalledProcessError(code, cmd, stdout)
CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 1
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 233, in main
    return command.main(cmd_args)
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 251, in main
    timeout=min(5, options.timeout)) as session:
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 72, in _build_session
    insecure_hosts=options.trusted_hosts,
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 329, in __init__
    self.headers["User-Agent"] = user_agent()
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 93, in user_agent
    from pip._vendor import distro
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 1050, in <module>
    _distro = LinuxDistribution()
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 594, in __init__
    if include_lsb else {}
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info
    raise subprocess.CalledProcessError(code, cmd, stdout)
subprocess.CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 1
</code>```

I have searched everywhere, but there is no solution for this problem. It started behaving like this recently. Also, Software Updater stopped working. Not sure if it is related to that. I am using Ubuntu 14.04 LTS and python 2.X

答:
Ahhh the classic lsb_release issue. I have battled this problem many times. The issue is that your default Python implementation is trying to use Python 3 but lsb_release requires Python 2. To fix this problem do the following:

Open /usr/bin/lsb_release (Make sure you use sudo or open as root!)

Edit the first line to be #! /usr/bin/python2.7

Save the file

now you can use pip again and everything should be fine.

UPDATE May 2019: Newer versions of Linux are shipping with Python3 by default. As noted in the comments here, you may just need to use a specific version of Python 3.

Body:
I am trying to install packages using pip and it is throwing error.

Command that I have used,

sudo pip install selenium

The error it is showing,

Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 272, in run
    with self._build_session(options) as session:
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 72, in _build_session
    insecure_hosts=options.trusted_hosts,
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 329, in __init__
    self.headers["User-Agent"] = user_agent()
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 93, in user_agent
    from pip._vendor import distro
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 1050, in <module>
    _distro = LinuxDistribution()
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 594, in __init__
    if include_lsb else {}
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info
    raise subprocess.CalledProcessError(code, cmd, stdout)
CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 1
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 233, in main
    return command.main(cmd_args)
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 251, in main
    timeout=min(5, options.timeout)) as session:
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 72, in _build_session
    insecure_hosts=options.trusted_hosts,
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 329, in __init__
    self.headers["User-Agent"] = user_agent()
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 93, in user_agent
    from pip._vendor import distro
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 1050, in <module>
    _distro = LinuxDistribution()
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 594, in __init__
    if include_lsb else {}
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info
    raise subprocess.CalledProcessError(code, cmd, stdout)
subprocess.CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 1

I have searched everywhere, but there is no solution for this problem. It started behaving like this recently. Also, Software Updater stopped working. Not sure if it is related to that. I am using Ubuntu 14.04 LTS and python 2.X

ContentLicense: CC BY-SA 4.0


问:
var in class gives error

Possible Duplicate:

  Using var outside of a method

```<code>class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
</code>```

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

答:
You can argue that the intent is quite obvious if you would write var _users = new List<User>() as a field declaration.

The problem is that not all field declarations contains an assignment which is required to infer the type. (You might want to initialize a field through the constructor)

Mixing both var and normal type declarations would look like a nasty soup. Therefore it's not possible.

(at least that's my guess)

Title: var in class gives error

Body:
Possible Duplicate:

  Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.


问:
How to Fetch All Parameters in 'User Defined Java Class' Step in Pentaho Data Integration (Kettle)
Scenario:
I am creating a Transformation in PDI. This transformation Has a Step 'User Defined Java Class', In which I am calling an external library.

This Transformation have'parameters' and for now, I have to fetch all parameters individually to pass to use them in this step (passing to my external jar)like this:

```<code>PgSqlHost = getVariable("PostgresHost");
PgSqlPort = getVariable("PgSqlPort");
PgSqlLoginUserId = getVariable("PgSqlLoginUserId");
PgSqlLoginPassword = getVariable("PgSqlLoginPassword");
</code>```

There are 50-60 params like these that I have to use in this step. and I have to fetch each of them individually and pass it to external java lib like this.

```<code>TransformationParameters tparams= new TransformationParameters();
tparams.PgSqlHost = PgSqlHost;
tparams.PgSqlPort = Integer.parseInt(PgSqlPort);
tparams.PgSqlLoginUserId = PgSqlLoginUserId;
tparams.PgSqlLoginPassword = PgSqlLoginPassword;
Configuration config =  ConfigurationReader.getConfiguration();
config.setParameters(tparams);
</code>```

The problem with this approach is:

I have to fetch all parameters individually.

When Adding new parameter I have to handle modify this step in all transformations

My question:
Is there a way to fetch all parameters something just like this:

```<code>HashMap<K,V> params = getAllVariables();
Configuration config =  ConfigurationReader.getConfiguration();
config.setParametersMap(tparams);
</code>```

What I tried:

I tried searching in Pentaho Wiki & This thread in Forums,
But found nothing close.

I could add a step to write those params to a .properties file and
read those in my external jar.

Can someone suggest a better idea to achieve this?
Thanks.

答:
Use such method in process row in UserDefinedJavaClass</p>

```<code>String[] variables =    super.parent.listVariables();
</code>```

Body:
Scenario:
I am creating a Transformation in PDI. This transformation Has a Step 'User Defined Java Class', In which I am calling an external library.

This Transformation have'parameters' and for now, I have to fetch all parameters individually to pass to use them in this step (passing to my external jar)like this:

PgSqlHost = getVariable("PostgresHost");
PgSqlPort = getVariable("PgSqlPort");
PgSqlLoginUserId = getVariable("PgSqlLoginUserId");
PgSqlLoginPassword = getVariable("PgSqlLoginPassword");

There are 50-60 params like these that I have to use in this step. and I have to fetch each of them individually and pass it to external java lib like this.

TransformationParameters tparams= new TransformationParameters();
tparams.PgSqlHost = PgSqlHost;
tparams.PgSqlPort = Integer.parseInt(PgSqlPort);
tparams.PgSqlLoginUserId = PgSqlLoginUserId;
tparams.PgSqlLoginPassword = PgSqlLoginPassword;
Configuration config =  ConfigurationReader.getConfiguration();
config.setParameters(tparams);

The problem with this approach is:

I have to fetch all parameters individually.

When Adding new parameter I have to handle modify this step in all transformations

My question:
Is there a way to fetch all parameters something just like this:

HashMap<K,V> params = getAllVariables();
Configuration config =  ConfigurationReader.getConfiguration();
config.setParametersMap(tparams);

What I tried:

I tried searching in Pentaho Wiki & This thread in Forums,
But found nothing close.

I could add a step to write those params to a .properties file and
read those in my external jar.

Can someone suggest a better idea to achieve this?
Thanks.

Body:
Use such method in process row in UserDefinedJavaClass

String[] variables =    super.parent.listVariables();


问:
How to set layout_gravity programmatically?
My question is simple,

How to set my buttons layout_gravity programmatically?

I found this on internet, but it simply throws me a Nullpointer exception:

```<code> Button MyButton = new Button(this);

    LinearLayout.LayoutParams  lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
    lllp.gravity=Gravity.RIGHT;
    MyButton.setLayoutParams(lllp);

    MyLinearLayout.addView(MyButton);
</code>```

Any solution?

答:
Try this code

```<code>    Button btn = new Button(YourActivity.this);
    btn.setGravity(Gravity.CENTER | Gravity.TOP);
    btn.setText("some text");
</code>```

or

```<code>    btn.setGravity(Gravity.TOP);
</code>```

Body:
My question is simple,

How to set my buttons layout_gravity programmatically?

I found this on internet, but it simply throws me a Nullpointer exception:

 Button MyButton = new Button(this);

    LinearLayout.LayoutParams  lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
    lllp.gravity=Gravity.RIGHT;
    MyButton.setLayoutParams(lllp);

    MyLinearLayout.addView(MyButton);

Any solution?

Body:
Try this code

    Button btn = new Button(YourActivity.this);
    btn.setGravity(Gravity.CENTER | Gravity.TOP);
    btn.setText("some text");

or

    btn.setGravity(Gravity.TOP);