问:
Dynamically assign variable in Oracle join statement
I am new to oracle script. Trying to convert the sql to oracle and trying to execute below script as sample

```<code>DECLARE v_Removalsql varchar(100);
v_strQuery VARCHAR(1000);
v_Removalsql := 'Node.ElectronicSerialNumber'
v_strQuery := 'select * from ConsumerMessage join Node on
ConsumerMessage.ElectronicSerialNumber = :name' ;
EXECUTE IMMEDIATE v_strQuery using v_Removalsql
</code>```

when I execute the above script it gives below error as below

PLS-00103: Encountered the symbol "=" when expecting one of the following:

constant exception

table long double ref

char time timestamp interval date binary national character

nchar

00000 - "line %s, column %s:\n%s"

Cause: Usually a PL/SQL compilation error.

答:
This sounds like a very strange request - normally your join conditions are fixed!

Anyway, as Alex Poole mentioned in a comment above, you can't use bind variables when you're trying to specify the table name, column names, where clauses etc; you can only use it where you might use a literal value. If you need to dynamically specify table names, column names etc, you need to be careful about sql injection - you definitely don't want someone to be able to hijack your procedure for nefarious purposes!

Here's one way you could do this (I have used a ref cursor to demonstrate; this would work with EXECUTE IMMEDIATE too, but you'd have to specify where you want the data to be stored into, again, as previously mentioned by Alex):

```<code>DECLARE
  v_Removalsql varchar(100);
  v_strQuery VARCHAR(1000);
  v_refcur SYS_REFCURSOR;
BEGIN
  v_Removalsql := 'Node.ElectronicSerialNumber'
  v_strQuery := 'select * from ConsumerMessage join Node on ConsumerMessage.ElectronicSerialNumber = :name';

  -- check the string to be concatenated is a valid qualified sql name format
  -- this helps to avoid sql injection, but doesn't check whether the referenced
  -- object exists or not, so if it doesn't the dynamic query will still fail.
  dbms_assert.qualified_sql_name(v_remvoalsql);

  -- Now we can go ahead and replace the string ":name" with the new string
  v_strQuery := REPLACE(v_strQuery, ':name', v_removalsql);

  -- Finally, we can open a ref cursor for the dynamic sql:
  OPEN v_refcur FOR v_strQuery;
END;
/
</code>```

Another way would be to not use :name in your sql statement and simply concatenate the separate elements of your query, e.g.:

```<code>open v_refcur for v_select_clause || chr(10) ||
                  v_from_clause || chr(10) ||
                  v_where_clause;
</code>```

Just make sure you ensure any parameters you build into the string are checked to make sure they meet the Oracle naming standard!

Body:
I am new to oracle script. Trying to convert the sql to oracle and trying to execute below script as sample

DECLARE v_Removalsql varchar(100);
v_strQuery VARCHAR(1000);
v_Removalsql := 'Node.ElectronicSerialNumber'
v_strQuery := 'select * from ConsumerMessage join Node on
ConsumerMessage.ElectronicSerialNumber = :name' ;
EXECUTE IMMEDIATE v_strQuery using v_Removalsql

when I execute the above script it gives below error as below

PLS-00103: Encountered the symbol "=" when expecting one of the following:

constant exception

table long double ref

char time timestamp interval date binary national character

nchar

00000 - "line %s, column %s:\n%s"

Cause: Usually a PL/SQL compilation error.

Body:
This sounds like a very strange request - normally your join conditions are fixed!

Anyway, as Alex Poole mentioned in a comment above, you can't use bind variables when you're trying to specify the table name, column names, where clauses etc; you can only use it where you might use a literal value. If you need to dynamically specify table names, column names etc, you need to be careful about sql injection - you definitely don't want someone to be able to hijack your procedure for nefarious purposes!

Here's one way you could do this (I have used a ref cursor to demonstrate; this would work with EXECUTE IMMEDIATE too, but you'd have to specify where you want the data to be stored into, again, as previously mentioned by Alex):

DECLARE
  v_Removalsql varchar(100);
  v_strQuery VARCHAR(1000);
  v_refcur SYS_REFCURSOR;
BEGIN
  v_Removalsql := 'Node.ElectronicSerialNumber'
  v_strQuery := 'select * from ConsumerMessage join Node on ConsumerMessage.ElectronicSerialNumber = :name';

  -- check the string to be concatenated is a valid qualified sql name format
  -- this helps to avoid sql injection, but doesn't check whether the referenced
  -- object exists or not, so if it doesn't the dynamic query will still fail.
  dbms_assert.qualified_sql_name(v_remvoalsql);

  -- Now we can go ahead and replace the string ":name" with the new string
  v_strQuery := REPLACE(v_strQuery, ':name', v_removalsql);

  -- Finally, we can open a ref cursor for the dynamic sql:
  OPEN v_refcur FOR v_strQuery;
END;
/

Another way would be to not use :name in your sql statement and simply concatenate the separate elements of your query, e.g.:

open v_refcur for v_select_clause || chr(10) ||
                  v_from_clause || chr(10) ||
                  v_where_clause;

Just make sure you ensure any parameters you build into the string are checked to make sure they meet the Oracle naming standard!


来源: stackexchange

问:
How to get nth root of a number in Ruby?
For example

```<code>x ** 3 # => 125
</code>```

Knowing that the result of applying ** with an argument 3 to x is 125, how can I get the value of x?
Is there some kind of built-in method for this? I have been looking at the Math module but didn't find anything similar.

答:
You can do an Nth root by raising to a fractional power.  For example, the 4th root of 625 is 5.

```<code>(BigDecimal(625)**(1.0/4.0)).to_f
# => 5.0
</code>```

Note, the .to_f is added for readability in this answer only.  Don't cast it to a Float in your code unless you need to.  IMHO, BigDecimals are "better" than Floats in Ruby - Floats lose precision too easily and you won't get accurate results.  Case in point the accepted awnser above.  The cube root of 125 is not 4.99999(repeat).  It is 5.0 exactly.

Edit: the Ruby Class Rational seems to handle nth roots a little better.

```<code>2.3.3 :007 > 625.to_r ** 0.25
=> 5.0
</code>```

But it still isn't as precise with a number that produces an irrational root.

```<code>2.3.3 :024 > (999.to_r ** 0.25) ** 4
=> 998.9999999999999
</code>```

Close...but you should be able to get back to 999.0 exactly.  My Mac's calculator and excel can do it.  Main point - just be careful.  If precision is important, Ruby may not handle this exactly the way one would expect.

ContentLicense: CC BY-SA 3.0

Body:
For example

x ** 3 # => 125

Knowing that the result of applying ** with an argument 3 to x is 125, how can I get the value of x?
Is there some kind of built-in method for this? I have been looking at the Math module but didn't find anything similar.

Body:
You can do an Nth root by raising to a fractional power.  For example, the 4th root of 625 is 5.

(BigDecimal(625)**(1.0/4.0)).to_f
# => 5.0

Note, the .to_f is added for readability in this answer only.  Don't cast it to a Float in your code unless you need to.  IMHO, BigDecimals are "better" than Floats in Ruby - Floats lose precision too easily and you won't get accurate results.  Case in point the accepted awnser above.  The cube root of 125 is not 4.99999(repeat).  It is 5.0 exactly.

Edit: the Ruby Class Rational seems to handle nth roots a little better.

2.3.3 :007 > 625.to_r ** 0.25
=> 5.0

But it still isn't as precise with a number that produces an irrational root.

2.3.3 :024 > (999.to_r ** 0.25) ** 4
=> 998.9999999999999

Close...but you should be able to get back to 999.0 exactly.  My Mac's calculator and excel can do it.  Main point - just be careful.  If precision is important, Ruby may not handle this exactly the way one would expect.

ContentLicense: CC BY-SA 4.0


问:
angular2 - infinite loop when i call method from a Angular 2 class inside template
I have a problem when i call a method from component in the template by interpolation: {{get_method()}}. The method runs, but in infinite loop I don't know why. Any help please ??

the code of method is like this :

```<code>get_name() {
  console.log("bonjour");
}
</code>```

and I call it in my template like this :

```<code>{{get_name()}}
</code>```

and this is the result :

答: i finally found the sollution ,  it's to change  Detection Strategy to  OnPush for more information visite this link Change Detection Strategy: OnPush</p>

Body:
I have a problem when i call a method from component in the template by interpolation: {{get_method()}}. The method runs, but in infinite loop I don't know why. Any help please ??

the code of method is like this :

get_name() {
  console.log("bonjour");
}

and I call it in my template like this :

{{get_name()}}

and this is the result :


问:
Laravel can't login using attempt
As my title mentioned, I am trying to login using auth()->attempt($credentials, false) but it always return false.

After further digging into the problem, I finally found that it was due to this:

```<code>public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }
</code>```

The $user->getAuthPassword() returns null even though the $user have password on the original while I dump it out.

答:
Actually this is very basic mistake. As I had mixed with some other programming language style of code (getter and setter).

I set a password variable on the User::class.
By such, when it retrieving $user->getAuthPassword() it will take the variable data instead of attribute data.

I'm sharing this knowledge in case someone else encounters the same issue. As I tried to solve this problem for about 2 days and wasn't able to find anything.

Title: Laravel can't login using attempt

