问:
How to express this existential type from Haskell in Scala?
I am trying to adapt this Haskell implementation of the type classes based solution of the expression problem to Scala.  My current code is below.  I'm having problems expressing the existential type Exp in Scala.

How can I achieve the same thing?

object ExpressionProblem {

  // class Eval a where
  //   eval :: a -> Int
  trait Eval[A] {
    def eval(expr: A): Int
  }

  // data Exp = forall t. Eval t => Expr t
  sealed abstract class Exp
  case class Expr[T](val e: T)(implicit ev: Eval[T]) extends Exp

  // instance Eval Exp where
  //   eval (Expr e) = eval e
  implicit val exprInstance = new Eval[Exp] {
    def eval(expr: Exp) = expr match { case Expr(e, ev) => ev.eval(e) }
  }
  //                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  //                                       here is the problem

  // data BaseExp = Const Int | Add Exp Exp | Mul Exp Exp
  sealed abstract class BaseExpr
  case class Const(c: Int) extends BaseExpr
  case class Add(lhs: Exp, rhs: Exp) extends BaseExpr
  case class Mul(lhs: Exp, rhs: Exp) extends BaseExpr

  // instance Eval BaseExp where
  //   eval (Const n) = n
  //   eval (Add a b) = eval a + eval b
  //   eval (Mul a b) = eval a * eval b
  implicit val baseExprInstance = new Eval[BaseExpr] {
    def eval(baseExpr: BaseExpr)(implicit e: Eval[Exp]): Int =
      baseExpr match {
        case Const(c)      => c
        case Add(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
        case Mul(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
      }
  }

  // TODO: Is there an easier way to make all of them implicitly convertible?
  //
  // The following doesn't seem to work:
  //
  //    implicit def baseExprToExp[T <: BaseExpr](t: T): Exp = Expr[BaseExpr](t)
  //
  implicit def constToExp(c: Const): Exp = Expr[BaseExpr](c)
  implicit def addToExp(a: Add): Exp = Expr[BaseExpr](a)
  implicit def mulToExp(m: Mul): Exp = Expr[BaseExpr](m)

  ///////////////////////////////////////////////
  // Possibly in another module/lib.
  ///////////////////////////////////////////////

  // data SubExp = Sub Exp Exp
  case class SubExpr(val lhs: Exp, val rhs: Exp)

  // instance Eval SubExp where
  //   eval (Sub a b) = eval a - eval b
  implicit val subExprInstance = new Eval[SubExpr] {
    def eval(subExpr: SubExpr)(implicit e: Eval[Exp]): Int =
      e.eval(subExpr.lhs) - e.eval(subExpr.rhs)
  }

  // Make it implicitly convertible to Exp.
  implicit def subExprToExp(s: SubExpr): Exp = Expr(s)

  object Test {
    val exprs: List[Exp] = List(
      SubExpr(Const(10), Const(3)),
      Add(Const(1), Const(1))
    )
  }

} // ExpressionProblem
```

<p><strong>EDIT</strong>:  Meanwhile I found this relevant StackOverflow answer and I adapted my code to it.</p>

```import scala.language.implicitConversions

object ExpressionProblem {

  // class Eval a where
  //   eval :: a -> Int
  trait Eval[A] {
    def eval(expr: A): Int
  }

  //////////////////////////////////////////
  // HERE'S THE MAGIC
  //
  // data Expr = forall t. Eval t => Expr t
  trait Expr {
    type T
    val t: T
    val evalInst: Eval[T]
  }

  object Expr {
    def apply[T0 : Eval](t0: T0) = new Expr {
      type T = T0
      val t = t0
      val evalInst = implicitly[Eval[T]]
    }
  }

  // Default boxing is needed
  implicit def box[T : Eval](t: T) = Expr(t)

  // instance Eval Expr where
  //   eval (Expr e) = eval e
  implicit object exprInstance extends Eval[Expr] {
    def eval(expr: Expr) = expr.evalInst.eval(expr.t)
  }

  // data BaseExpr = Const Int | Add Expr Expr | Mul Expr Exp
  sealed abstract class BaseExpr
  case class Const(c: Int) extends BaseExpr
  case class Add(lhs: Expr, rhs: Expr) extends BaseExpr
  case class Mul(lhs: Expr, rhs: Expr) extends BaseExpr

  // instance Eval BaseExpr where
  //   eval (Const n) = n
  //   eval (Add a b) = eval a + eval b
  //   eval (Mul a b) = eval a * eval b
  implicit object baseExprInstance extends Eval[BaseExpr] {
    def eval(baseExpr: BaseExpr): Int =
      baseExpr match {
        case Const(c)      => c
        case Add(lhs, rhs) => exprInstance.eval(lhs) + exprInstance.eval(rhs)
        case Mul(lhs, rhs) => exprInstance.eval(lhs) + exprInstance.eval(rhs)
      }
  }

  // Implicit conversions for all base expressions
  implicit def baseExprToExpr[T <: BaseExpr](t: T): Expr = Expr[BaseExpr](t)

  ///////////////////////////////////////////////
  // Possibly somewhere else (in the future).
  ///////////////////////////////////////////////

  // data SubExpr = Sub Expr Exp
  case class SubExpr(val lhs: Expr, val rhs: Expr)

  // instance Eval SubExpr where
  //   eval (Sub a b) = eval a - eval b
  implicit object subExprInstance extends Eval[SubExpr] {
    def eval(subExpr: SubExpr): Int =
      exprInstance.eval(subExpr.lhs) - exprInstance.eval(subExpr.rhs)
  }

  // NOTE: We don't have to provide an implicit conversion to Expr as the
  // default `box` one suffices.

  object Test {
    val exprs: List[Expr] = List(
      SubExpr(Const(10), Const(3)),
      Add(Const(1), Const(1))
    )
  }

} // ExpressionProblem
```

答:
Your problem is that you are using an extractor (unapply), but neglecting the fact that implicits are not by default exposed as part of unapply.

So this line:

```<code>def eval(expr: Exp) = expr match { case Expr(e, ev) => ev.eval(e) }
</code>```

There is no case Expr(e, ev), only case Expr(e), because only e is exposed. Either write a custom extractor or find a different approach.

Scala does offer existential types of the form:

```<code>Expr[T] forSome { type T})
</code>```

That has a shorthand type notation available: Expr[_]

Your code has a few more issues though:

If you define an implicit on eval, all implementors must implement an eval function with that particular signature, you can't override eval with an implementation that doesn't contain the implicit in the signature like you do in.

```<code> implicit val baseExprInstance = new Eval[BaseExpr] {
    def eval(baseExpr: BaseExpr)(implicit e: Eval[Exp]): Int =
      baseExpr match {
        case Const(c)      => c
        case Add(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
        case Mul(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
      }
  }
</code>```

Next up you are going to need to either make T on Expr contravariant or make SubExpr also extend Exp, you have a problem here:

```<code>  // instance Eval SubExp where
  //   eval (Sub a b) = eval a - eval b
  implicit val subExprInstance = new Eval[SubExpr] {
    def eval(subExpr: SubExpr)(implicit e: Eval[SubExpr]): Int =
      e.eval(subExpr.lhs) - e.eval(subExpr.rhs)
  }
</code>```

If you will try to match the type signature, implicit e: Eval[SubExpr] can eval types that are T >: SubExpr, but what you require is a lower Exp implicit for Eval.

Body:
I am trying to adapt this Haskell implementation of the type classes based solution of the expression problem to Scala.  My current code is below.  I'm having problems expressing the existential type Exp in Scala.

How can I achieve the same thing?

object ExpressionProblem {

  // class Eval a where
  //   eval :: a -> Int
  trait Eval[A] {
    def eval(expr: A): Int
  }

  // data Exp = forall t. Eval t => Expr t
  sealed abstract class Exp
  case class Expr[T](val e: T)(implicit ev: Eval[T]) extends Exp

  // instance Eval Exp where
  //   eval (Expr e) = eval e
  implicit val exprInstance = new Eval[Exp] {
    def eval(expr: Exp) = expr match { case Expr(e, ev) => ev.eval(e) }
  }
  //                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  //                                       here is the problem

  // data BaseExp = Const Int | Add Exp Exp | Mul Exp Exp
  sealed abstract class BaseExpr
  case class Const(c: Int) extends BaseExpr
  case class Add(lhs: Exp, rhs: Exp) extends BaseExpr
  case class Mul(lhs: Exp, rhs: Exp) extends BaseExpr

  // instance Eval BaseExp where
  //   eval (Const n) = n
  //   eval (Add a b) = eval a + eval b
  //   eval (Mul a b) = eval a * eval b
  implicit val baseExprInstance = new Eval[BaseExpr] {
    def eval(baseExpr: BaseExpr)(implicit e: Eval[Exp]): Int =
      baseExpr match {
        case Const(c)      => c
        case Add(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
        case Mul(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
      }
  }

  // TODO: Is there an easier way to make all of them implicitly convertible?
  //
  // The following doesn't seem to work:
  //
  //    implicit def baseExprToExp[T <: BaseExpr](t: T): Exp = Expr[BaseExpr](t)
  //
  implicit def constToExp(c: Const): Exp = Expr[BaseExpr](c)
  implicit def addToExp(a: Add): Exp = Expr[BaseExpr](a)
  implicit def mulToExp(m: Mul): Exp = Expr[BaseExpr](m)

  ///////////////////////////////////////////////
  // Possibly in another module/lib.
  ///////////////////////////////////////////////

  // data SubExp = Sub Exp Exp
  case class SubExpr(val lhs: Exp, val rhs: Exp)

  // instance Eval SubExp where
  //   eval (Sub a b) = eval a - eval b
  implicit val subExprInstance = new Eval[SubExpr] {
    def eval(subExpr: SubExpr)(implicit e: Eval[Exp]): Int =
      e.eval(subExpr.lhs) - e.eval(subExpr.rhs)
  }

  // Make it implicitly convertible to Exp.
  implicit def subExprToExp(s: SubExpr): Exp = Expr(s)

  object Test {
    val exprs: List[Exp] = List(
      SubExpr(Const(10), Const(3)),
      Add(Const(1), Const(1))
    )
  }

} // ExpressionProblem

EDIT:  Meanwhile I found this relevant StackOverflow answer and I adapted my code to it.

import scala.language.implicitConversions

object ExpressionProblem {

  // class Eval a where
  //   eval :: a -> Int
  trait Eval[A] {
    def eval(expr: A): Int
  }

  //////////////////////////////////////////
  // HERE'S THE MAGIC
  //
  // data Expr = forall t. Eval t => Expr t
  trait Expr {
    type T
    val t: T
    val evalInst: Eval[T]
  }

  object Expr {
    def apply[T0 : Eval](t0: T0) = new Expr {
      type T = T0
      val t = t0
      val evalInst = implicitly[Eval[T]]
    }
  }

  // Default boxing is needed
  implicit def box[T : Eval](t: T) = Expr(t)

  // instance Eval Expr where
  //   eval (Expr e) = eval e
  implicit object exprInstance extends Eval[Expr] {
    def eval(expr: Expr) = expr.evalInst.eval(expr.t)
  }

  // data BaseExpr = Const Int | Add Expr Expr | Mul Expr Exp
  sealed abstract class BaseExpr
  case class Const(c: Int) extends BaseExpr
  case class Add(lhs: Expr, rhs: Expr) extends BaseExpr
  case class Mul(lhs: Expr, rhs: Expr) extends BaseExpr

  // instance Eval BaseExpr where
  //   eval (Const n) = n
  //   eval (Add a b) = eval a + eval b
  //   eval (Mul a b) = eval a * eval b
  implicit object baseExprInstance extends Eval[BaseExpr] {
    def eval(baseExpr: BaseExpr): Int =
      baseExpr match {
        case Const(c)      => c
        case Add(lhs, rhs) => exprInstance.eval(lhs) + exprInstance.eval(rhs)
        case Mul(lhs, rhs) => exprInstance.eval(lhs) + exprInstance.eval(rhs)
      }
  }

  // Implicit conversions for all base expressions
  implicit def baseExprToExpr[T <: BaseExpr](t: T): Expr = Expr[BaseExpr](t)

  ///////////////////////////////////////////////
  // Possibly somewhere else (in the future).
  ///////////////////////////////////////////////

  // data SubExpr = Sub Expr Exp
  case class SubExpr(val lhs: Expr, val rhs: Expr)

  // instance Eval SubExpr where
  //   eval (Sub a b) = eval a - eval b
  implicit object subExprInstance extends Eval[SubExpr] {
    def eval(subExpr: SubExpr): Int =
      exprInstance.eval(subExpr.lhs) - exprInstance.eval(subExpr.rhs)
  }

  // NOTE: We don't have to provide an implicit conversion to Expr as the
  // default `box` one suffices.

  object Test {
    val exprs: List[Expr] = List(
      SubExpr(Const(10), Const(3)),
      Add(Const(1), Const(1))
    )
  }

} // ExpressionProblem

Body:
Your problem is that you are using an extractor (unapply), but neglecting the fact that implicits are not by default exposed as part of unapply.

So this line:

def eval(expr: Exp) = expr match { case Expr(e, ev) => ev.eval(e) }

There is no case Expr(e, ev), only case Expr(e), because only e is exposed. Either write a custom extractor or find a different approach.

Scala does offer existential types of the form:

Expr[T] forSome { type T})

That has a shorthand type notation available: Expr[_]

Your code has a few more issues though:

If you define an implicit on eval, all implementors must implement an eval function with that particular signature, you can't override eval with an implementation that doesn't contain the implicit in the signature like you do in.

 implicit val baseExprInstance = new Eval[BaseExpr] {
    def eval(baseExpr: BaseExpr)(implicit e: Eval[Exp]): Int =
      baseExpr match {
        case Const(c)      => c
        case Add(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
        case Mul(lhs, rhs) => e.eval(lhs) + e.eval(rhs)
      }
  }

Next up you are going to need to either make T on Expr contravariant or make SubExpr also extend Exp, you have a problem here:

  // instance Eval SubExp where
  //   eval (Sub a b) = eval a - eval b
  implicit val subExprInstance = new Eval[SubExpr] {
    def eval(subExpr: SubExpr)(implicit e: Eval[SubExpr]): Int =
      e.eval(subExpr.lhs) - e.eval(subExpr.rhs)
  }

If you will try to match the type signature, implicit e: Eval[SubExpr] can eval types that are T >: SubExpr, but what you require is a lower Exp implicit for Eval.


来源: stackexchange

问:
What is the direct python/pandas equivalent of R/caret's str function, for factors?
I would specifically like a function that displays the levels for a factor/categorical variable, as does str() in R/caret.

For example, in R we have:

```<code>data(iris)
str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
</code>```

How would I accomplish this exactly in python/pandas?

Neither dataFrame.describe() nor dataFrame.info() would get this right for iris$Species.

答:
the simplest would be</p>

```<code>df.Species.value_counts()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would specifically like a function that displays the levels for a factor/categorical variable, as does str() in R/caret.

For example, in R we have:

data(iris)
str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

How would I accomplish this exactly in python/pandas?

Neither dataFrame.describe() nor dataFrame.info() would get this right for iris$Species.

Body:
the simplest would be

df.Species.value_counts()


问:
Python- if statement evaluation pattern
what the heck is the if statement doing?

```<code>>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])
</code>```

and this will result in ['e', 'f']

I dont know that the if is doing.

答:
the if statement is deleting elements in you list at indices greater than  or equal to 2.

if i/2: will evaluate to true when i/2 is not 0. i.e. index>=2.

Title: Python- if statement evaluation pattern

Body:
what the heck is the if statement doing?

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])

and this will result in ['e', 'f']

I dont know that the if is doing.


问:
mysql PDO and stored procedure dynamic SQL injection
As I have seen in many posts, dynamic SQL in stored procedure is vulnerable to SQL injection. But if we use previously PDO with prepared statement this still be unsafe?

Example:

```<code>CREATE PROCEDURE my_sp(
  IN in_var VARCHAR(32)
)
BEGIN
    DECLARE query VARCHAR(255);

    SET @query = CONCAT("SELECT * FROM my_table  WHERE my_column = '",in_var,"' LIMIT 1;";

    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END;

$dbh = new PDO( $connection_params );
$dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND,"SET NAMES utf8mb4");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$sql = "CALL my_sp( :in_var )";
$stmt = $dbh->prepare( $sql );
$stmt->execute( array( ':in_var' => $_POST['in_var'] ) );
</code>```

EDITED:

Sorry for rectivate that question again but there is something that is not clear to me yet.

Example:

```<code>/* php */
$in_var = " ' OR '1' = '1'; -- ";

/*If I try with PDO without prepared statement and
without calling a stored procedure THAT WORK ... the injection is succesful*/
$sql = "SELECT * FROM my_table  WHERE my_column = '$in_var' ";

/*With prepared statement NO RESULTS no errors so no injection*/
$sql = "SELECT * FROM my_table  WHERE my_column = :in_var ";

/*Now if I call a Stored Procedure with prepared statement in PDO PHP
but in the procedure I have not used prepared statement that return NO RESULTS no errors so no injection
*/
$sql = "CALL my_sp( :in_var )";

/*If I call the Stored procedure without prepared statement in PDO PHP
that got an PDO error:
Syntax error or access violation: 1064 ...
But seem that injection was not succesful
*/
$sql = "CALL my_sp( '$in_var' )";
</code>```

I am a beginner and I know that my logic may not be good, but it seems that when using prepared statement in PDO the injection does not happen although it is not used again prepared statement inside the procedure.

答:
Yes, of course.

What if in_var is equal to ' UNION SELECT password from admins --?

To avoid that, you should use not a cargo cult prepared statement but a real one, substituting your variable with a placeholder.

```<code>SET @query = CONCAT("SELECT * FROM my_table  WHERE my_column = ? LIMIT 1;");

PREPARE stmt FROM @query;
EXECUTE stmt USING @in_var;
</code>```

Body:
As I have seen in many posts, dynamic SQL in stored procedure is vulnerable to SQL injection. But if we use previously PDO with prepared statement this still be unsafe?

Example:

CREATE PROCEDURE my_sp(
  IN in_var VARCHAR(32)
)
BEGIN
    DECLARE query VARCHAR(255);