Body:
As my title mentioned, I am trying to login using auth()->attempt($credentials, false) but it always return false.

After further digging into the problem, I finally found that it was due to this:

public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }

The $user->getAuthPassword() returns null even though the $user have password on the original while I dump it out.


问:
Aspectj overwrite an argument of a method
I'm developing an aspect that checks arguments of setter methods and overwrites empty strings with null value. This is my state so far:

```<code>@Before("execution(* de.foo.entity.*.set*(..)) && args(java.lang.String)")
public void check(final JoinPoint jp) {
    LOGGER.debug(jp.getSignature().toLongString());
    Object[] args = jp.getArgs();
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof String && ((String) args[i]).isEmpty()) {
            args[i] = null;
        }
    }
}</code>```

Unfortunately the overwrite statement args[i] = null; does now work! Do anyone know how should I overwrite it?

Cheers,

Kevin

答:
I believe you have to implement an around advice, instead of a before advice.

Because you can use proceed with your new arguments:

```<code>proceed(newArgs);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm developing an aspect that checks arguments of setter methods and overwrites empty strings with null value. This is my state so far:

@Before("execution(* de.foo.entity.*.set*(..)) && args(java.lang.String)")
public void check(final JoinPoint jp) {
    LOGGER.debug(jp.getSignature().toLongString());
    Object[] args = jp.getArgs();
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof String && ((String) args[i]).isEmpty()) {
            args[i] = null;
        }
    }
}

Unfortunately the overwrite statement args[i] = null; does now work! Do anyone know how should I overwrite it?

Cheers,

Kevin

Body:
I believe you have to implement an around advice, instead of a before advice.

Because you can use proceed with your new arguments:

proceed(newArgs);


问:
How to make a list of xml tags with javaxb
I need to create the following part of xml file with javaxb :

```<code>    <tag> ..... </tag>
    <foto_1> ... </foto_1>
    <foto_2> ... </foto_2>
    <foto_3> ... </foto_3>
    <foto_4> ... </foto_4>
    .....
</code>```

Where the tag  is dynamic, so it could be a number between 1 and 15.
I asked the receiver if it is possible to make a tag list, but it is not !

Is it possible to create in javaxb this type of list ?
Or better, i don't know what to write in --> @XmlElement(name="") of the getter method.

答:
Found a solution with an @XmlAnyElement-annotated property that returns the elements as JAXBElements:

```<code>private List<Foto> foto = ...;