    SET @query = CONCAT("SELECT * FROM my_table  WHERE my_column = '",in_var,"' LIMIT 1;";

    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END;

$dbh = new PDO( $connection_params );
$dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND,"SET NAMES utf8mb4");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$sql = "CALL my_sp( :in_var )";
$stmt = $dbh->prepare( $sql );
$stmt->execute( array( ':in_var' => $_POST['in_var'] ) );

EDITED:

Sorry for rectivate that question again but there is something that is not clear to me yet.

Example:

/* php */
$in_var = " ' OR '1' = '1'; -- ";

/*If I try with PDO without prepared statement and
without calling a stored procedure THAT WORK ... the injection is succesful*/
$sql = "SELECT * FROM my_table  WHERE my_column = '$in_var' ";

/*With prepared statement NO RESULTS no errors so no injection*/
$sql = "SELECT * FROM my_table  WHERE my_column = :in_var ";

/*Now if I call a Stored Procedure with prepared statement in PDO PHP
but in the procedure I have not used prepared statement that return NO RESULTS no errors so no injection
*/
$sql = "CALL my_sp( :in_var )";

/*If I call the Stored procedure without prepared statement in PDO PHP
that got an PDO error:
Syntax error or access violation: 1064 ...
But seem that injection was not succesful
*/
$sql = "CALL my_sp( '$in_var' )";

I am a beginner and I know that my logic may not be good, but it seems that when using prepared statement in PDO the injection does not happen although it is not used again prepared statement inside the procedure.

Body:
Yes, of course.

What if in_var is equal to ' UNION SELECT password from admins --?

To avoid that, you should use not a cargo cult prepared statement but a real one, substituting your variable with a placeholder.

SET @query = CONCAT("SELECT * FROM my_table  WHERE my_column = ? LIMIT 1;");

PREPARE stmt FROM @query;
EXECUTE stmt USING @in_var;


问:
Mysql(GroupBy) alternative for Postgresql?
I am using laravel with mysql..

I have query something like this..

```<code>$mix = Ergebnisse::where(function($q) use($result) {
    foreach ($result as $item) {
         $q->orWhere(function($q) use($item) {
             $q->where('temperatur', $item->temperatur)
               ->where('zeit', $item->zeit);
        });
    }
})->groupBy('katogorie_id')->get();
</code>```

on my localhost it is working fine as i am using mysql there.
but i deployed the project on Heroku with Postgresql.

I got an error..

```<code>SQLSTATE[42803]: Grouping error: 7 ERROR: column "ergebnisse.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "ergebnisse" where (("temperatur" = $1 and "ze...
^ (SQL: select * from "ergebnisse" where (("temperatur" = 85 and "zeit" = 35) or ("temperatur" = 85 and "zeit" = 30)) group by "katogorie_id")
</code>```

after further searching i came to know that GroupBy is not compatible with postgre. is there any other way of doing that? thanks

答:
You SELECT * but GROUP BY katogorie_id. In short, you need to GROUP BY all columns that you are SELECTing. This is in contrast to MySQL old behavior accepting non-standard GROUP BY usage.

So either add more columns to your group by or select less columns (I doubt you need SELECT *).

Body:
I am using laravel with mysql..

I have query something like this..

$mix = Ergebnisse::where(function($q) use($result) {
    foreach ($result as $item) {
         $q->orWhere(function($q) use($item) {
             $q->where('temperatur', $item->temperatur)
               ->where('zeit', $item->zeit);
        });
    }
})->groupBy('katogorie_id')->get();

on my localhost it is working fine as i am using mysql there.
but i deployed the project on Heroku with Postgresql.

I got an error..

SQLSTATE[42803]: Grouping error: 7 ERROR: column "ergebnisse.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "ergebnisse" where (("temperatur" = $1 and "ze...
^ (SQL: select * from "ergebnisse" where (("temperatur" = 85 and "zeit" = 35) or ("temperatur" = 85 and "zeit" = 30)) group by "katogorie_id")

after further searching i came to know that GroupBy is not compatible with postgre. is there any other way of doing that? thanks


问:
Set custom publish date, but publish now if it's empty
I am trying to make a custom publish date, because the user wants to use that as the publishing date and for sorting. The date will also be displayed on the page.

Here is what I want:

The user can input a date

The date can be empty (meaning it will be published now)

It has to use that date for sorting

The date has to be set to UTC time, so it's equal for everyone in the world

I am desperate and I cannot figure out how to do this.

Here is what I have tried so far: I found a neat little plugin, which displays the user's current UTC time next to the input field, so the person knows their UTC time. I modified that to always enter the current date in the input field:

```<code>var timer = setInterval(function () {
    var date = $(".custom-date").val();
    if (date === "") {
        $(".custom-date").focus();
        $(".custom-date").click();
        $(".custom-date").trigger("click");
        //the date has now been set on the input field
    } else if (date !== "") {
        var newDate = new Date(date);
        var stringDate = newDate.getFullYear() + "-" + ('0' + (newDate.getMonth() + 1)).slice(-2) + "-" + ('0' + (newDate.getDate() - 1)).slice(-2) + " " + ('0' + (newDate.getHours() - offset)).slice(-2) + ":" + ('0' + newDate.getMinutes()).slice(-2) + ":" + ('0' + newDate.getSeconds()).slice(-2);
        $(".custom-date").val(stringDate);
        angular.element(".custom-date").scope().$apply(function () {
            angular.element(".custom-date").scope().datetimePickerValue = stringDate;
        });
        clearInterval(timer);
    }
}, 1000);
</code>```

Yes, this looks like a lot... and no, it does not work. I do the focus/click/trigger on the element, because that will automatically set the time to be the user's local time. I then turn that into UTC time (offset is the UTC time offset). Then I apply the date to the element's scope and the value gets updated both in $scope and in the view (I can actually see it).

However, when I hit save and publish, the date gets reset (it's empty in the database). It's only when I physically click on the input field and select a new date it will actually update it. I like this method, as I am in 100% control of it, so is it possible? It would seem like setting the new date on the scope doesn't trigger the actual "new date has been selected".

Alternatively I have my Razor code here:

```<code>//selection is all my elements/nodes
selection.OrderByDescending(x => x.GetProperty("publishDate") != null).ThenByDescending(x => x.GetPropertyValue("publishDate")).Where(x => x.GetPropertyValue<DateTime>("publishDate") < DateTime.UtcNow);
</code>```

答:
So apparently before the Angular event is triggered, I need to, at least, call these:

```<code>$(".custom-date").trigger("click");
$(".custom-date").change();
</code>```

So I did that right after I set my new date and now it works.

Body:
I am trying to make a custom publish date, because the user wants to use that as the publishing date and for sorting. The date will also be displayed on the page.

Here is what I want:

The user can input a date

The date can be empty (meaning it will be published now)

It has to use that date for sorting

The date has to be set to UTC time, so it's equal for everyone in the world

I am desperate and I cannot figure out how to do this.

Here is what I have tried so far: I found a neat little plugin, which displays the user's current UTC time next to the input field, so the person knows their UTC time. I modified that to always enter the current date in the input field:

var timer = setInterval(function () {
    var date = $(".custom-date").val();
    if (date === "") {
        $(".custom-date").focus();
        $(".custom-date").click();
        $(".custom-date").trigger("click");
        //the date has now been set on the input field
    } else if (date !== "") {
        var newDate = new Date(date);
        var stringDate = newDate.getFullYear() + "-" + ('0' + (newDate.getMonth() + 1)).slice(-2) + "-" + ('0' + (newDate.getDate() - 1)).slice(-2) + " " + ('0' + (newDate.getHours() - offset)).slice(-2) + ":" + ('0' + newDate.getMinutes()).slice(-2) + ":" + ('0' + newDate.getSeconds()).slice(-2);
        $(".custom-date").val(stringDate);
        angular.element(".custom-date").scope().$apply(function () {
            angular.element(".custom-date").scope().datetimePickerValue = stringDate;
        });
        clearInterval(timer);
    }
}, 1000);

Yes, this looks like a lot... and no, it does not work. I do the focus/click/trigger on the element, because that will automatically set the time to be the user's local time. I then turn that into UTC time (offset is the UTC time offset). Then I apply the date to the element's scope and the value gets updated both in $scope and in the view (I can actually see it).

However, when I hit save and publish, the date gets reset (it's empty in the database). It's only when I physically click on the input field and select a new date it will actually update it. I like this method, as I am in 100% control of it, so is it possible? It would seem like setting the new date on the scope doesn't trigger the actual "new date has been selected".

Alternatively I have my Razor code here:

//selection is all my elements/nodes
selection.OrderByDescending(x => x.GetProperty("publishDate") != null).ThenByDescending(x => x.GetPropertyValue("publishDate")).Where(x => x.GetPropertyValue<DateTime>("publishDate") < DateTime.UtcNow);

Body:
So apparently before the Angular event is triggered, I need to, at least, call these:

$(".custom-date").trigger("click");
$(".custom-date").change();

So I did that right after I set my new date and now it works.


问:
Is there a way to verify that a method on Spring Controller was called using Mockito
This is my Mockito Test:

```<code>@RunWith(MockitoJUnitRunner.class)
public class Controller_Test {

    private MockMvc mockMvc;

    @InjectMocks
    private EmployeeController employeeController;

    @Mock
    private InputValidationService inputValidationService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(restController).build();

    }

    @Test
    public void testGetEmployeeDetails() {

        EmployeeController spy = Mockito.spy(employeeController);
        MvcResult result = mockMvc.perform(get("/employee/details/9816")).andDo(print()).andExpect(status().isOk()).andReturn();

    // Have some basic asserts here on the result that are working fine

    }

    }
</code>```

Now my question is, Is there a way to assert that the method I expected to be called in my controller was actually invoked.

I know it was, but how do I assert it with unit test

For e.g.
This is my RequestMapping in the controller:

```<code>@RequestMapping(value = "/employee/details/{id}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
    @ResponseStatus( HttpStatus.OK)
    @ResponseBody
    public EmployeeDetails getEmployeeDetailsById(@PathVariable String employeeID) {

    //Some business logic

    }
</code>```

Now I would like to make some assertion like:

```<code>Mockito.verify(spy, times(1)).getEmployeeDetailsById();
</code>```

So basically I would like to assert that the  method I expected to get called was the one that got called. I know this can be done on the Mock Service object that I have i.e. inputValidationService but would like something similar for the controller as well.

Please let me know if there are any additional details that you would like me to post.

答:
You can use @MockBean.This will use Mockito beans for which you will be able to use standart Mockito functions like "verify".

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans

Body:
This is my Mockito Test:

@RunWith(MockitoJUnitRunner.class)
public class Controller_Test {

    private MockMvc mockMvc;

    @InjectMocks
    private EmployeeController employeeController;

    @Mock
    private InputValidationService inputValidationService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(restController).build();

    }

    @Test
    public void testGetEmployeeDetails() {

        EmployeeController spy = Mockito.spy(employeeController);
        MvcResult result = mockMvc.perform(get("/employee/details/9816")).andDo(print()).andExpect(status().isOk()).andReturn();

    // Have some basic asserts here on the result that are working fine

    }

    }

Now my question is, Is there a way to assert that the method I expected to be called in my controller was actually invoked.

I know it was, but how do I assert it with unit test

For e.g.
This is my RequestMapping in the controller:

@RequestMapping(value = "/employee/details/{id}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
    @ResponseStatus( HttpStatus.OK)
    @ResponseBody
    public EmployeeDetails getEmployeeDetailsById(@PathVariable String employeeID) {

    //Some business logic

    }

Now I would like to make some assertion like:

Mockito.verify(spy, times(1)).getEmployeeDetailsById();

So basically I would like to assert that the  method I expected to get called was the one that got called. I know this can be done on the Mock Service object that I have i.e. inputValidationService but would like something similar for the controller as well.

Please let me know if there are any additional details that you would like me to post.


问:
Hidden features of Scala
What are the hidden features of Scala that every Scala developer should be aware of?

One hidden feature per answer, please.

答:
You can compose structural types with the 'with' keyword</p>

```<code>object Main {
  type A = {def foo: Unit}
  type B = {def bar: Unit}

  type C = A with B

  class myA {
    def foo: Unit = println("myA.foo")
  }

  class myB {
    def bar: Unit = println("myB.bar")
  }
  class myC extends myB {
    def foo: Unit = println("myC.foo")
  }

  def main(args: Array[String]): Unit = {
    val a: A = new myA
    a.foo
    val b: C = new myC
    b.bar
    b.foo
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Hidden features of Scala

LastEditorDisplayName: Roger Pate

Body:
You can compose structural types with the 'with' keyword

object Main {
  type A = {def foo: Unit}
  type B = {def bar: Unit}

  type C = A with B

  class myA {
    def foo: Unit = println("myA.foo")
  }

  class myB {
    def bar: Unit = println("myB.bar")
  }
  class myC extends myB {
    def foo: Unit = println("myC.foo")
  }

  def main(args: Array[String]): Unit = {
    val a: A = new myA
    a.foo
    val b: C = new myC
    b.bar
    b.foo
  }
}


问:
Escaping Quotes in Chef Bash
This I need quotes in a cronjob which I am creating through a chef recipe but even though I escape the quotes they do not appear in the cronjob which is created.

```<code>bash "Add cron" do
  user root
  group root
  code <<-EOH
      (
        (crontab -l; echo "5 0 * * * /bin/find #{node['user']['dir']}/files/ -type f \\( -name \"*.csv\" -o -name \"*.csv.bad\" -o -name \"*.ctrl\" \\) -mtime +1 -print0 | xargs -0 gzip -f" ) | crontab -
       )
  EOH
end
</code>```

just to clarify the cron job I want to end up with should contain -name "*.csv"

but what I actually get is -name *.csv

答:
```<code>bash "Add cron" do
  user "root"
  group "root"
  code <<-EOH
      (
        (crontab -l; echo -e '5 0 * * * /bin/find /home/root/files/ -type f \\( -name \"*.csv\" -o -name \"*.csv.bad\" -o -name \"*.ctrl\" \\) -mtime +1 -print0 | xargs -0 gzip -f'
       )
  EOH
end
</code>```

Use single quote instead of double here.

Title: Escaping Quotes in Chef Bash

Body:
This I need quotes in a cronjob which I am creating through a chef recipe but even though I escape the quotes they do not appear in the cronjob which is created.

bash "Add cron" do
  user root
  group root
  code <<-EOH
      (
        (crontab -l; echo "5 0 * * * /bin/find #{node['user']['dir']}/files/ -type f \\( -name \"*.csv\" -o -name \"*.csv.bad\" -o -name \"*.ctrl\" \\) -mtime +1 -print0 | xargs -0 gzip -f" ) | crontab -
       )
  EOH
end

just to clarify the cron job I want to end up with should contain -name "*.csv"

but what I actually get is -name *.csv

Body:
bash "Add cron" do
  user "root"
  group "root"
  code <<-EOH
      (
        (crontab -l; echo -e '5 0 * * * /bin/find /home/root/files/ -type f \\( -name \"*.csv\" -o -name \"*.csv.bad\" -o -name \"*.ctrl\" \\) -mtime +1 -print0 | xargs -0 gzip -f'
       )
  EOH
end

Use single quote instead of double here.


问:
Exception on using ng2-tag-input
I am using ng-tag-input for tags input. I have followed the steps in the getting started in this link.

Getting the following error:

```<code> Found the synthetic property @flyInOut. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.
</code>```

Here's my package.json, I suspect this has something to do with versioning.
Also cant find the BrowserAnimationsModule in any of the packages.:

```<code>    {
  "name": "angular-demo",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
    "lint": "tslint ./app/**/*.ts -t verbose",
    "lite": "lite-server",
    "pree2e": "webdriver-manager update",
    "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
    "test-once": "tsc && karma start karma.conf.js --single-run",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.2",
    "core-js": "^2.4.1",
    "ng2-bootstrap": "^1.4.2",
    "ng2-bs-dropdown": "^0.7.0",
    "ng2-tag-input": "^0.9.0",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "systemjs": "0.19.40",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "concurrently": "^3.1.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.0.10",
    "canonical-path": "0.0.2",
    "http-server": "^0.9.0",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "@types/node": "^6.0.46",
    "@types/jasmine": "^2.5.36"
  },
  "repository": {}
}
</code>```

答:
Try to install the package this will fix the issue.

```<code>npm install --save @angular/animations
</code>```

Import this is in your app.module.ts file

```<code>import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
  ...
  imports: [BrowserAnimationsModule],
  ...
})
export class PizzaPartyAppModule { }
</code>```

Title: Exception on using ng2-tag-input

Body:
I am using ng-tag-input for tags input. I have followed the steps in the getting started in this link.

Getting the following error:

 Found the synthetic property @flyInOut. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.

Here's my package.json, I suspect this has something to do with versioning.
Also cant find the BrowserAnimationsModule in any of the packages.:

    {
  "name": "angular-demo",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
    "lint": "tslint ./app/**/*.ts -t verbose",
    "lite": "lite-server",
    "pree2e": "webdriver-manager update",
    "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
    "test-once": "tsc && karma start karma.conf.js --single-run",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.2",
    "core-js": "^2.4.1",
    "ng2-bootstrap": "^1.4.2",
    "ng2-bs-dropdown": "^0.7.0",
    "ng2-tag-input": "^0.9.0",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "systemjs": "0.19.40",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "concurrently": "^3.1.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.0.10",
    "canonical-path": "0.0.2",
    "http-server": "^0.9.0",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "@types/node": "^6.0.46",
    "@types/jasmine": "^2.5.36"
  },
  "repository": {}
}

Body:
Try to install the package this will fix the issue.

npm install --save @angular/animations

Import this is in your app.module.ts file

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
  ...
  imports: [BrowserAnimationsModule],
  ...
})
export class PizzaPartyAppModule { }


问:
What is needed to be done to migrate chaincode from v0.6 to v1.0?
I wrote some Hyperledger Fabric chaincode for v0.6 in Golang, and I want to use v0.6 chaincode in v1.0.

How should I migrate the chaincode from v0.6 to v1.0?
What is the difference between v0.6 and v1.0 from chaincode perspective?

答: This article might help you. It's a document about the migration of the Auction chaincode from v0.6  to v1.0</p>


问:
Best practice for uninstalling software with PowerShell
Like a lot of other applications out there the BlueJeans Desktop App MSI comes in two flavours: Per User MSI & Per Machine MSI.

Today, it is possible to have both installed on the same machine, but I have an increasing number of customers who have users with both installed and want to be able to clean it up. I have put together a cleanup script that handles uninstalling our application, but what I need to know from the community is whether I should utilize PowerShell to connect to each machine and run the script remotely or deploy the script via SCCM, IBM BigFix etc. to each machine and run the script locally?

A copy of my script can be found here: https://github.com/stuartminch/powershell/blob/master/cleanup_utility.ps1

答:
If you have two separate MSI installers (User MSI & Per Machine MSI) the easiest way would be to use MSI {GUID} to uninstall them.

example msiexec.exe /x {GUID} /q

If you have them installed on a machine you can find uninstall string with GUID under

"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{GUID}\UninstallString

You can then configure it in SCCM.

Best practice would be to configure the deployment along with uninstall so if you deployed it through SCCM just add Uninstall commands there.


问:
Update progress bar from Task.Run async
I have a method to generate software activation key from User Information:

```<code>private async void GenerateAsync()
        {
            await Task.Run(() =>
            {
                var secretstring = "CustomerName >> " + txtFullname.Text + " >> " + txtproducid.Text;
                keymng = new KeyManager(secretstring);
                var dateexp = numExpdate.Value;
                if (dateexp == 0)
                {
                    dateexp = 730000;
                }

                if (cbLicenseType.SelectedIndex == 0)
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.FULL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };

                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
                else
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.TRIAL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };
                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
            });

        }