@XmlAnyElement
public List<JAXBElement<Foto>> getFoto() {
List<JAXBElement<Foto>> elements = new ArrayList<JAXBElement<Foto>>();
for (Foto current : foto )
    elements.add(new JAXBElement(new QName("foto_" + current.getValue(),
                                 Foto.class, current);
return elements;
}
</code>```

I think is not a clean solution, but it works !
I hope it could be useful

Body:
I need to create the following part of xml file with javaxb :

    <tag> ..... </tag>
    <foto_1> ... </foto_1>
    <foto_2> ... </foto_2>
    <foto_3> ... </foto_3>
    <foto_4> ... </foto_4>
    .....

Where the tag  is dynamic, so it could be a number between 1 and 15.
I asked the receiver if it is possible to make a tag list, but it is not !

Is it possible to create in javaxb this type of list ?
Or better, i don't know what to write in --> @XmlElement(name="") of the getter method.

Body:
Found a solution with an @XmlAnyElement-annotated property that returns the elements as JAXBElements:

private List<Foto> foto = ...;

@XmlAnyElement
public List<JAXBElement<Foto>> getFoto() {
List<JAXBElement<Foto>> elements = new ArrayList<JAXBElement<Foto>>();
for (Foto current : foto )
    elements.add(new JAXBElement(new QName("foto_" + current.getValue(),
                                 Foto.class, current);
return elements;
}

I think is not a clean solution, but it works !
I hope it could be useful


问:
typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here
I am trying to use Typescript for my AWS Lambda and i am getting the following errors where ever I use promises.

```
error TS2693: 'Promise' only refers to a type, but is being used as a value here.
```

I tried using the following variations in the code

Using the Promise constructor

```<code>responsePromise = new Promise((resolve, reject) => {
                    return reject(new Error(`missing is needed data`))
                })
</code>```

using Promise.reject

```<code>responsePromise = Promise.reject(new Error(`Unsupported method "${request.httpMethod}"`));
</code>```

Versions

Following are the versions in my dev dependencies:

```<code>"typescript": "^2.2.2"
"@types/aws-lambda": "0.0.9",
"@types/core-js": "^0.9.40",
"@types/node": "^7.0.12",
</code>```

Contents of tsconfig.json

```<code>{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        // "typeRoots" : ["./typings", "./node_modules/@types"],
        "target": "es5",
        // "types" : [ "core-js" ],
        "noImplicitAny": true,
        "strictNullChecks": true,
        "allowJs": true,
        "noEmit": true,
        "alwaysStrict": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "outDir": "dist",
        "moduleResolution": "Node",
        "declaration": true,
        "lib": [
            "es6"
        ]
    },
    "include": [
        "index.ts",
        "lib/**/*.ts"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}
</code>```

I am using grunt-ts with the following configuration for running ts task.

```<code>ts: {
            app: {
                tsconfig: {
                    tsconfig: "./tsconfig.json",
                    ignoreSettings: true
                }
            },
...
</code>```

I tried with the solution mentioned in I get: [ts] 'Promise' only refers to a type, but is being used as a value here but no luck.

答:
I had the same issue with the aws-sdk and I solved it by using "target": "es2015". This is my tsconfig.json file.

```<code>{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": false,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es2015"
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}
</code>```

Body:
I am trying to use Typescript for my AWS Lambda and i am getting the following errors where ever I use promises.

error TS2693: 'Promise' only refers to a type, but is being used as a value here.

I tried using the following variations in the code

Using the Promise constructor

responsePromise = new Promise((resolve, reject) => {
                    return reject(new Error(`missing is needed data`))
                })

using Promise.reject

responsePromise = Promise.reject(new Error(`Unsupported method "${request.httpMethod}"`));

Versions

Following are the versions in my dev dependencies:

"typescript": "^2.2.2"
"@types/aws-lambda": "0.0.9",
"@types/core-js": "^0.9.40",
"@types/node": "^7.0.12",

Contents of tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        // "typeRoots" : ["./typings", "./node_modules/@types"],
        "target": "es5",
        // "types" : [ "core-js" ],
        "noImplicitAny": true,
        "strictNullChecks": true,
        "allowJs": true,
        "noEmit": true,
        "alwaysStrict": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "outDir": "dist",
        "moduleResolution": "Node",
        "declaration": true,
        "lib": [
            "es6"
        ]
    },
    "include": [
        "index.ts",
        "lib/**/*.ts"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

I am using grunt-ts with the following configuration for running ts task.

ts: {
            app: {
                tsconfig: {
                    tsconfig: "./tsconfig.json",
                    ignoreSettings: true
                }
            },
...

I tried with the solution mentioned in I get: [ts] 'Promise' only refers to a type, but is being used as a value here but no luck.

Body:
I had the same issue with the aws-sdk and I solved it by using "target": "es2015". This is my tsconfig.json file.

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": false,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es2015"
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}


问:
unset all environment variables starting with a leading string while in a script (without closing or restarting bash)
I'd like to:

unset myvarname*

where myvarname is a string and * is... well, you got it.

Tried

env | grep string | unset

but doesn't work.

I'm into a script and I don't want to start a new shell so no env -i or source something or leaving the reentering the shell

Please help a poor noob

Thanks in advance

答:
Try this -

```<code>unset $(env | grep string |awk -F'=' '{print $1}')
</code>```

Let say I have environment variable like -

```<code>printenv
string1=hello
string2=vipin
</code>```

and when you will search with string grep will fetch both environment and fetch the name of environment variable and pass to unset command.

Body:
Try this -

unset $(env | grep string |awk -F'=' '{print $1}')

Let say I have environment variable like -

printenv
string1=hello
string2=vipin

and when you will search with string grep will fetch both environment and fetch the name of environment variable and pass to unset command.


问:
How to use Identity Server 4 Sign-in with desktop/mobile apps
We have a .Net Core Identity Server, a .Net Core Api, our clients however are desktop and mobile apps.

Looking through the docs it seems our Users need to Sign-in using Hybrid flow, however it seems this flow is for Web browser apps.

What is the correct flow/grant_type to Authenticate my Desktop Users and give them access to the Api?

答:
Hybrid flow is correct. See this spec:

https://datatracker.ietf.org/doc/html/draft-ietf-oauth-native-apps-09

You can use this library:
https://github.com/IdentityModel/IdentityModel.OidcClient2

and here are some sample:
https://github.com/IdentityModel/IdentityModel.OidcClient.Samples


问:
Spark DataFrame to RDD and back
I am writing an Apache Spark application using Scala. To handle and store data I use DataFrames. I have a nice pipeline with feature extraction and a MultiLayerPerceptron classifier, using the ML API.

I also want to use SVM (for comparison purposes). The thing is (and correct me if I am mistaken) only the MLLib provides SVM. And MLLib is not ready to handle DataFrames, only RDDs.

So I figured I can maintain the core of my application using DataFrames and to use SVM 1) I just convert the DataFrame's columns I need to an RDD[LabeledPoint] and 2) after the classification add the SVMs prediction to the DataFrame as a new column.

The first part I handled with a small function:

```<code>private def dataFrameToRDD(dataFrame : DataFrame) : RDD[LabeledPoint] = {
    val rddMl = dataFrame.select("label", "features").rdd.map(r => (r.getInt(0).toDouble, r.getAs[org.apache.spark.ml.linalg.SparseVector](1)))
    rddMl.map(r => new LabeledPoint(r._1, Vectors.dense(r._2.toArray)))
}
</code>```

I have to specify and convert the type of vector since the feature extraction method uses ML API and not MLLib.

Then, this RDD[LabeledPoint] is fed to the SVM and classification goes smoothly, no issues. At the end and following spark's example I get an RDD[Double]:

```<code>val predictions = rdd.map(point => model.predict(point.features))
</code>```

Now, I want to add the prediction score as column to the original DataFrame and return it. This is where I got stuck. I can convert the RDD[Double] to a DataFrame using

```<code>(sql context ommited)
import sqlContext.implicits._
val plDF = predictions.toDF("prediction")
</code>```

But how do I join the two DataFrames where the second DataFrame becomes a column of the original one? I tried to use methods join and union but got SQL exceptions as the DataFrames have no equal columns to join or unite on.

EDIT
I tried

```<code>data.withColumn("prediction", plDF.col("prediction"))
</code>```

But I get an Analysis Exception :(

答:
I haven't figured out how to do it without recurring to RDDs, but anyway here's how I solved it with RDD. Added the rest of the code so that anyone can understand the complete logic. Any suggestions are appreciated.</p>

```<code>package stuff

import java.util.logging.{Level, Logger}

import org.apache.spark.mllib.classification.{SVMModel, SVMWithSGD}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{DataFrame, Row, SQLContext}

/**
  * Created by camandros on 10-03-2017.
  */
class LinearSVMClassifier extends Classifier with Serializable{

  @transient lazy val log: Logger = Logger.getLogger(getClass.getName)

  private var model : SVMModel = _

  override def train(data : DataFrame): Unit = {
    val rdd = dataFrameToRDD(data)
    // Run training algorithm to build the model
    val numIter : Int = 100
    val step = Osint.properties(Osint.SVM_STEPSIZE).toDouble
    val c = Osint.properties(Osint.SVM_C).toDouble
    log.log(Level.INFO, "Initiating SVM training with parameters: C="+c+", step="+step)
    model = SVMWithSGD.train(rdd, numIterations = numIter, stepSize = step, regParam = c)
    log.log(Level.INFO, "Model training finished")

    // Clear the default threshold.
    model.clearThreshold()
  }

  override def classify(data : DataFrame): DataFrame = {
    log.log(Level.INFO, "Converting DataFrame to RDD")
    val rdd = dataFrameToRDD(data)
    log.log(Level.INFO, "Conversion finished; beginning classification")
    // Compute raw scores on the test set.
    val predictions = rdd.map(point => model.predict(point.features))
    log.log(Level.INFO, "Classification finished; Transforming RDD to DataFrame")

    val sqlContext : SQLContext = Osint.spark.sqlContext
    val tupleRDD = data.rdd.zip(predictions).map(t => Row.fromSeq(t._1.toSeq ++ Seq(t._2)))
    sqlContext.createDataFrame(tupleRDD, data.schema.add("predictions", "Double"))

    //TODO this should work it doesn't since this "withColumn" method seems to be applicable only to add
    // new columns using information from the same dataframe; therefore I am using the horrible rdd conversion
    //val sqlContext : SQLContext = Osint.spark.sqlContext
    //import sqlContext.implicits._
    //val plDF = predictions.toDF("predictions")
    //data.withColumn("prediction", plDF.col("predictions"))
  }

  private def dataFrameToRDD(dataFrame : DataFrame) : RDD[LabeledPoint] = {
    val rddMl = dataFrame.select("label", "features").rdd.map(r => (r.getInt(0).toDouble, r.getAs[org.apache.spark.ml.linalg.SparseVector](1)))
    rddMl.map(r => new LabeledPoint(r._1, Vectors.dense(r._2.toArray)))
  }
}
</code>```

Title: Spark DataFrame to RDD and back

Body:
I am writing an Apache Spark application using Scala. To handle and store data I use DataFrames. I have a nice pipeline with feature extraction and a MultiLayerPerceptron classifier, using the ML API.

I also want to use SVM (for comparison purposes). The thing is (and correct me if I am mistaken) only the MLLib provides SVM. And MLLib is not ready to handle DataFrames, only RDDs.

So I figured I can maintain the core of my application using DataFrames and to use SVM 1) I just convert the DataFrame's columns I need to an RDD[LabeledPoint] and 2) after the classification add the SVMs prediction to the DataFrame as a new column.

The first part I handled with a small function:

private def dataFrameToRDD(dataFrame : DataFrame) : RDD[LabeledPoint] = {
    val rddMl = dataFrame.select("label", "features").rdd.map(r => (r.getInt(0).toDouble, r.getAs[org.apache.spark.ml.linalg.SparseVector](1)))
    rddMl.map(r => new LabeledPoint(r._1, Vectors.dense(r._2.toArray)))
}

I have to specify and convert the type of vector since the feature extraction method uses ML API and not MLLib.

Then, this RDD[LabeledPoint] is fed to the SVM and classification goes smoothly, no issues. At the end and following spark's example I get an RDD[Double]:

val predictions = rdd.map(point => model.predict(point.features))

Now, I want to add the prediction score as column to the original DataFrame and return it. This is where I got stuck. I can convert the RDD[Double] to a DataFrame using

(sql context ommited)
import sqlContext.implicits._
val plDF = predictions.toDF("prediction")

But how do I join the two DataFrames where the second DataFrame becomes a column of the original one? I tried to use methods join and union but got SQL exceptions as the DataFrames have no equal columns to join or unite on.

EDIT
I tried

data.withColumn("prediction", plDF.col("prediction"))

But I get an Analysis Exception :(

Body:
I haven't figured out how to do it without recurring to RDDs, but anyway here's how I solved it with RDD. Added the rest of the code so that anyone can understand the complete logic. Any suggestions are appreciated.

package stuff

import java.util.logging.{Level, Logger}

import org.apache.spark.mllib.classification.{SVMModel, SVMWithSGD}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{DataFrame, Row, SQLContext}

/**
  * Created by camandros on 10-03-2017.
  */
class LinearSVMClassifier extends Classifier with Serializable{

  @transient lazy val log: Logger = Logger.getLogger(getClass.getName)

  private var model : SVMModel = _

  override def train(data : DataFrame): Unit = {
    val rdd = dataFrameToRDD(data)
    // Run training algorithm to build the model
    val numIter : Int = 100
    val step = Osint.properties(Osint.SVM_STEPSIZE).toDouble
    val c = Osint.properties(Osint.SVM_C).toDouble
    log.log(Level.INFO, "Initiating SVM training with parameters: C="+c+", step="+step)
    model = SVMWithSGD.train(rdd, numIterations = numIter, stepSize = step, regParam = c)
    log.log(Level.INFO, "Model training finished")

    // Clear the default threshold.
    model.clearThreshold()
  }

  override def classify(data : DataFrame): DataFrame = {
    log.log(Level.INFO, "Converting DataFrame to RDD")
    val rdd = dataFrameToRDD(data)
    log.log(Level.INFO, "Conversion finished; beginning classification")
    // Compute raw scores on the test set.
    val predictions = rdd.map(point => model.predict(point.features))
    log.log(Level.INFO, "Classification finished; Transforming RDD to DataFrame")

    val sqlContext : SQLContext = Osint.spark.sqlContext
    val tupleRDD = data.rdd.zip(predictions).map(t => Row.fromSeq(t._1.toSeq ++ Seq(t._2)))
    sqlContext.createDataFrame(tupleRDD, data.schema.add("predictions", "Double"))

    //TODO this should work it doesn't since this "withColumn" method seems to be applicable only to add
    // new columns using information from the same dataframe; therefore I am using the horrible rdd conversion
    //val sqlContext : SQLContext = Osint.spark.sqlContext
    //import sqlContext.implicits._
    //val plDF = predictions.toDF("predictions")
    //data.withColumn("prediction", plDF.col("predictions"))
  }

  private def dataFrameToRDD(dataFrame : DataFrame) : RDD[LabeledPoint] = {
    val rddMl = dataFrame.select("label", "features").rdd.map(r => (r.getInt(0).toDouble, r.getAs[org.apache.spark.ml.linalg.SparseVector](1)))
    rddMl.map(r => new LabeledPoint(r._1, Vectors.dense(r._2.toArray)))
  }
}


问:
how to add NYC map bound in plot using R
How can I add NYC map bound into my plot.nycmap dataset include longitude,latitude,and price variable.

longitude latitude price
-70.23  49.34   120
-20.31  30.26   56
...```
</div>
</div>
</p>

```min_lat <- 40.5774
max_lat <- 40.9176
min_long <- -74.15
max_long <- -73.7004

library(ggmap)
library(ggthemes)

plot <- ggplot(mapnyc, aes(x=longitude, y=latitude,color =logprice),alpha =0.03) +
            geom_point(size=0.8) +
            scale_x_continuous(limits=c(min_long, max_long)) +
            scale_y_continuous(limits=c(min_lat, max_lat))
plot
```

So I want to get spatial plots in NYC map bound? In my plot,I don't have bound there.

答:
Since you are using the ggmap package, I would suggest using ggmap() function:

```<code>mapnyc <- data.frame(latitude = c(40.7032815,40.7082398),
                     longitude = c(-74.0192166, -74.0054436),
                     logprice = c(120,56))
nyc_base <- ggmap::get_map("New York City", zoom = 14)
ggmap(nyc_base) + geom_point(data=mapnyc, aes(x=longitude, y=latitude), color="red", size=20, alpha=0.5)
</code>```

Note: I could not make sense of your original data with regards to your bounding box so I just made my own data.

Body:
How can I add NYC map bound into my plot.nycmap dataset include longitude,latitude,and price variable.

longitude latitude price
-70.23  49.34   120
-20.31  30.26   56
...

min_lat <- 40.5774
max_lat <- 40.9176
min_long <- -74.15
max_long <- -73.7004

library(ggmap)
library(ggthemes)

plot <- ggplot(mapnyc, aes(x=longitude, y=latitude,color =logprice),alpha =0.03) +
            geom_point(size=0.8) +
            scale_x_continuous(limits=c(min_long, max_long)) +
            scale_y_continuous(limits=c(min_lat, max_lat))
plot

So I want to get spatial plots in NYC map bound? In my plot,I don't have bound there.

Body:
Since you are using the ggmap package, I would suggest using ggmap() function:

mapnyc <- data.frame(latitude = c(40.7032815,40.7082398),
                     longitude = c(-74.0192166, -74.0054436),
                     logprice = c(120,56))
nyc_base <- ggmap::get_map("New York City", zoom = 14)
ggmap(nyc_base) + geom_point(data=mapnyc, aes(x=longitude, y=latitude), color="red", size=20, alpha=0.5)

Note: I could not make sense of your original data with regards to your bounding box so I just made my own data.


问:
Using Named Ranges in VBA Excel 2007
I am trying to access a named range from using VBA in Excel 2007. When I used the explicit range i.e. "A3:M53" I can get the formula below to work. However, when I replace the explicit range with a named range I get an error. I need to use named ranges as the program needs to select different ranges depending on what data is imported. Fixed.OAX.5 is a named range on the OAX50 worksheet.

```<code>WorksheetFunction.Match(5, Worksheets("OAX50").Range("Fixed.OAX.5"), 1)
</code>```

When I run this code I get "Unable to get the Match property of the WorksheetFunction class.

答:
you're most probably not finding value 5 in Worksheets("OAX50").Range("Fixed.OAX.5")

use Application.Match() and wrap any possible error:

```<code>Dim x As Variant
With Worksheets("OAX50").Range("Fixed.OAX.5")
    x = Application.Match(5, .Cells, 1)
    If IsError(x) Then
        MsgBox "Sorry, no match for '5' in range " & .Address & " of worksheet '" & .Parent.Name & "'"
    Else
        'your code to exploit 'x'
    End If
End With
</code>```

Title: Using Named Ranges in VBA Excel 2007

Body:
I am trying to access a named range from using VBA in Excel 2007. When I used the explicit range i.e. "A3:M53" I can get the formula below to work. However, when I replace the explicit range with a named range I get an error. I need to use named ranges as the program needs to select different ranges depending on what data is imported. Fixed.OAX.5 is a named range on the OAX50 worksheet.

WorksheetFunction.Match(5, Worksheets("OAX50").Range("Fixed.OAX.5"), 1)

When I run this code I get "Unable to get the Match property of the WorksheetFunction class.

Body:
you're most probably not finding value 5 in Worksheets("OAX50").Range("Fixed.OAX.5")

use Application.Match() and wrap any possible error:

Dim x As Variant
With Worksheets("OAX50").Range("Fixed.OAX.5")
    x = Application.Match(5, .Cells, 1)
    If IsError(x) Then
        MsgBox "Sorry, no match for '5' in range " & .Address & " of worksheet '" & .Parent.Name & "'"
    Else
        'your code to exploit 'x'
    End If
End With


问:
Setting environment variables when running Scala / SBT test suite
I've created a Config object with a get method to return different strings based on the PROJECT_ENV environment variable.  If PROJECT_ENV=test, then Config.get("somePath") returns some/path.csv, otherwise it returns s3a://some_bucket/a_file.csv.

```<code>object Config {

  def test(): Map[String,String] = {
    Map(
      "somePath" -> "some/path.csv"
    )
  }

  def default(): Map[String,String] = {
    Map(
      "somePath" -> "s3a://some_bucket/a_file.csv"
    )
  }

  def get(key: String, env: Option[String] = sys.env.get("PROJECT_ENV")): String = {
    val lookupMap = if (env == Some("test")) {
      List(default(), test()).flatten.toMap
    } else {
      default()
    }
    lookupMap(key)
  }

}
</code>```

With Ruby / RSpec, I set the environment variable in the spec_helper.rb file with ENV['PROJECT_ENV'] = 'test'.

What is the scalatest equivalent of the spec_helper.rb file?  How can I set an environment variable in Scala?  This answer isn't sufficient.

My test suite runs successfully if I run $ PROJECT_ENV=test sbt test, but I want to simply run $ sbt test.

答:
This question appears to have overlap with Set default env variable for test configuration in sbt .

The accepted answer over there worked well for me:

```<code>fork in Test := true
envVars in Test := Map("PROJECT_ENV" -> "test")
</code>```

The key is to make sure to include the fork otherwise the same env in play when launching sbt gets used.

Body:
I've created a Config object with a get method to return different strings based on the PROJECT_ENV environment variable.  If PROJECT_ENV=test, then Config.get("somePath") returns some/path.csv, otherwise it returns s3a://some_bucket/a_file.csv.

object Config {

  def test(): Map[String,String] = {
    Map(
      "somePath" -> "some/path.csv"
    )
  }

  def default(): Map[String,String] = {
    Map(
      "somePath" -> "s3a://some_bucket/a_file.csv"
    )
  }

  def get(key: String, env: Option[String] = sys.env.get("PROJECT_ENV")): String = {
    val lookupMap = if (env == Some("test")) {
      List(default(), test()).flatten.toMap
    } else {
      default()
    }
    lookupMap(key)
  }

}

With Ruby / RSpec, I set the environment variable in the spec_helper.rb file with ENV['PROJECT_ENV'] = 'test'.

What is the scalatest equivalent of the spec_helper.rb file?  How can I set an environment variable in Scala?  This answer isn't sufficient.

My test suite runs successfully if I run $ PROJECT_ENV=test sbt test, but I want to simply run $ sbt test.

Body:
This question appears to have overlap with Set default env variable for test configuration in sbt .

The accepted answer over there worked well for me:

fork in Test := true
envVars in Test := Map("PROJECT_ENV" -> "test")

The key is to make sure to include the fork otherwise the same env in play when launching sbt gets used.


问:
Is Parse LiveQuery available for use in Android development?
I saw that Parse had introduced live querying into Javascript and iOS, but I have not heard anything about Android.  Is it available?</p>

答:
Parse Live Query support for Android is available here now:
https://github.com/ParsePlatform/ParseLiveQuery-Android</p>


问:
Feed subscription statistics with Drupal?
I have a Drupal website, and I am currently using Feedburner, mainly to get statistics about the number of subscribers and methods of subscriptions.

However "burning" my feed is complicated, it's hard to restrict people from accessing the original feed, and it only does one feed, as opposed to various tag feeds, user feeds, etc.

How would you have Drupal collect and present feed access and subscription satistics?

答: Are you using the Feedburner module? It will do redirection from the original feed URL to the FeedBurner feed URL (FeedBurner itself will still have access to the original). You can do it for multiple feeds, though I think you still have to add those manually, which will be cumbersome for all the various tag feeds.</p>


问:
How to swipe Left and Right with vertical scrolling using ScrollView in Android
I have some layouts inside a scrollView. Those layouts have to be swipable in left and right directions but it creates some conflicts with the scroll View. How can use both swipe and scroll using ScrollView in Android. I don,t want to use ViewPager.

Please help me as i am fresher in android.

Thanks in Advance.

答:
Use HorizontalScrollView, which scrolls left-right, inside your parent ScrollView.

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="your_width" android:layout_height="your_height" >

 <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="your_width" android:layout_height="your_height">

</HorizontalScrollView>

</ScrollView>
</code>```

Body:
Use HorizontalScrollView, which scrolls left-right, inside your parent ScrollView.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="your_width" android:layout_height="your_height" >

 <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="your_width" android:layout_height="your_height">

</HorizontalScrollView>

</ScrollView>


问:
Can´t log on to subsite in wordpress multisite
We have 4 sites on our network.
mainsite.com, dev.mainsite.com, site2.com, and dev.site2.com.
But we can´t log on to site2.com and dev.site2.com?
We are not using any plugin since: WordPress 4.5+, domain mapping is a native feature.</p>

答:
Please do the following:

1) Navigate to the network dashboard using networkdomain/wp-admin/network

2) Navigate to Sites > All Sites

3) Click Edit Site > Check if Info- SiteURL is correct and also check if Settings > SitUrl and HomeUrl are correct

VHosts

If this is all correct, then you have a problem with your vhosts file. You will need to configure your vhosts file to point the domain name towards the Wordpress installation.

DNS Records

If the vhosts files are correct, you will need to check if the DNS records for your domain and subdomain are correct.

Get back to me if you need any help :)


问:
animateLayoutChanges="true" in BottomSheetView showing unexpected behaviour
I have a BottomSheetView which has animateLayoutChanges="true". Initially it shows up fine. But if change the visibility of a view (inside BottomSheetView) from GONE to VISIBLE, the app messes up calculations and my BottomSheetView moves to the top of the screen. i have tried setting layout_gravity=bottom at the root of the BottomSheetView layout. But no success.

Here I have the image of my BottomSheetView before changing the visibility of any view. (Click image for full size)

After I change the visibility of a view (GONE to VISIBLE or VISIBLE to GONE), my BottomSheetView moves to the top. (Click image for full size)

I guess, Android is messing up while making calculations about the measurement of view width and height. Any way to solve this??

I also tried to make my BottomSheetView extend fully to match the parent view, but somehow that is making the height of the BottomSheetView longer than the phone screen and in-tun creating scrolling issues.

Expected solutions:

1> Prevent BottomSheetView from changing its position even when the visibility of a view is changed.

OR

2>Make the BottomSheetView match parent so that it does not look bad after messing up with the calculations.

答:
I was running into the same issue and determined to find a fix. I was able to find the underlying cause but unfortunately I do not see a great  fix at the moment.

The Cause:
The problem occurs between the bottomsheet behavior and the LayoutTransition. When the LayoutTransition is created, it creates a OnLayoutChangeListener on the view so that it can capture its endValues and setup an animator with the proper values. This OnLayoutChangeListener is triggered in the bottomSheetBehavior's onLayout() call when it first calls parent.onLayout(child). The parent will layout the child as it normally would, ignoring any offsets that the behavior would change later. The problem lies here. The values of the view at this point are captured by the OnLayoutChangeListener and stored in the animator. When the animation runs, it will animate to these values, not to where your behavior defines. Unfortunately, the LayoutTransition class does not give us access to the animators to allow updating of the end values.

The Fix:
Currently, I don't see an elegant fix that involves LayoutTransitions. I am going to submit a bug for a way to access and update  LayoutTransition animators. For now you can disable any layoutTransition on the parent container using layoutTransition.setAnimateParentHierarchy(false). Then you can animate the change yourself. I'll update my answer with a working example as soon as I can.


问:
Why does `std::make_shared` perform two separate allocations with `-fno-rtti`?
```<code>#include <memory>
struct foo { };
int main() { std::make_shared<foo>(); }
</code>```

The asssembly generated by both g++7 and clang++5 with -fno-exceptions -Ofast for the code above:

Contains a single call to operator new if -fno-rtti is not passed.

Contains two separate calls to operator new if -fno-rtti is passed.

This can be easily verified on gcc.godbolt.org (clang++5 version):

Why is this happening? Why does disabling RTTI prevent make_shared from unifying the object and control block allocations?

答:
No good reason.  This looks like a QoI issue in libstdc++.

Using clang 4.0, libc++ does not have this issue., while libstdc++ does.

The libstdc++ implementation with RTTI relies on get_deleter:

```<code>void* __p = _M_refcount._M_get_deleter(typeid(__tag));
                  _M_ptr = static_cast<_Tp*>(__p);
                  __enable_shared_from_this_helper(_M_refcount, _M_ptr, _M_ptr);
_M_ptr = static_cast<_Tp*>(__p);
</code>```

and in general, get_deleter isn't possible to implement without RTTI.

It appears that it is using the deleters position and the tag to store the T in this implementation.

Basically, the RTTI version used get_deleter.  get_deleter relied on RTTI.  Getting make_shared to work without RTTI required rewriting it, and they took an easy route that caused it to do two allocations.

make_shared unifies the T and reference counting blocks.  I suppose with both variable sized deleters and variable sized T things get nasty, so they reused the deleter's variable sized block to store the T.

A modified (internal) get_deleter that did not do RTTI and returned a void* might be enough to do what they need from this deleter; but possibly not.

Body:
#include <memory>
struct foo { };
int main() { std::make_shared<foo>(); }

The asssembly generated by both g++7 and clang++5 with -fno-exceptions -Ofast for the code above:

Contains a single call to operator new if -fno-rtti is not passed.

Contains two separate calls to operator new if -fno-rtti is passed.

This can be easily verified on gcc.godbolt.org (clang++5 version):

Why is this happening? Why does disabling RTTI prevent make_shared from unifying the object and control block allocations?

Body:
No good reason.  This looks like a QoI issue in libstdc++.

Using clang 4.0, libc++ does not have this issue., while libstdc++ does.

The libstdc++ implementation with RTTI relies on get_deleter:

void* __p = _M_refcount._M_get_deleter(typeid(__tag));
                  _M_ptr = static_cast<_Tp*>(__p);
                  __enable_shared_from_this_helper(_M_refcount, _M_ptr, _M_ptr);
_M_ptr = static_cast<_Tp*>(__p);

and in general, get_deleter isn't possible to implement without RTTI.

It appears that it is using the deleters position and the tag to store the T in this implementation.

Basically, the RTTI version used get_deleter.  get_deleter relied on RTTI.  Getting make_shared to work without RTTI required rewriting it, and they took an easy route that caused it to do two allocations.

make_shared unifies the T and reference counting blocks.  I suppose with both variable sized deleters and variable sized T things get nasty, so they reused the deleter's variable sized block to store the T.

A modified (internal) get_deleter that did not do RTTI and returned a void* might be enough to do what they need from this deleter; but possibly not.


问:
How to access the user's selection in the browser?
I'm trying to write an extension for chrome that operates on a user's selection on a webpage. How can I get access to the selected text from a chrome plugin?

Thanks,
Joshua

答:
I don't know anything about Chrome plug-ins, but I imagine they have access to the regular window object. This is how you do it in a web page:

```<code>var sel = window.getSelection();
var selectedText = sel.toString();
</code>```

Body:
I don't know anything about Chrome plug-ins, but I imagine they have access to the regular window object. This is how you do it in a web page:

var sel = window.getSelection();
var selectedText = sel.toString();


问:
How do I only keep the rows with the lowest and highest value in a certain column, by groups?
In a nutshell, how do I go from this

```<code>structure(list(id = c(1, 2, 3, 4, 5, 6), user = c(1, 1, 1, 2,
2, 2), value = c(1, 3, 5, 2, 5, 9)), .Names = c("id", "user",
"value"), row.names = c(NA, -6L), class = "data.frame")
</code>```

to this?

```<code>structure(list(id = c(1, 3, 4, 6), user = c(1, 1, 2, 2), value = c(1,
5, 2, 9)), .Names = c("id", "user", "value"), row.names = c(NA,
-4L), class = "data.frame")
</code>```

Meaning, for each user, need to keep only the two rows corresponding to the lowest and highest value.

I'd like a solution using dplyr, if possible. Otherwise, any solution is fine.

答:
In base R, we can combine ave and range with subsetting [ like this

```<code>df1[as.logical(ave(df1$value, df1$user, FUN=function(i) i %in% range(i))), ]
  id user value
1  1    1     1
3  3    1     5
4  4    2     2
6  6    2     9
</code>```

Here, %in% checks if the elements of value are in range, a vector which returns the minimum and maximum, and ave applies this for each user. This returns a binary (0 , 1) vector the same length as the number of rows of the data.frame, which is converted to logical with as.logical. If you want something a bit shorter, as.logical could be changed out for !!.

Note that this will keep all min and max values, so depending on the type of df$value, this may or may not be desirable.

Body:
In a nutshell, how do I go from this

structure(list(id = c(1, 2, 3, 4, 5, 6), user = c(1, 1, 1, 2,
2, 2), value = c(1, 3, 5, 2, 5, 9)), .Names = c("id", "user",
"value"), row.names = c(NA, -6L), class = "data.frame")

to this?

structure(list(id = c(1, 3, 4, 6), user = c(1, 1, 2, 2), value = c(1,
5, 2, 9)), .Names = c("id", "user", "value"), row.names = c(NA,
-4L), class = "data.frame")

Meaning, for each user, need to keep only the two rows corresponding to the lowest and highest value.

I'd like a solution using dplyr, if possible. Otherwise, any solution is fine.

Body:
In base R, we can combine ave and range with subsetting [ like this

df1[as.logical(ave(df1$value, df1$user, FUN=function(i) i %in% range(i))), ]
  id user value
1  1    1     1
3  3    1     5
4  4    2     2
6  6    2     9

Here, %in% checks if the elements of value are in range, a vector which returns the minimum and maximum, and ave applies this for each user. This returns a binary (0 , 1) vector the same length as the number of rows of the data.frame, which is converted to logical with as.logical. If you want something a bit shorter, as.logical could be changed out for !!.

Note that this will keep all min and max values, so depending on the type of df$value, this may or may not be desirable.


问:
threejs colorsNeedUpdate not triggering update
I am trying to trigger a change of face color on external event - button. Even though there are many similar questions, none of the offered solutions worked out so far. So, I have an interactive model and  I want to be able to toggle its colors.

The model is rendered and colored on init() (ignore the fact it is being colored in for loop, there are some coloring conditions going on, which are irrelevant here)

First I iterate through faces and color them

```<code>geometry = new THREE.Geometry().fromBufferGeometry( object );
var faceIndices = [ 'a', 'b', 'c' ];
for ( var i = 0; i < geometry.faces.length; i ++ ) {
    var face  = geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color( 0xff0000 );
        face.vertexColors[ j ] = color;
    }
}
</code>```

Then I set the material and its flags

```<code>var material = new THREE.MeshPhongMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors} );
material.needsUpdate = true;
var solidModel = new THREE.Mesh( geometry, material );
solidModel.dynamic = true;
solidModel.name = "solid";
</code>```

After which I add it to the scene which is being rendered

```<code>scene.add( solidModel );
</code>```

And that works fine. Here comes the troubling part. On click I call the color() function

```<code>console.log("Coloring...");
// Color the object
var solid = scene.getObjectByName("solid"); // retrieve the object from the scene
// change colors
for ( var i = 0; i < solid.geometry.faces.length; i ++ ) {
    var face  = solid.geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color(  0xffffff );
        color.setHex( Math.random() * 0xffffff );
        face.vertexColors[ j ] = color;
    }
}
// raise the update flag
solid.geometry.colorsNeedUpdate = true;
</code>```

And nothing happens.
I also tried by removing the solid object from the scene, creating the new one frome the same geometry and again adding it to the scene. Also doesn't work.

What is really curious is that within the chrome debugger, colorsNeedUpdate flag on the "solid" object is actually true at the rendering time.

I work with threejs r84

Any insight would be helpful

答:
Try this:

```<code>for (var i = 0; i < solid.geometry.faces.length; i++) {
  var face = solid.geometry.faces[i];
  for (var j = 0; j < 3; j++) {
    face.vertexColors[j].setHex(Math.random() * 0xffffff);
  }
}
</code>```

jsfiddle example

Body:
I am trying to trigger a change of face color on external event - button. Even though there are many similar questions, none of the offered solutions worked out so far. So, I have an interactive model and  I want to be able to toggle its colors.

The model is rendered and colored on init() (ignore the fact it is being colored in for loop, there are some coloring conditions going on, which are irrelevant here)

First I iterate through faces and color them

geometry = new THREE.Geometry().fromBufferGeometry( object );
var faceIndices = [ 'a', 'b', 'c' ];
for ( var i = 0; i < geometry.faces.length; i ++ ) {
    var face  = geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color( 0xff0000 );
        face.vertexColors[ j ] = color;
    }
}

Then I set the material and its flags

var material = new THREE.MeshPhongMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors} );
material.needsUpdate = true;
var solidModel = new THREE.Mesh( geometry, material );
solidModel.dynamic = true;
solidModel.name = "solid";

After which I add it to the scene which is being rendered

scene.add( solidModel );

And that works fine. Here comes the troubling part. On click I call the color() function

console.log("Coloring...");
// Color the object
var solid = scene.getObjectByName("solid"); // retrieve the object from the scene
// change colors
for ( var i = 0; i < solid.geometry.faces.length; i ++ ) {
    var face  = solid.geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color(  0xffffff );
        color.setHex( Math.random() * 0xffffff );
        face.vertexColors[ j ] = color;
    }
}
// raise the update flag
solid.geometry.colorsNeedUpdate = true;

And nothing happens.
I also tried by removing the solid object from the scene, creating the new one frome the same geometry and again adding it to the scene. Also doesn't work.

What is really curious is that within the chrome debugger, colorsNeedUpdate flag on the "solid" object is actually true at the rendering time.

I work with threejs r84

Any insight would be helpful

Body:
Try this:

for (var i = 0; i < solid.geometry.faces.length; i++) {
  var face = solid.geometry.faces[i];
  for (var j = 0; j < 3; j++) {
    face.vertexColors[j].setHex(Math.random() * 0xffffff);
  }
}

jsfiddle example


问:
This application failed to start because it could not find or load the Qt platform plugin "xcb" in ""
I have an application which runs using Qt5 (via PyQt). I am using miniconda and the python code has been cythonised. The code was setup on my local machine, the cython code produced from the original .py files and the relevant libraries and modules installed in miniconda such that the code runs successfully. Then I ship everything to another machine, compile the cython code to give .so files and attempt to run it. At this point I get the error:

```<code>This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".