</code>```

and I have progressbar. I want to run this method async and update progress to progressbar. How to update UI with async-await method. BackgroundWorker is  alternative???

答:
You should use the more modern IProgress<T>/Progress<T> types:

```<code>var progress = new Progress<int>(value => { progressBar.Value = value; });
await Task.Run(() => GenerateAsync(progress));

void GenerateAsync(IProgress<int> progress)
{
  ...
  progress?.Report(13);
  ...
}
</code>```

This is better than Invoke because it doesn't tie your business logic (GenerateAsync) to a particular UI, or to any UI at all.

Title: Update progress bar from Task.Run async

Body:
I have a method to generate software activation key from User Information:

private async void GenerateAsync()
        {
            await Task.Run(() =>
            {
                var secretstring = "CustomerName >> " + txtFullname.Text + " >> " + txtproducid.Text;
                keymng = new KeyManager(secretstring);
                var dateexp = numExpdate.Value;
                if (dateexp == 0)
                {
                    dateexp = 730000;
                }

                if (cbLicenseType.SelectedIndex == 0)
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.FULL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };

                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
                else
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.TRIAL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };
                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
            });

        }

and I have progressbar. I want to run this method async and update progress to progressbar. How to update UI with async-await method. BackgroundWorker is  alternative???

Body:
You should use the more modern IProgress<T>/Progress<T> types:

var progress = new Progress<int>(value => { progressBar.Value = value; });
await Task.Run(() => GenerateAsync(progress));

void GenerateAsync(IProgress<int> progress)
{
  ...
  progress?.Report(13);
  ...
}

This is better than Invoke because it doesn't tie your business logic (GenerateAsync) to a particular UI, or to any UI at all.


问:
Mojo plugin for writing to filesystem
I would like to write mojo plugin like this:

```<code> /**
 * @goal write-to-fs
 */

public class WriteToFsMojo extends AbstractMojo
{

    public void execute() throws MojoExecutionException
    {
        String relativePathToFile = "resource/my_direcory/my_file.csv"
        // find `relativePathToFile` from where goal executes
        // write the file using goal arguments
    }
}
</code>```

I would like to find in project specific file e.g. Menu.csv and insert row into this file from mvn goal argument.

For example:

```<code>mvn org.apache.maven.plugins:my-plugin:write-to-fs "-Did=100" "-Dname=New Menu Item"
</code>```

What I am interesting about is this approach correct? Is it possible? Could you provide examples?

答:
First of all, you are using the ancient method of annotating your classes with Javadoc doclets. That mechanism is deprecated. Ever since Maven 3, you should use annotations instead.

Apart from that, it depends on what you are trying to do in your plugin. If you elaborate on what you are trying to do, I'll expand on my answer.

Here's a skeleton:

```<code>@Mojo(name = "write-csv")
public class WriteToFsMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject project;

    @Parameter(property = "outputFile", defaultValue = "someFileName.csv")
    private String filePath;

    public void execute() throws MojoExecutionException {
        File outputFile = new File(project.getBasedir(), filePath);
        // now do something with it
    }
}
</code>```

This will get the Maven project definition injected and let the user supply the outputFile parameter, either via command line, or via plugin configuration.

Title: Mojo plugin for writing to filesystem

Body:
I would like to write mojo plugin like this:

 /**
 * @goal write-to-fs
 */

public class WriteToFsMojo extends AbstractMojo
{

    public void execute() throws MojoExecutionException
    {
        String relativePathToFile = "resource/my_direcory/my_file.csv"
        // find `relativePathToFile` from where goal executes
        // write the file using goal arguments
    }
}

I would like to find in project specific file e.g. Menu.csv and insert row into this file from mvn goal argument.

For example:

mvn org.apache.maven.plugins:my-plugin:write-to-fs "-Did=100" "-Dname=New Menu Item"

What I am interesting about is this approach correct? Is it possible? Could you provide examples?

Body:
First of all, you are using the ancient method of annotating your classes with Javadoc doclets. That mechanism is deprecated. Ever since Maven 3, you should use annotations instead.

Apart from that, it depends on what you are trying to do in your plugin. If you elaborate on what you are trying to do, I'll expand on my answer.

Here's a skeleton:

@Mojo(name = "write-csv")
public class WriteToFsMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject project;

    @Parameter(property = "outputFile", defaultValue = "someFileName.csv")
    private String filePath;

    public void execute() throws MojoExecutionException {
        File outputFile = new File(project.getBasedir(), filePath);
        // now do something with it
    }
}

This will get the Maven project definition injected and let the user supply the outputFile parameter, either via command line, or via plugin configuration.


问:
Error when saving data in a table (codeigniter)
Everthing seems to be working properly on my code, but when i want to add a new subject,i fill the different fields, i click on the "save" button AND i got this error:

A Database Error Occurred

  Error number: 1054

  Unknown column 'carrera' in 'field list'

  INSERT INTO `materias` (`carrera`, `materia`, `descripcion`, `carga_horaria`) VALUES ('5', 'Calculus', 'dfsfsdfsd', '2')

  Filename: C:/xampp/htdocs/NUEVO_PROJECTO/crud/system/database/DB_driver.php

  Line Number: 691

I was given 2 tables: "materias" and "carreras"

"materias" includes (id, carrera_id (is the foreign key to the column "id" of the table "carreras") nombre, descripcion, carga_horaria)

"carreras" includes (id,nombre,descripcion).

Here is my controller file (with the save function only):

```<code>public function save() {
    $txtcarr = $this->input->post("txtcarr");
    $txtmat = $this->input->post("txtmat");
    $txtdesc = $this->input->post("txtdesc");
    $txtcarga = $this->input->post("txtcarga");

    $this->Crudmodel->save($txtcarr, $txtmat, $txtdesc, $txtcarga);
    redirect('Home/index');
}
</code>```

Here is my crudmodel file (with the save function only):

```<code>public function save($txtcarr, $txtmat, $txtdesc, $txtcarga) {
    $data = array(
        'carrera' => $txtcarr,
        'materia' => $txtmat,
        'descripcion' => $txtdesc,
        'carga_horaria' => $txtcarga
    );
    $this->db->insert('materias', $data);
}
</code>```

And my "ADD" function:

```<code><?php include('footer.php'); ?>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h2 align="center">AGREGAR MATERIA</h2>
            <form method="post" action='<?php echo site_url('Home/save'); ?>'>
    <tr>

        <td>
            <select name="txtcarr">
                <?php foreach($carreras as $item):?>
                <option value="<?php echo $item->id;?>"><?php echo $item->nombre;?></option>
                 <?php endforeach;?>
            </select>
        </td>
    </tr>
    <tr>
        <td>Materia : </td>
        <td><input type="text" name="txtmat"/></td>
    </tr>
    <tr>
        <td>Descripcion : </td>
        <td><textarea name="txtdesc"></textarea></td>
    </tr>
    <tr>
        <td>Carga horaria : </td>
        <td><input type="text" name="txtcarga" /></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" value="save" /></td>
    </tr>
        <table class="table table-hover" align="center" border="0" cellspacing="0" cellpadding="0" width="300">

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