Reinstalling the application may fix this problem.
Aborted (core dumped)
</code>```

I have looked around for a long time for possible solutions and I have the following extra information:

I have checked ldd on the various .so files. All seem to find the required libraries.

I have tried locate libqxcb.so and this returns:
~/miniconda3/pkgs/qt-5.6.2-3/plugins/platforms/libqxcb.so
&
~/miniconda3/plugins/platforms/libqxcb.so

Based on the suggestions here from TranslucentCloud, I have copied this to the directory ~/miniconda3/bin/platforms (newly created).

I have also included export QT_DEBUG_PLUGINS=1 in the script which calls my code. This gives the following output:

```<code>QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "~/miniconda3/bin/platforms/libqxcb.so"
Found metadata in lib ~/miniconda3/bin/platforms/libqxcb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "xcb"
        ]
    },
    "className": "QXcbIntegrationPlugin",
    "debug": false,
    "version": 329218
}

Got keys from plugin meta data ("xcb")
loaded library "~/miniconda3/bin/platforms/libqxcb.so"
xkbcommon: ERROR: failed to add default include path ~/Programmes/miniconda3/lib
Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent enough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/xcbglintegrations" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/platformthemes" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/platforminputcontexts" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/styles" ...
Fontconfig error: Cannot load default config file
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/accessible" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/accessiblebridge" ...
QXcbConnection: XCB error: 145 (Unknown), sequence: 165, resource id: 0, major code: 139 (Unknown), minor code: 20
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/imageformats" ...
QLibraryPrivate::unload succeeded on "~/miniconda3/bin/platforms/libqxcb.so"
</code>```

The GUI now loads and buttons etc work. However, there are still a few issues - the minor issue is that all the fonts are different from my local machine (not a major problem, but presumably indicative that it's still not finding some relevant libraries).

More seriously, the GUI doesn't respond to any key presses - the GUI has lots of text boxes to fill in so this makes it unusable.

There are clearly some errors still in the output above, however, it's not clear from this which libraries etc. it is still unable to find (or why this is the case).

答:
A number of steps were necessary to resolve the errors above:

```<code>This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".