Hope you can help me!

答: This error means that you don't have column "carrera" in your table, so you need add it to your table in datatbase or maybe you have spelling mistake there.</p>

Body:
Everthing seems to be working properly on my code, but when i want to add a new subject,i fill the different fields, i click on the "save" button AND i got this error:

A Database Error Occurred

  Error number: 1054

  Unknown column 'carrera' in 'field list'

  INSERT INTO `materias` (`carrera`, `materia`, `descripcion`, `carga_horaria`) VALUES ('5', 'Calculus', 'dfsfsdfsd', '2')

  Filename: C:/xampp/htdocs/NUEVO_PROJECTO/crud/system/database/DB_driver.php

  Line Number: 691

I was given 2 tables: "materias" and "carreras"

"materias" includes (id, carrera_id (is the foreign key to the column "id" of the table "carreras") nombre, descripcion, carga_horaria)

"carreras" includes (id,nombre,descripcion).

Here is my controller file (with the save function only):

public function save() {
    $txtcarr = $this->input->post("txtcarr");
    $txtmat = $this->input->post("txtmat");
    $txtdesc = $this->input->post("txtdesc");
    $txtcarga = $this->input->post("txtcarga");

    $this->Crudmodel->save($txtcarr, $txtmat, $txtdesc, $txtcarga);
    redirect('Home/index');
}

Here is my crudmodel file (with the save function only):

public function save($txtcarr, $txtmat, $txtdesc, $txtcarga) {
    $data = array(
        'carrera' => $txtcarr,
        'materia' => $txtmat,
        'descripcion' => $txtdesc,
        'carga_horaria' => $txtcarga
    );
    $this->db->insert('materias', $data);
}

And my "ADD" function:

<?php include('footer.php'); ?>

AGREGAR MATERIA

            <form method="post" action='<?php echo site_url('Home/save'); ?>'>

            <select name="txtcarr">
                <?php foreach($carreras as $item):?>
                <option value="<?php echo $item->id;?>"><?php echo $item->nombre;?></option>
                 <?php endforeach;?>
            </select>

        Materia :
        <input type="text" name="txtmat"/>

        Descripcion :
        <textarea name="txtdesc"></textarea>

        Carga horaria :
        <input type="text" name="txtcarga" />

        <input type="submit" value="save" />

Hope you can help me!


问:
Laravel 5.2 exclude column from the json response which is in foreign key relationship
I want to exclude question_type_id from question.  Please help me.

```<code>[
 {
  "template_id": 2,
  "title": "news surey2345",
  "instructions": " this is news surey2345",
  "reference": "a426a9288424ff3d540115ffc38bd0b4",
  "status_id": 1,
  "published_date": "2017-03-30 11:12:48",
  "expiry_date": null,
  "survey_template": {
  "is_public": 0,
  "submission_type": 1,
  "id": 2
},
"questiongroup": [
  {
    "survey_id": 17,
    "title": "question group 2",
    "instructions": " this is question group 2",
    "has_free_text": 1,
    "sort": 4,
    "id": 19,
    "question": [
      {
        "id": 58,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 31,
        "question_answers": [
          {
            "question_id": 58,
            "answer": "answer1",
            "points": "12",
            "id": 206
          },
          {
            "question_id": 58,
            "answer": "answer2",
            "points": "11",
            "id": 207
          },
          {
            "question_id": 58,
            "answer": "NA",
            "points": "0",
            "id": 208
          }
        ],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      },
      {
        "id": 134,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 33,
        "question_answers": [],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      },
      {
        "id": 161,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 34,
        "question_answers": [],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      },
      {
        "id": 165,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 35,
        "question_answers": [],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      }
     ]
     }
    ]
   }
 ]
</code>```

答:
```<code>class MyModel extends Model {
    protected $hidden = ['question_type_id'];
}
</code>```

You can add attributes to the  $hidden property to prevent it been shown when a model is converted to JSON.

Body:
I want to exclude question_type_id from question.  Please help me.

[
 {
  "template_id": 2,
  "title": "news surey2345",
  "instructions": " this is news surey2345",
  "reference": "a426a9288424ff3d540115ffc38bd0b4",
  "status_id": 1,
  "published_date": "2017-03-30 11:12:48",
  "expiry_date": null,
  "survey_template": {
  "is_public": 0,
  "submission_type": 1,
  "id": 2
},
"questiongroup": [
  {
    "survey_id": 17,
    "title": "question group 2",
    "instructions": " this is question group 2",
    "has_free_text": 1,
    "sort": 4,
    "id": 19,
    "question": [
      {
        "id": 58,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 31,
        "question_answers": [
          {
            "question_id": 58,
            "answer": "answer1",
            "points": "12",
            "id": 206
          },
          {
            "question_id": 58,
            "answer": "answer2",
            "points": "11",
            "id": 207
          },
          {
            "question_id": 58,
            "answer": "NA",
            "points": "0",
            "id": 208
          }
        ],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      },
      {
        "id": 134,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 33,
        "question_answers": [],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      },
      {
        "id": 161,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 34,
        "question_answers": [],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      },
      {
        "id": 165,
        "question_type_id": 1,
        "question_group_id": 19,
        "title": "question3",
        "can_upload_file": 0,
        "can_comment": 0,
        "include_na_answer": 1,
        "sort": 35,
        "question_answers": [],
        "question_type": {
          "slug": "multi-choice",
          "id": 1
        }
      }
     ]
     }
    ]
   }
 ]

Body:
class MyModel extends Model {
    protected $hidden = ['question_type_id'];
}

You can add attributes to the  $hidden property to prevent it been shown when a model is converted to JSON.


问:
calculate method execution time in Visual Studio Express (No profiler available)?
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

```<code>        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);
</code>```

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?

答:
Most likely, your code is executing more quickly than the maximum resolution of your timing device. That's why it's reporting "0" milliseconds as the execution time for both pieces of code: the amount of time that has passed is undetectable. For some people, that might be enough to conclude it probably doesn't matter which way you do it.

However, if it's important to get an accurate comparison of each method's speed, you could try running the code in a tight loop. Essentially, do whatever it is you are doing about 100 or 1,000 or even a million times in a row, however many it takes to pass a sufficient amount of time that will register on your time-keeping device. Obviously, it won't take anywhere near that long to run the routine once or even several times in your final code, but at least it will give you an idea as to the relative speed of each option.

Body:
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?


问:
Cassandra - How to get the Day of week from the timestamp column?
I have a timestamp column in a Cassandra table, how do i get the day of week from the timestamp column using cql?

答:
There isn't support out of the box for this but

If using the CQL is a must you can have a look at the User Defined Functions:

http://cassandra.apache.org/doc/latest/cql/functions.html

http://www.datastax.com/dev/blog/user-defined-functions-in-cassandra-3-0

http://docs.datastax.com/en//cql/latest/cql/cql_using/useCreateUDF.html

Then you could use something as simple as:

How to determine day of week by passing specific date?

or even something like

Aggregation with Group By date in Spark SQL

And then you have a UDF that gives you day of the week when you are working with a dates.


问:
How to configure Apache mod_pagespeed to disable filters for specific URL?
I wanna enable filter defer_javascript on whole site (Wordpress) except every urls ending with /amp/ to avoid violating AMP-HTML rules (user-defined javascripts). I've tried to put these into my vhost config

```<code><LocationMatch "/amp">
    ModPagespeedDisableFilters defer_javascript
</LocationMatch>
</code>```

But that isn't worked.

Any help would be great :)

答: I think you can create another .htaccess inside the folder and disable the Pagespeed filter afterwards</p>

ContentLicense: CC BY-SA 4.0

Body:
I wanna enable filter defer_javascript on whole site (Wordpress) except every urls ending with /amp/ to avoid violating AMP-HTML rules (user-defined javascripts). I've tried to put these into my vhost config

<LocationMatch "/amp">
    ModPagespeedDisableFilters defer_javascript
</LocationMatch>

But that isn't worked.

Any help would be great :)


问:
Postgres - detect overlapping lines from 2 tables
QUESTION: I have 2 tables with bike and hike trails of a country (Poland).

```<code>Table bicycle_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |bicycle |szlak1       |ncn        |blue      |proposed
{geo2}   |bicycle |szlak2       |lcn        |red       |null
{geo3}   |bicycle |szlak3       |ncn        |green     |proposed
{geo4}   |bicycle |szlak4       |rcn        |blue      |proposed
{geo5}   |bicycle |szlak5       |lcn        |blue      |null
{geo6}   |bicycle |szlak6       |ncn        |yellow    |proposed
....and so on

Table hiking_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |hiking  |szlak1       |ncn        |blue      |proposed
{geo2}   |hiking  |szlak2       |ncn        |red       |null
{geo3}   |hiking  |szlak3       |ncn        |green     |proposed
{geo4}   |hiking  |szlak4       |ncn        |blue      |proposed
{geo5}   |hiking  |szlak5       |ncn        |blue      |null
{geo6}   |hiking  |szlak6       |ncn        |yellow    |proposed
...and so on
</code>```

{geo1},{geo2} etc. is a unique geometry of every trail.

Every trail has a unique geometry but sometimes bicycle and hiking routes overlap.
The picture below shows example in QGIS:

I would like to delete the overlapping parts as I already have them in a different database.

EDIT:
I have tried a solution suggested by Julia Leder :

```<code>create table intersections as
(select st_intersection(b.way, h.way) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(g.way, h.way));
</code>```

Not all overlapping lines were detected. I'm not sure why?
Here's a picture to show the issue:

答:
Are you looking for this:

```<code>(SELECT way,route,name,color,description,network FROM bicycle_merge
UNION
SELECT way,route,name,color,description,network FROM hiking_merge)
EXCEPT
(SELECT way,route,name,color,description,network FROM bicycle_merge
INTERSECT
SELECT way,route,name,color,description,network FROM hiking_merge);
</code>```

This is the MS SQL syntax. For Oracle, write MINUS instead of EXCEPT.

Body:
QUESTION: I have 2 tables with bike and hike trails of a country (Poland).

Table bicycle_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |bicycle |szlak1       |ncn        |blue      |proposed
{geo2}   |bicycle |szlak2       |lcn        |red       |null
{geo3}   |bicycle |szlak3       |ncn        |green     |proposed
{geo4}   |bicycle |szlak4       |rcn        |blue      |proposed
{geo5}   |bicycle |szlak5       |lcn        |blue      |null
{geo6}   |bicycle |szlak6       |ncn        |yellow    |proposed
....and so on

Table hiking_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |hiking  |szlak1       |ncn        |blue      |proposed
{geo2}   |hiking  |szlak2       |ncn        |red       |null
{geo3}   |hiking  |szlak3       |ncn        |green     |proposed
{geo4}   |hiking  |szlak4       |ncn        |blue      |proposed
{geo5}   |hiking  |szlak5       |ncn        |blue      |null
{geo6}   |hiking  |szlak6       |ncn        |yellow    |proposed
...and so on

{geo1},{geo2} etc. is a unique geometry of every trail.

Every trail has a unique geometry but sometimes bicycle and hiking routes overlap.
The picture below shows example in QGIS:

I would like to delete the overlapping parts as I already have them in a different database.

EDIT:
I have tried a solution suggested by Julia Leder :

create table intersections as
(select st_intersection(b.way, h.way) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(g.way, h.way));

Not all overlapping lines were detected. I'm not sure why?
Here's a picture to show the issue:

Body:
Are you looking for this:

(SELECT way,route,name,color,description,network FROM bicycle_merge
UNION
SELECT way,route,name,color,description,network FROM hiking_merge)
EXCEPT
(SELECT way,route,name,color,description,network FROM bicycle_merge
INTERSECT
SELECT way,route,name,color,description,network FROM hiking_merge);

This is the MS SQL syntax. For Oracle, write MINUS instead of EXCEPT.


问:
Pass changed files path to another command
I have a versioning command and we have to manually run it with all the changed files.

Is it possible to pass the changed and added files to another command as argument?

I have tried solutions mentioned in this link: is it possible to `git status` only modified files?, but its not working.

For sample I have made a dummy command:

```<code>function notify(){
    echo "*****************************************************************"
    echo $1
    echo "*****************************************************************"
}
</code>```

And I try to use it as:

git status -s | notify

git ls-files -m | notify

Is there a way to send individual file path to such command?

Edit 1:

As rightly pointed by mallaudin, I was missing xargs. But adding that now throws another error.

xargs: notify: No such file or directory

答:
You can use xargs

```<code>git ls-files -m | xargs notify
</code>```

From this question

xargs takes an executable as an argument (including custom scripts) rather than a function defined in the environment.

Either move your code to a script or use xargs to pass arguments to an external command.

You can move your function's code to a separate bash file e.g. notify.bash and use it like

```<code>git ls-files -m | xargs notify.bash
</code>```

Body:
I have a versioning command and we have to manually run it with all the changed files.

Is it possible to pass the changed and added files to another command as argument?

I have tried solutions mentioned in this link: is it possible to `git status` only modified files?, but its not working.

For sample I have made a dummy command:

function notify(){
    echo "*****************************************************************"
    echo $1
    echo "*****************************************************************"
}

And I try to use it as:

git status -s | notify

git ls-files -m | notify

Is there a way to send individual file path to such command?

Edit 1:

As rightly pointed by mallaudin, I was missing xargs. But adding that now throws another error.

xargs: notify: No such file or directory

Body:
You can use xargs

git ls-files -m | xargs notify

From this question

xargs takes an executable as an argument (including custom scripts) rather than a function defined in the environment.

Either move your code to a script or use xargs to pass arguments to an external command.

You can move your function's code to a separate bash file e.g. notify.bash and use it like

git ls-files -m | xargs notify.bash


问:
$.Post 404 Error with parameters
I'm working on the below ajax call in my MVC application which isn't working(the controller is not getting called) when parameter is used.
Works well when i remove the parameter in both ajax call and controller.

//Code:

```<code> $('#btnGw').click(function (e) {

                $.post("../api/cuews/", {  openId: "3" }, function (data) {

                    // data to manipulate for filter values

                });

            });
</code>```

//Controller

```<code>[HttpPost]
    public string Post(string openId)
    {
        string json = openId;

        return json;
    }
</code>```

Tried adding Json.Stringify,

```<code>$.post("../api/cuews/", {  openId: Json.Stringify("3") }, function (data) {

                    // data to manipulate for filter values

                });
</code>```

and

```<code>$.post("../api/cuews/", Json.Stringify({ openId: "3" }), function (data) {

                    // data to manipulate for filter values

                });
</code>```

But the result is same.

Error:(In console)

```<code>POST http://localhost/api/cuews/ 404 (Not Found)
</code>```

What am i doing wrong with the parameters?

FYI,

The same structure works for $.get with parameters.

答:
Try this,

Create a model with required properties.

Pass the model as a param

Make sure the param passed from AJAX is same(TEXT) as what is in Model.

Eg:

```<code> public class TestModel
 {
     public int ID { get; set; }
     public string Desc { get;set; }
 }

 $.ajax({
     url: '../api/Test/',
     type: 'POST',
     dataType: 'json',
     data: JSON.stringify({ Id: "1", Desc : "Name" }),
     contentType: "application/json; charset=utf-8",
     success: function (data) {
                  alert("Success!!!")
              },
     error: function (xhrequest, ErrorText, thrownError) {
                        alert("Error")
              }
 });
</code>```