Reinstalling the application may fix this problem.
Aborted (core dumped)
</code>```

This can be resolved by copying ~/miniconda3/plugins/platforms to ~/miniconda3/bin.

In addition in the bash script which launches the Qt GUI I have added the following lines, otherwise all the text in the GUI appears in Courier:

```<code>export FONTCONFIG_FILE=/etc/fonts/fonts.conf
export FONTCONFIG_PATH=/etc/fonts/
</code>```

Finally I also needed the following line to allow keypresses to be registered by the GUI:

```<code>export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb
</code>```

Key to resolving this was the line:
export QT_DEBUG_PLUGINS=1 which enabled me to see where Qt was breaking.

Body:
I have an application which runs using Qt5 (via PyQt). I am using miniconda and the python code has been cythonised. The code was setup on my local machine, the cython code produced from the original .py files and the relevant libraries and modules installed in miniconda such that the code runs successfully. Then I ship everything to another machine, compile the cython code to give .so files and attempt to run it. At this point I get the error:

This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".

Reinstalling the application may fix this problem.
Aborted (core dumped)

I have looked around for a long time for possible solutions and I have the following extra information:

I have checked ldd on the various .so files. All seem to find the required libraries.

I have tried locate libqxcb.so and this returns:
~/miniconda3/pkgs/qt-5.6.2-3/plugins/platforms/libqxcb.so
&
~/miniconda3/plugins/platforms/libqxcb.so

Based on the suggestions here from TranslucentCloud, I have copied this to the directory ~/miniconda3/bin/platforms (newly created).

I have also included export QT_DEBUG_PLUGINS=1 in the script which calls my code. This gives the following output:

QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "~/miniconda3/bin/platforms/libqxcb.so"
Found metadata in lib ~/miniconda3/bin/platforms/libqxcb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "xcb"
        ]
    },
    "className": "QXcbIntegrationPlugin",
    "debug": false,
    "version": 329218
}

Got keys from plugin meta data ("xcb")
loaded library "~/miniconda3/bin/platforms/libqxcb.so"
xkbcommon: ERROR: failed to add default include path ~/Programmes/miniconda3/lib
Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent enough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/xcbglintegrations" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/platformthemes" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/platforminputcontexts" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/styles" ...
Fontconfig error: Cannot load default config file
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/accessible" ...
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/accessiblebridge" ...
QXcbConnection: XCB error: 145 (Unknown), sequence: 165, resource id: 0, major code: 139 (Unknown), minor code: 20
QFactoryLoader::QFactoryLoader() checking directory path "~/miniconda3/bin/imageformats" ...
QLibraryPrivate::unload succeeded on "~/miniconda3/bin/platforms/libqxcb.so"

The GUI now loads and buttons etc work. However, there are still a few issues - the minor issue is that all the fonts are different from my local machine (not a major problem, but presumably indicative that it's still not finding some relevant libraries).

More seriously, the GUI doesn't respond to any key presses - the GUI has lots of text boxes to fill in so this makes it unusable.

There are clearly some errors still in the output above, however, it's not clear from this which libraries etc. it is still unable to find (or why this is the case).

Body:
A number of steps were necessary to resolve the errors above:

This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".

Reinstalling the application may fix this problem.
Aborted (core dumped)

This can be resolved by copying ~/miniconda3/plugins/platforms to ~/miniconda3/bin.

In addition in the bash script which launches the Qt GUI I have added the following lines, otherwise all the text in the GUI appears in Courier:

export FONTCONFIG_FILE=/etc/fonts/fonts.conf
export FONTCONFIG_PATH=/etc/fonts/

Finally I also needed the following line to allow keypresses to be registered by the GUI:

export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb

Key to resolving this was the line:
export QT_DEBUG_PLUGINS=1 which enabled me to see where Qt was breaking.


问:
Fluent NHibernate Upgrade to NH3.0 alpha
Hy
We want to use the latest alpha version of NHibernate. Unfortunately the latest fluent nhibernate release is built for 2.1 GA. When do you plan to upgrade to latest NH? Is there a source tree which I can fork to build the latest version from?

Daniel

答: You also can put AssemblyRedirect and use Fluent with latest Nhibernate. Fluent generates XML mappings, so everything should be fine.</p>


问:
Invariant Violation: _registerComponent(...): Target container is not a DOM element
I get this error after a making trivial React example page:

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

Here's my code:

```<code>/** @jsx React.DOM */
'use strict';

var React = require('react');

var App = React.createClass({
  render() {
    return <h1>Yo</h1>;
  }
});

React.renderComponent(<App />, document.body);
</code>```

HTML:

```<code><html>
<head>
  <script src="/bundle.js"></script>
</head>
<body>
</body>
</html>
</code>```

What does this mean?

答:
just a wild guess, how about adding to index.html the following:

```<code>type="javascript"
</code>```

like this:

```<code><script type="javascript" src="public/bundle.js"> </script>
</code>```

For me it worked! :-)

Body:
I get this error after a making trivial React example page:

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

Here's my code:

/** @jsx React.DOM */
'use strict';

var React = require('react');

var App = React.createClass({
  render() {
    return
Yo
;
  }
});

React.renderComponent(<App />, document.body);

HTML:

What does this mean?

Body:
just a wild guess, how about adding to index.html the following:

type="javascript"

like this:

<script type="javascript" src="public/bundle.js"> </script>

For me it worked! :-)


问:
String cannot be converted to JSONObject for a registration page
i am trying to make a registration page, and i have completed the xml page and i have written the activity java file
here is the code

```<code>public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etUserName = (EditText) findViewById(R.id.etUserName);
    final EditText etUserEmail = (EditText) findViewById(R.id.etUserEmail);
    final EditText etUserContactNo = (EditText) findViewById(R.id.etUserContactNo);
    final EditText etUserPassword = (EditText) findViewById(R.id.etUserPassword);
    final Button btnRegister = (Button) findViewById(R.id.btnRegister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String UserName = etUserName.getText().toString();
            final String UserContactNo = etUserContactNo.getText().toString();
            final String UserEmail = etUserEmail.getText().toString();
            final String UserPassword = etUserPassword.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success =  jsonResponse.getBoolean("success");

                        if (success){
                            Intent intent  = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Registration Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(UserName, UserPassword, UserContactNo, UserEmail, responseListener);
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);

        }
    });

}
</code>```

}

and the php file that is connected to the activity

```<code><?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>
</code>```

and the problem that i am facing, which is written in the android monitor

```<code>03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:43)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:39)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-30 20:39:24.125 1582-1595/system_process I/UsageStatsService: User[0] Flushing usage stats to disk
</code>```

答:
Add this header in your php, that´s the way to return only json without html

```<code>header('Content-Type: application/json');
echo json_encode($response);
</code>```

Now your php sholud look like this

```<code><?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response->success= true;