AJAX works well when the params in these state. Just an work around.

Title: $.Post 404 Error with parameters

Body:
I'm working on the below ajax call in my MVC application which isn't working(the controller is not getting called) when parameter is used.
Works well when i remove the parameter in both ajax call and controller.

//Code:

 $('#btnGw').click(function (e) {

                $.post("../api/cuews/", {  openId: "3" }, function (data) {

                    // data to manipulate for filter values

                });

            });

//Controller

[HttpPost]
    public string Post(string openId)
    {
        string json = openId;

        return json;
    }

Tried adding Json.Stringify,

$.post("../api/cuews/", {  openId: Json.Stringify("3") }, function (data) {

                    // data to manipulate for filter values

                });

and

$.post("../api/cuews/", Json.Stringify({ openId: "3" }), function (data) {

                    // data to manipulate for filter values

                });

But the result is same.

Error:(In console)

POST http://localhost/api/cuews/ 404 (Not Found)

What am i doing wrong with the parameters?

FYI,

The same structure works for $.get with parameters.

Body:
Try this,

Create a model with required properties.

Pass the model as a param

Make sure the param passed from AJAX is same(TEXT) as what is in Model.

Eg:

 public class TestModel
 {
     public int ID { get; set; }
     public string Desc { get;set; }
 }

 $.ajax({
     url: '../api/Test/',
     type: 'POST',
     dataType: 'json',
     data: JSON.stringify({ Id: "1", Desc : "Name" }),
     contentType: "application/json; charset=utf-8",
     success: function (data) {
                  alert("Success!!!")
              },
     error: function (xhrequest, ErrorText, thrownError) {
                        alert("Error")
              }
 });

AJAX works well when the params in these state. Just an work around.


问:
Assign multiple new variables on LHS in a single line
I want to assign multiple variables in a single line in R. Is it possible to do something like this?

```<code>values # initialize some vector of values
(a, b) = values[c(2,4)] # assign a and b to values at 2 and 4 indices of 'values'
</code>```

Typically I want to assign about 5-6 variables in a single line, instead of having multiple lines. Is there an alternative?

答:
Another version with recursion:

```<code>let <- function(..., env = parent.frame()) {
    f <- function(x, ..., i = 1) {
        if(is.null(substitute(...))){
            if(length(x) == 1)
                x <- rep(x, i - 1);
            stopifnot(length(x) == i - 1)
            return(x);
        }
        val <- f(..., i = i + 1);
        assign(deparse(substitute(x)), val[[i]], env = env);
        return(val)
    }
    f(...)
}
</code>```

example:

```<code>> let(a, b, 4:10)
[1]  4  5  6  7  8  9 10
> a
[1] 4
> b
[1] 5
> let(c, d, e, f, c(4, 3, 2, 1))
[1] 4 3 2 1
> c
[1] 4
> f
[1] 1
</code>```

My version:

```<code>let <- function(x, value) {
    mapply(
        assign,
        as.character(substitute(x)[-1]),
        value,
        MoreArgs = list(envir = parent.frame()))
    invisible()
}
</code>```

example:

```<code>> let(c(x, y), 1:2 + 3)
> x
[1] 4
> y
[1]
</code>```

Body:
I want to assign multiple variables in a single line in R. Is it possible to do something like this?

values # initialize some vector of values
(a, b) = values[c(2,4)] # assign a and b to values at 2 and 4 indices of 'values'

Typically I want to assign about 5-6 variables in a single line, instead of having multiple lines. Is there an alternative?

Body:
Another version with recursion:

let <- function(..., env = parent.frame()) {
    f <- function(x, ..., i = 1) {
        if(is.null(substitute(...))){
            if(length(x) == 1)
                x <- rep(x, i - 1);
            stopifnot(length(x) == i - 1)
            return(x);
        }
        val <- f(..., i = i + 1);
        assign(deparse(substitute(x)), val[[i]], env = env);
        return(val)
    }
    f(...)
}

example:

> let(a, b, 4:10)
[1]  4  5  6  7  8  9 10
> a
[1] 4
> b
[1] 5
> let(c, d, e, f, c(4, 3, 2, 1))
[1] 4 3 2 1
> c
[1] 4
> f
[1] 1

My version:

let <- function(x, value) {
    mapply(
        assign,
        as.character(substitute(x)[-1]),
        value,
        MoreArgs = list(envir = parent.frame()))
    invisible()
}

example:

> let(c(x, y), 1:2 + 3)
> x
[1] 4
> y
[1]


问:
Android : onTouch event trigger movement of other object.
I am developing an android application with custom layout as below with a button on left hand side of the screen by default on load of the page.

When user clicks swipe button from left to right. The application will display a custom layout as shown below. The custom layout is attached with the image button. When user move the image button from left to right. The custom layout is displaying on the screen.
I can write the custom layout in xml file. The problem is I have no idea how to display the custom layout when I move the button from left to right.

答:
```<code>public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_MOVE){
                // To Do
            }
            return true;
        }
</code>```

Inside the if statement you can get the x position for the current touch event through motionEvent.getX() method. Then you can translate the custom layout to that position. I am not sure whether that is the best approach or not. But I think it will serve your purpose.

Body:
public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_MOVE){
                // To Do
            }
            return true;
        }

Inside the if statement you can get the x position for the current touch event through motionEvent.getX() method. Then you can translate the custom layout to that position. I am not sure whether that is the best approach or not. But I think it will serve your purpose.


问:
Could not resolve state from 'home'
I am working on a Mean-Js project in which I have to get redirected to another page in AngularJS. I used $state.go() to navigate . But i am getting the error as:

Could not resolve state 'registerPage' from 'home' state .

My config file is :

```<code>'use strict';
</code>```

//Setting up route

```<code>angular.module('SampleApp').config(['$stateProvider', '$urlRouterProvider',
  function ($stateProvider, $urlRouterProvider) {
        $stateProvider
        .state('registerPage',{
          url:'/register',
          templateUrl:'modules/Sample/Client/Views/register.html',
          data: {roles:['admin']},
          controller:'TestControl'
        });
    }
]);
</code>```

In my controller :

```<code>$scope.registerPage = function(){
    $state.go('registerPage' , {});
};
</code>```

The registerPage function is called in ng-click.

Kindly help. Thanks.

答:
Your custom module:

```<code>angular.module('SampleApp').config(['$stateProvider', '$urlRouterProvider',
  function ($stateProvider, $urlRouterProvider) {

        $stateProvider
        .state('registerPage',{
          url:'/register',
          templateUrl:'modules/Sample/Client/Views/register.html',
          data: {roles:['admin']},
          controller:'TestControl'
        });

      }
      ]);
</code>```

Your main module, Include sampleApp, and other dependencies

```<code>  angular.module('myApp', ['SampleApp', 'otherDependencies'])
</code>```

Title: Could not resolve state from 'home'

Body:
I am working on a Mean-Js project in which I have to get redirected to another page in AngularJS. I used $state.go() to navigate . But i am getting the error as:

Could not resolve state 'registerPage' from 'home' state .

My config file is :

'use strict';

//Setting up route

angular.module('SampleApp').config(['$stateProvider', '$urlRouterProvider',
  function ($stateProvider, $urlRouterProvider) {
        $stateProvider
        .state('registerPage',{
          url:'/register',
          templateUrl:'modules/Sample/Client/Views/register.html',
          data: {roles:['admin']},
          controller:'TestControl'
        });
    }
]);

In my controller :

$scope.registerPage = function(){
    $state.go('registerPage' , {});
};

The registerPage function is called in ng-click.

Kindly help. Thanks.

Body:
Your custom module:

angular.module('SampleApp').config(['$stateProvider', '$urlRouterProvider',
  function ($stateProvider, $urlRouterProvider) {

        $stateProvider
        .state('registerPage',{
          url:'/register',
          templateUrl:'modules/Sample/Client/Views/register.html',
          data: {roles:['admin']},
          controller:'TestControl'
        });

      }
      ]);

Your main module, Include sampleApp, and other dependencies

  angular.module('myApp', ['SampleApp', 'otherDependencies'])


问:
Laravel 5.2 eloquent model order by their relation model attribute
I have a question. I have an user model and a post model. A user can have many posts. Now I need to get posts with pagination. And I need to sort posts by their related user's id desc. Per page number is 10. I do not know how to write this code, someone can help me? Thanks.</p>

答:
Since Post belongs to User the posts table has user_id key. Use it:

```<code>Post::orderBy('user_id', 'desc')->paginate(10);
</code>```

Body:
Since Post belongs to User the posts table has user_id key. Use it:

Post::orderBy('user_id', 'desc')->paginate(10);


问:
Setting text to a TextView in Fragment A after adding and removing Fragment B
I have fragment A, on TextView click I add another Fragment B, I want to update the TextView of Fragment A when I remove Fragment B, any ideas on how to do that?</p>

答:
As Shubhank Gupta mentioned use a boolean when you remove Fragment B set it true and in Fragement A onResume() check for that boolean if it is true then change the text.

In Fragment B when removing it:

```<code>isTextChange = true;
</code>```

In Fragment A:

```<code> @Override
    public void onResume() {
        super.onResume();
        if(isTextChange){
        mTextView.setText("Text you want");
        isTextChange = false;
        }
}
</code>```

Edit:

or you can override isUserVisibleHint() method inside Fragment A and check there.

```<code>@Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
     super.setUserVisibleHint(isVisibleToUser);
     if (isVisibleToUser) {
        if(isTextChange){
            mTextView.setText("Text you want");
            isTextChange = false;
          }
        }
  }
</code>```

Body:
As Shubhank Gupta mentioned use a boolean when you remove Fragment B set it true and in Fragement A onResume() check for that boolean if it is true then change the text.

In Fragment B when removing it:

isTextChange = true;

In Fragment A:

 @Override
    public void onResume() {
        super.onResume();
        if(isTextChange){
        mTextView.setText("Text you want");
        isTextChange = false;
        }
}

Edit:

or you can override isUserVisibleHint() method inside Fragment A and check there.

@Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
     super.setUserVisibleHint(isVisibleToUser);
     if (isVisibleToUser) {
        if(isTextChange){
            mTextView.setText("Text you want");
            isTextChange = false;
          }
        }
  }