echo json_encode($response);
?>
</code>```

Body:
i am trying to make a registration page, and i have completed the xml page and i have written the activity java file
here is the code

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etUserName = (EditText) findViewById(R.id.etUserName);
    final EditText etUserEmail = (EditText) findViewById(R.id.etUserEmail);
    final EditText etUserContactNo = (EditText) findViewById(R.id.etUserContactNo);
    final EditText etUserPassword = (EditText) findViewById(R.id.etUserPassword);
    final Button btnRegister = (Button) findViewById(R.id.btnRegister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String UserName = etUserName.getText().toString();
            final String UserContactNo = etUserContactNo.getText().toString();
            final String UserEmail = etUserEmail.getText().toString();
            final String UserPassword = etUserPassword.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success =  jsonResponse.getBoolean("success");

                        if (success){
                            Intent intent  = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Registration Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(UserName, UserPassword, UserContactNo, UserEmail, responseListener);
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);

        }
    });

}

}

and the php file that is connected to the activity

<?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>

and the problem that i am facing, which is written in the android monitor

03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:43)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:39)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-30 20:39:24.125 1582-1595/system_process I/UsageStatsService: User[0] Flushing usage stats to disk

Body:
Add this header in your php, that´s the way to return only json without html

header('Content-Type: application/json');
echo json_encode($response);

Now your php sholud look like this

<?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response->success= true;

echo json_encode($response);
?>


问:
Invalid CREATE command when it is used with another command
I am trying to print query result using solution in that page.  The spool solution didn't work in my project but the other one worked in sqldeveloper. "run_query" procedure defined in that page. The problem is that it doesn't work in c# code. The code is like that:

```<code>cmd.CommandText = string.Format(@"CREATE OR REPLACE DIRECTORY TEST_DIR AS '{0}';
             exec run_query('SELECT {1} FROM  {2} {3} ORDER BY {4}','TEST_DIR','{5}');"
             ,strDirForFiles.Substring(0, strDirForFiles.Length - 2),
             strColToSelect, strTableName, strWhere, strColToSelect, strTMPFileName);