问:
Redis Sentinel 3.2 not firing scripts
So we just apt updated Redis to v3.2.8 (from 3.0.7) on our Ubuntu 16.04 servers, and have noticed that the client-reconfig-script and notification-script doesn't seem to fire anymore, on failover events.

We tested with debug sleep 30 and we can manipulate the sentinels to failover just fine, but the scripts do not fire.

Relevant info:

We're using the config files from 3.2 (we had to, as our own were replaced by the updater).

In sentinel.conf, the paths to the two scripts are correct:

sentinel notification-script ourmaster /mnt/efs/scripts/sentinel-notify.sh
sentinel client-reconfig-script ourmaster /mnt/efs/scripts/sentinel-failover.sh

We've even changed the permissions on these files to redis:redis, but still nothing.

We've turned protected mode off, on both redis and sentinel.

bind is commented out, as we need to bind to all adapters, but we've also tried bind 0.0.0.0

Everything else seem to work, its just these two scripts.

Running the scripts manually still works.

Anyone have any ideas?

Is it even supported anymore?

答:
We were using this unofficial Ubuntu PPA for Redis upgrades:
https://launchpad.net/~chris-lea/+archive/ubuntu/redis-server

The official PPA still uses 3.0.7, so we rolled back to that, and the problem went away.

The only theory I have is that Redis was built incorrectly in Chris' PPA. We've tried everything else at this point.

Title: Redis Sentinel 3.2 not firing scripts


问:
Python- if statement evaluation pattern
what the heck is the if statement doing?

```<code>>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])
</code>```

and this will result in ['e', 'f']

I dont know that the if is doing.

答:
Python interprets i/2 as a boolean expression: if it equals 0 the the expression ist considered false, else it is considered true. Let's look at the code line by line:

```<code>lst = ['a', 'b', 'c', 'd', 'e', 'f']
</code>```

We create a list with those 6 elements

```<code>for i in xrange(len(list)):
</code>```

len(list) is the length of our list, i.e. 6 and xrange(n) allows you to iterate an integer from 0 to n-1 (at each loop, i will be 0, 1, ..., 6)

```<code>    if i / 2:
</code>```

We check if the integer division from i by 2 is true or false. Remember: 0 is equivalent to False, everything else to True.

When i is 0 or 1, the quotient i/2 is 0, therefore the next statement is not executed. in the 4 other cases (i is 2, 3, 4 , 5), i/2 is greater than 0. There fore we execute the statement.

```<code>        del(lst[0])
</code>```

This simply asks to delete the first element of the list, and we've seen that this will be done 4 times, hence the result is a list with just the two last elements remaining.

The process can be visualized as follows (remember that / is the euclidian division in Python):

```<code>BEGIN OF LOOP
i=0, lst=['a', 'b', 'c', 'd', 'e', 'f']
  i/2 = 0/2 = 0 --> False --> Nothing happens
i=1, lst=['a', 'b', 'c', 'd', 'e', 'f']
  i/2 = 1/2 = 0 --> False --> Nothing happens
i=2, lst=['a', 'b', 'c', 'd', 'e', 'f']
  i/2 = 2/2 = 1 --> True --> Remove first element ('a')
i=3, lst=['b', 'c', 'd', 'e', 'f']
  i/2 = 3/2 = 1 --> True --> Remove first element ('b')
i=4, lst=['c', 'd', 'e', 'f']
  i/2 = 4/2 = 2 --> True --> Remove first element ('c')
i=5, lst=['d', 'e', 'f']
  i/2 = 5/2 = 2 --> True --> Remove first element ('d')
END OF LOOP

lst=['e', 'f']
</code>```

Title: Python- if statement evaluation pattern

Body:
what the heck is the if statement doing?

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])

and this will result in ['e', 'f']

I dont know that the if is doing.

Body:
Python interprets i/2 as a boolean expression: if it equals 0 the the expression ist considered false, else it is considered true. Let's look at the code line by line:

lst = ['a', 'b', 'c', 'd', 'e', 'f']

We create a list with those 6 elements

for i in xrange(len(list)):

len(list) is the length of our list, i.e. 6 and xrange(n) allows you to iterate an integer from 0 to n-1 (at each loop, i will be 0, 1, ..., 6)

    if i / 2:

We check if the integer division from i by 2 is true or false. Remember: 0 is equivalent to False, everything else to True.

When i is 0 or 1, the quotient i/2 is 0, therefore the next statement is not executed. in the 4 other cases (i is 2, 3, 4 , 5), i/2 is greater than 0. There fore we execute the statement.

        del(lst[0])

This simply asks to delete the first element of the list, and we've seen that this will be done 4 times, hence the result is a list with just the two last elements remaining.

The process can be visualized as follows (remember that / is the euclidian division in Python):

BEGIN OF LOOP
i=0, lst=['a', 'b', 'c', 'd', 'e', 'f']
  i/2 = 0/2 = 0 --> False --> Nothing happens
i=1, lst=['a', 'b', 'c', 'd', 'e', 'f']
  i/2 = 1/2 = 0 --> False --> Nothing happens
i=2, lst=['a', 'b', 'c', 'd', 'e', 'f']
  i/2 = 2/2 = 1 --> True --> Remove first element ('a')
i=3, lst=['b', 'c', 'd', 'e', 'f']
  i/2 = 3/2 = 1 --> True --> Remove first element ('b')
i=4, lst=['c', 'd', 'e', 'f']
  i/2 = 4/2 = 2 --> True --> Remove first element ('c')
i=5, lst=['d', 'e', 'f']
  i/2 = 5/2 = 2 --> True --> Remove first element ('d')
END OF LOOP

lst=['e', 'f']


问:
Is there any way to generate data dictionary in DOC or Excel format in PHP MyAdmin 4.5.1
In PHP MyAdmin 4.5.1 there is a option for generating Data Dictionary of Databages.
Data Dictionary option Image

But I need to generate it with DOC or Excel format.
Is it possible?

Or is there any other way to manage it?

This is the output I get when I clicked on Data Dictionary

答: No it's not possible. You have to manually do it. </p>


问:
HC 05 in debug mode
I have a doubt related to HC 05 Bluetooth module. Actually, I am having one android app, using that app I just want to start communication between them. Which is doing properly. Now I want to check what is exact communication going on between HC 05 and android app?

Description :
In a simple manner, I want to know about Bluetooth protocol. If I pair HC 05 with my mobile then which command send by my mobile? If I send data to the HC 05 then which frame I received from Mobile App?

Basically, I am reading one BLE stack and working on BLE programming from last 2 week on one of the BLE module. But not able to understand their communication. So that's why I just want, Is there any way to put HC 05 in debug mode.

Thanks you,

答:
You can use this link to know about the Bluetooth SPP Library.You can send the data to your hardware device and you can also implement listeners to listen to the data sent by the hardware device.
I have used it many times to integrate my mobile app with another harware device using android bluetooth SPP protocol.
Also, the data to send or receive depends on the way your hardware device is configured. Generally, you can check for some starting bytes as headers for receiving a particular info from the device.

Simple usage is as follows:

```<code>BluetoothSPP bt = new BluetoothSPP(yourContext);
//connect to device before sending data
bt.send("Message", true);
</code>```

Title: HC 05 in debug mode

Body:
You can use this link to know about the Bluetooth SPP Library.You can send the data to your hardware device and you can also implement listeners to listen to the data sent by the hardware device.
I have used it many times to integrate my mobile app with another harware device using android bluetooth SPP protocol.
Also, the data to send or receive depends on the way your hardware device is configured. Generally, you can check for some starting bytes as headers for receiving a particular info from the device.

Simple usage is as follows:

BluetoothSPP bt = new BluetoothSPP(yourContext);
//connect to device before sending data
bt.send("Message", true);


问:
do while loop ignores my bool flag variable c++
If userList[i].CheckUser(username, password) returns false then it enters the else condition and I get the output "User Does Not Exist! Try Again Enter username and password" that line then gets stuck in an infinite loop and I cant figure out why, I mean the program re-enters the do-while loop again so I don't see how the loop would carry over?</p>

```<code>int main()
{
    LoadUsersFromDatabase();
    bool flag;
    string username;
    int password;
do{
    cout << "Enter username and password: ";
    cin >> username >> password;
    for (int i = 0; i < numOfUsers; i++)
        if (userList[i].CheckUser(username, password) == true)
        {
            if (userList[i].GetUserType() == 'A')
            {
                ProcessAssistantMenu();
            }
            else if (userList[i].GetUserType() == 'M')
            {
                ProcessManagerMenu();
            }
        }
        else
                cout << "\rUser Does Not Exist! Try Again! ";
                flag = false;
  } while(flag == false);
return 0;
}
</code>```

答: The flag is never set true in the loop.

Body:
If userList[i].CheckUser(username, password) returns false then it enters the else condition and I get the output "User Does Not Exist! Try Again Enter username and password" that line then gets stuck in an infinite loop and I cant figure out why, I mean the program re-enters the do-while loop again so I don't see how the loop would carry over?

int main()
{
    LoadUsersFromDatabase();
    bool flag;
    string username;
    int password;
do{
    cout << "Enter username and password: ";
    cin >> username >> password;
    for (int i = 0; i < numOfUsers; i++)
        if (userList[i].CheckUser(username, password) == true)
        {
            if (userList[i].GetUserType() == 'A')
            {
                ProcessAssistantMenu();
            }
            else if (userList[i].GetUserType() == 'M')
            {
                ProcessManagerMenu();
            }
        }
        else
                cout << "\rUser Does Not Exist! Try Again! ";
                flag = false;
  } while(flag == false);
return 0;
}

Body: The flag is never set true in the loop.


问:
Closing UIAlertView instead of using dissmissing
I have a question about how I close and release the custom designed UIAlertView. In my UIAlertView, i'm using the dismissWithClickedButtonIndex function; however, it only closes to the background, it doesn't close in real manner.

Does anyone have a solution for that?

答: How does it close to the background? I assume you are refering to the pointer of the UIAlertView is still valid after dismissing? In that case you need to [myAlertView release]; to "make it go away completely".