cmd.ExecuteNonQuery();
</code>```

In runtime the query is like that:

```<code>CREATE DIRECTORY TEST_DIR AS 'C:\\';
exec run_query('SELECT AccountNumber
                FROM  LowCreditList WHERE VersionNumber=1 AND ChangeStatus = 0
                ORDER BY AccountNumber','TEST_DIR','ASD.TMP');
</code>```

But that code throws an exception like that:

Message = "ERROR [HY000] [Oracle][ODBC][Ora]ORA-00901: invalid CREATE
  command\n"

When I execute just

```<code>CREATE DIRECTORY TEST_DIR AS 'C:\\';
</code>```

command, there is no exception.

I can not figure it out. It works in sqldeveloper but not in C#.

NOTE: I use Visual Studio as administrator.

答:
I don't know C# but I assume you can only send individual SQL statements or PL/SQL blocks, not a list separated by semicolons. In any case, exec is neither (it's a SQL*Plus shortcut supported by some IDEs.)

You probably need to send separate commands as something like:

```<code>create directory test_dir as 'C:\\'
</code>```

and

```<code>begin run_query('SELECT {1} FROM  {2} {3} ORDER BY {4}','TEST_DIR','{5}'); end;
</code>```

(Note PL/SQL uses semicolons but SQL has no native statement terminator, although tools often require a terminator character and semicolon is often the default.)

Body:
I am trying to print query result using solution in that page.  The spool solution didn't work in my project but the other one worked in sqldeveloper. "run_query" procedure defined in that page. The problem is that it doesn't work in c# code. The code is like that:

cmd.CommandText = string.Format(@"CREATE OR REPLACE DIRECTORY TEST_DIR AS '{0}';
             exec run_query('SELECT {1} FROM  {2} {3} ORDER BY {4}','TEST_DIR','{5}');"
             ,strDirForFiles.Substring(0, strDirForFiles.Length - 2),
             strColToSelect, strTableName, strWhere, strColToSelect, strTMPFileName);
cmd.ExecuteNonQuery();

In runtime the query is like that:

CREATE DIRECTORY TEST_DIR AS 'C:\\';
exec run_query('SELECT AccountNumber
                FROM  LowCreditList WHERE VersionNumber=1 AND ChangeStatus = 0
                ORDER BY AccountNumber','TEST_DIR','ASD.TMP');

But that code throws an exception like that:

Message = "ERROR [HY000] [Oracle][ODBC][Ora]ORA-00901: invalid CREATE
  command\n"

When I execute just

CREATE DIRECTORY TEST_DIR AS 'C:\\';

command, there is no exception.

I can not figure it out. It works in sqldeveloper but not in C#.

NOTE: I use Visual Studio as administrator.

Body:
I don't know C# but I assume you can only send individual SQL statements or PL/SQL blocks, not a list separated by semicolons. In any case, exec is neither (it's a SQL*Plus shortcut supported by some IDEs.)

You probably need to send separate commands as something like:

create directory test_dir as 'C:\\'

and

begin run_query('SELECT {1} FROM  {2} {3} ORDER BY {4}','TEST_DIR','{5}'); end;

(Note PL/SQL uses semicolons but SQL has no native statement terminator, although tools often require a terminator character and semicolon is often the default.)


问:
MS (Project) Find Strings in text10 and change font color
I'm changing the color of font in MS Project based on Percentage complete and Names in text10 column.  The percentages work however can someone give me a steer on the names I would be grateful, I want to highlight in teal if for example "David" or "Darren" or both are in Text10 field.

Any help gratefully received.

```<code>Sub text()

Dim Ctr As Integer

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"
SelectAll

For Ctr = 1 To ActiveSelection.Tasks.Count
    SelectRow Row:=Ctr, rowrelative:=False
    If Not ActiveSelection.Tasks(1) Is Nothing Then
        If ActiveSelection.Tasks(1).Text10 = ("David") & ("Darren") Then
            Font Color:=pjTeal
        Else
            If ActiveSelection.Tasks(1).PercentComplete = 100 Then
                Font Color:=pjGreen
            Else
                If ActiveSelection.Tasks(1).PercentComplete = 0 Then
                    Font Color:=pjBlack
                Else
                    If ActiveSelection.Tasks(1).PercentComplete > 0 < 100 Then
                        Font Color:=pjBlue
                    Else
                    End If
                End If
            End If
        End If
    End If
Next Ctr

End Sub
</code>```

答:
```<code>Sub test()

Dim Ctr As Integer

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"
SelectAll
For Ctr = 1 To ActiveSelection.Tasks.Count
    SelectRow Row:=Ctr, rowrelative:=False
    If Not ActiveSelection.Tasks(1) Is Nothing Then
        If ActiveSelection.Tasks(1).Text10 = "David" Then
            Font Color:=pjBlue
        Else
        If ActiveSelection.Tasks(1).Text10 = "Mary" Then
            Font Color:=pjTeal
        Else
        If ActiveSelection.Tasks(1).Text10 = "Bill" Then
            Font Color:=pjBlack
        Else
        If ActiveSelection.Tasks(1).Text10 = "Sandra" Then
            Font Color:=pjPurple
        Else
        If ActiveSelection.Tasks(1).PercentComplete = 100 Then
            Font Color:=pjGreen
        Else
        If ActiveSelection.Tasks(1).finish < currentdate Then
            Font Color:=pjRed
        End If
        End If
        End If
        End If
        End If
        End If
        End If
    Next Ctr
End Sub
</code>```

Body:
I'm changing the color of font in MS Project based on Percentage complete and Names in text10 column.  The percentages work however can someone give me a steer on the names I would be grateful, I want to highlight in teal if for example "David" or "Darren" or both are in Text10 field.

Any help gratefully received.

Sub text()

Dim Ctr As Integer

ViewApply "Gantt Chart"
OutlineShowAllTasks
FilterApply "All Tasks"
SelectAll

For Ctr = 1 To ActiveSelection.Tasks.Count
    SelectRow Row:=Ctr, rowrelative:=False
    If Not ActiveSelection.Tasks(1) Is Nothing Then
        If ActiveSelection.Tasks(1).Text10 = ("David") & ("Darren") Then
            Font Color:=pjTeal
        Else
            If ActiveSelection.Tasks(1).PercentComplete = 100 Then
                Font Color:=pjGreen
            Else
                If ActiveSelection.Tasks(1).PercentComplete = 0 Then
                    Font Color:=pjBlack
                Else
                    If ActiveSelection.Tasks(1).PercentComplete > 0 < 100 Then
                        Font Color:=pjBlue
                    Else
                    End If
                End If
            End If
        End If
    End If
Next Ctr

End Sub


问:
Lazy for html content
I'm using lazy for my images lazySizes plugin I'm looking for a way to do html content but I couldn't do that for html is there any way to do simply ? and my html structure

$('.lazy.teaser.lazy_content').on('lazyunveilread', function (ev) {

            data_url = $(this).attr("data-url");
            data_id = $(this).attr("data-target-id");

            $.ajax({
                url: data_url,
                type: "POST",
                beforeSend: function () {
                    $(".loaderDiv").show();
                    $("#" + data_id).html("");
                },
                success: function (data) {
                    $(".loaderDiv").hide();
                    $("#" + data_id).html(data);
                }

            })

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/3.0.0/lazysizes.min.js"></script>

<div class="trustyou-detail-box section lazy teaser lazy_content" data-url="/ajax/yorumlar/@Model.OtelBilgileri.seflink" data-expand="-210" data-target-id="ajax-content" id="yorumlar-area">
  <h4 class="tur-main-baslik section-head">YORUMLAR</h4>
  <div id="ajax-content"></div>
</div></code>```

I have data-url and data-target-id to get url and my content

答:
Yes, you can:

```<code><!-- The ID (id="ajax-content) is redundant -->
<div class="lazyload" data-url="...">
    <div class="loaderDiv"></div>
</div>

$(document).on('lazybeforeunveil', function(e) {
    var $target = $(e.target);
    $target.load($target.data('url'));
});
</code>```

http://jsfiddle.net/80hg2ykv/4/

Title: Lazy for html content

Body:
I'm using lazy for my images lazySizes plugin I'm looking for a way to do html content but I couldn't do that for html is there any way to do simply ? and my html structure

$('.lazy.teaser.lazy_content').on('lazyunveilread', function (ev) {

            data_url = $(this).attr("data-url");
            data_id = $(this).attr("data-target-id");

            $.ajax({
                url: data_url,
                type: "POST",
                beforeSend: function () {
                    $(".loaderDiv").show();
                    $("#" + data_id).html("");
                },
                success: function (data) {
                    $(".loaderDiv").hide();
                    $("#" + data_id).html(data);
                }

            })

        });

YORUMLAR

I have data-url and data-target-id to get url and my content

Body:
Yes, you can:

<!-- The ID (id="ajax-content) is redundant -->
<div class="lazyload" data-url="...">
    <div class="loaderDiv"></div>
</div>

$(document).on('lazybeforeunveil', function(e) {
    var $target = $(e.target);
    $target.load($target.data('url'));
});

http://jsfiddle.net/80hg2ykv/4/


问:
Decision trees in R, predicting one choice
I'm doing a tutorial with iris dataset on decision trees in R. Here is my code for the basic tutorial.

```<code>library(rpart)
install.packages('rpart.plot')
library(rpart.plot)

s = sample(150,100)

iris_train = iris[s,]
iris_test = iris[-s,]

dtm = rpart(Species~.,iris_train, method="class")

rpart.plot(dtm, type=4, extra=101)

p = predict(dtm,iris_test,type="class")
table(iris_test[,5],p)
</code>```

The table line gives me:

```<code>                 setosa versicolor virginica
    setosa         12          0         0
    versicolor      0         18         0
    virginica       0          3        17
</code>```

How would I go about if I am only interestted in the prediction of Virginica? Is there a possibility to merge the values of the rest so that I get a binary classification of Virginica vs Versicolor + Setosa?

答:
you can do what you want like that</p>

```<code>library(rpart)
install.packages('rpart.plot')
library(rpart.plot)

s = sample(150,100)
class <- which(iris$Species %in% c("versicolor","setosa"))

####################################
new_species = rep("virginica",nrow(iris))

new_species[class] <- "vers_seto"

iris$new_species <- new_species
####################################
iris_train = iris[s,-5]    # -5 Delete the old column Species (column number 5)

iris_test = iris[-s,-5]

dtm = rpart(new_species~.,iris_train, method="class")

rpart.plot(dtm, type=4, extra=101)

p = predict(dtm,iris_test,type="class")
table(iris_test[,5],p)
</code>```

Body:
I'm doing a tutorial with iris dataset on decision trees in R. Here is my code for the basic tutorial.

library(rpart)
install.packages('rpart.plot')
library(rpart.plot)

s = sample(150,100)

iris_train = iris[s,]
iris_test = iris[-s,]

dtm = rpart(Species~.,iris_train, method="class")

rpart.plot(dtm, type=4, extra=101)

p = predict(dtm,iris_test,type="class")
table(iris_test[,5],p)

The table line gives me:

                 setosa versicolor virginica
    setosa         12          0         0
    versicolor      0         18         0
    virginica       0          3        17

How would I go about if I am only interestted in the prediction of Virginica? Is there a possibility to merge the values of the rest so that I get a binary classification of Virginica vs Versicolor + Setosa?

Body:
you can do what you want like that

library(rpart)
install.packages('rpart.plot')
library(rpart.plot)

s = sample(150,100)
class <- which(iris$Species %in% c("versicolor","setosa"))

####################################
new_species = rep("virginica",nrow(iris))

new_species[class] <- "vers_seto"

iris$new_species <- new_species
####################################
iris_train = iris[s,-5]    # -5 Delete the old column Species (column number 5)

iris_test = iris[-s,-5]

dtm = rpart(new_species~.,iris_train, method="class")

rpart.plot(dtm, type=4, extra=101)

p = predict(dtm,iris_test,type="class")
table(iris_test[,5],p)


问:
Search file for zip code in bash grep/sed
Trying to find each line containing a zip code using sed/grep
can't figure out what im missing, and cant find anything like what i am after.

zip code is 4 digits.

答:
```<code>grep '\s[0-9]\{4\}\s' matches 4 digits which start and end with a whitespace.
</code>```

Is this what you want?

Body:
grep '\s[0-9]\{4\}\s' matches 4 digits which start and end with a whitespace.

Is this what you want?


问:
Error with Tuple in C# 2008
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

```<code>private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
</code>```

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

```<code>public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}
</code>```

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks

答:
Tuples are new in C# 4.0

Check the article linked to from this question, it explains their usage.

Will a future version of .NET support tuples in C#?

Title: Error with Tuple in C# 2008

Body:
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks