问:
Error with success condition ajax on phonegap
I'm trying to create a login and registration app, but there was a problem. When I'm click the button the alert showed was exchange with another alert condition.

This is my code

```<code>$("#regis").click(function() {
                var nama = $("#namalengkap").val();
                var noid = $("#noid").val();
                var username = $("#uname").val();
                var password = $("#pwd").val();
                var email = $("#email").val();
                var ttl = $("#ttl").val();
                var alamat = $("#alamat").val();
                var jk = $("#gender").val();
                var dataString = "namalengkap=" + nama + "&noid=" + noid + "&uname=" + username + "&pwd=" + password + "&email=" + email + "&ttl=" + ttl + "&alamat=" + alamat + "&gender=" + jk + "&regis=";
                if ($.trim(nama).length > 0 & $.trim(noid).length > 0 & $.trim(username).length > 0 & $.trim(password).length > 0 & $.trim(email).length > 0 & $.trim(ttl).length > 0 & $.trim(alamat).length > 0 & $.trim(jk).length > 0)
                {
                    $.ajax({
                        type: "POST",
                        url: "http://localhost/JsEx/www/php/regis.php",
                        data: dataString,
                        crossDomain: true,
                        cache: false,
                        success: function (data) {
                            if (data=="success"){
                                alert("Registration Complete");
                            }
                            else {
                                alert("registration Failed");
                                window.location.reload();
                            }
                        }
                    });
                }
                return false;
            });
</code>```

the alert was showed when I'm finished the registration was alert in else , but the data was inserted to the database.

When I'm click the button

In the database

答:
working code ...

```<code>$.ajax({
          type: "POST",
          url: "http://localhost/JsEx/www/php/regis.php",
          data: dataString,
          crossDomain: true,
          cache: false,
          success: function(){
             alert("Registration Complete");
          },
          error: function(){
            alert("registration Failed");
            window.location.reload();
          }
      });
</code>```

for more ref check.  https://api.jquery.com/jquery.post/

Body:
I'm trying to create a login and registration app, but there was a problem. When I'm click the button the alert showed was exchange with another alert condition.

This is my code

$("#regis").click(function() {
                var nama = $("#namalengkap").val();
                var noid = $("#noid").val();
                var username = $("#uname").val();
                var password = $("#pwd").val();
                var email = $("#email").val();
                var ttl = $("#ttl").val();
                var alamat = $("#alamat").val();
                var jk = $("#gender").val();
                var dataString = "namalengkap=" + nama + "&noid=" + noid + "&uname=" + username + "&pwd=" + password + "&email=" + email + "&ttl=" + ttl + "&alamat=" + alamat + "&gender=" + jk + "&regis=";
                if ($.trim(nama).length > 0 & $.trim(noid).length > 0 & $.trim(username).length > 0 & $.trim(password).length > 0 & $.trim(email).length > 0 & $.trim(ttl).length > 0 & $.trim(alamat).length > 0 & $.trim(jk).length > 0)
                {
                    $.ajax({
                        type: "POST",
                        url: "http://localhost/JsEx/www/php/regis.php",
                        data: dataString,
                        crossDomain: true,
                        cache: false,
                        success: function (data) {
                            if (data=="success"){
                                alert("Registration Complete");
                            }
                            else {
                                alert("registration Failed");
                                window.location.reload();
                            }
                        }
                    });
                }
                return false;
            });

the alert was showed when I'm finished the registration was alert in else , but the data was inserted to the database.

When I'm click the button

In the database

Body:
working code ...

$.ajax({
          type: "POST",
          url: "http://localhost/JsEx/www/php/regis.php",
          data: dataString,
          crossDomain: true,
          cache: false,
          success: function(){
             alert("Registration Complete");
          },
          error: function(){
            alert("registration Failed");
            window.location.reload();
          }
      });

for more ref check.  https://api.jquery.com/jquery.post/


来源: stackexchange

问:
Adding a C# enum value to a Navigation URI
I'm developing a Windows Phone application. I make the question here because I think a silverlight question.

I have defined the following Navigations URIs on App.xaml:

```<code><!-- Navigation links-->
<nav:UriMapper x:Name="UriMapper">
    <nav:UriMapper.UriMappings>
        <nav:UriMapping Uri="/Destination" MappedUri="/Views/Tourism/Common.xaml?Type=1"/>
        <nav:UriMapping Uri="/Points" MappedUri="/Views/Tourism/Common.xaml?Type=2"/>
    </nav:UriMapper.UriMappings>
</nav:UriMapper>
</code>```

And the following C# enum:

```<code>public enum TourismItemType
{
    Destination = 1,
    PointOfInterest = 2,
    Content = 3
}
</code>```

I want to change the '1' on MappedUri="/Views/Tourism/Common.xaml?Type=1" with the value obtained from TourismItemType.Destination.

I think, I can do that:

And do it programatically, but is there any way to access the value represented by TourismType.Destination on XAML?

Thanks.

答:
This can be easily achieved by passing the value of the enum as a string and then parsing it into an enum in the OnNavigatedTo event.

```<code>MappedUri="/Views/Tourism/Common.xaml?Type=PointOfInterest"
</code>```

and then in common.xaml:

```<code>string selectedType = "";
if (NavigationContext.QueryString.TryGetValue("Type", out selectedType))
{
    var tit = Enum.Parse(typeof (TourismItemType), selectedType, true);

    // do something with `tit`...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm developing a Windows Phone application. I make the question here because I think a silverlight question.

I have defined the following Navigations URIs on App.xaml:

And the following C# enum:

public enum TourismItemType
{
    Destination = 1,
    PointOfInterest = 2,
    Content = 3
}

I want to change the '1' on MappedUri="/Views/Tourism/Common.xaml?Type=1" with the value obtained from TourismItemType.Destination.

I think, I can do that:

And do it programatically, but is there any way to access the value represented by TourismType.Destination on XAML?

Thanks.

Body:
This can be easily achieved by passing the value of the enum as a string and then parsing it into an enum in the OnNavigatedTo event.

MappedUri="/Views/Tourism/Common.xaml?Type=PointOfInterest"

and then in common.xaml:

string selectedType = "";
if (NavigationContext.QueryString.TryGetValue("Type", out selectedType))
{
    var tit = Enum.Parse(typeof (TourismItemType), selectedType, true);

    // do something with `tit`...
}


问:
In PostScript, define a procedure to define other procedures
The purpose of this question is to understand PostScript a bit better from a programming perspective. The goal described below is just an example used for illustration.

In the PostScript language, I can define a procedure to set the current graphics color as follows:

```<code>/cRED { 1 0 0 setrgbcolor } def  % define a procedure to set the color to red.
</code>```

I was wondering if there was a way to define a procedure that would define other color procedures. Assume that such a procedure called cdef were defined. I could use it as follows:

```<code>/cRED 1 0 0 cdef
</code>```

This should have the same effect as the previous definition of cRED.
The problem is that I can't seem to figure out how to "capture" the literal value of items on the stack in a procedure passed to def.

I tried the following:

```<code>/cdef { /B exch def /G exch def /R exch def { R G B setrgbcolor } bind def } def
/cRED 1 0 0  cdef
/cGRN 0 1 0  cdef
/cBLU 0 0 1  cdef
</code>```

My expectation was that by using bind the values of R G and B would be captured literally. I.e. I was expecting the code above to be equivalent to this:

```<code>/cRED { 1 0 0 setrgbcolor } def
/cGRN { 0 1 0 setrgbcolor } def
/cBLU { 0 0 1 setrgbcolor } def
</code>```

Unfortunately the actual result is that cRED cGRN and cBLU all set the color to blue. This is because cRED cGRN and cBLU are still dependent on the R G and B objects (which are globals). And so the color is blue for all because cBLU defined last, setting R G and B. Apparently bind didn't work the way I expected.

Is there a way to define cdef to achieve this? The crux of the issue is being able to pop a value off the stack and store it literally using def. E.g. something like this pseudo-code:

```<code>/cdef { { $ $ $ setrgbcolor } bind def } def
</code>```

Where $ woudl be replaced with the literal value of the item at the top of the stack when cdef is being evaluated. So /cCYN 0 1 1 cdef is evaluated as /cCYN { 0 1 1 setrgbcolor } bind def

Is there some operator that fulfills the purpose of the $ as described above? The operators pop, =, and index are close, but don't seem to work.
In addition, the use of Immediately Evaluated Names (e.g. //name) seems promising, but they seem to be evaluated even before cdef is executed.

Thanks

答:
Stefan's answer is probably the best and simplest way for this case. But there are many more ways to construct procedures in postscript.

Since you know the exact number of elements, you can skip the stack juggling with the mark and do it like this:

```<code>/cdef { /setrgbcolor load 4 array astore cvx def } def
</code>```

And a more complicated way might be useful for more complicated functions. You can define the arguments and substitute definitions into a string template. I think this is what you were striving toward with the immediately-evaluated names. Executing the string yield the procedure body, but the scanning and evaluation is performed at run-time.

```<code>/cdef {
    3 dict begin
        { b g r } { exch def } forall
        ({ //r //g //b setrgbcolor }) cvx exec
    end
    def
} def
</code>```

And another way, which is perhaps clumsy but very flexible.

```<code>/curry {
    /exec cvx
    3 array astore cvx
} def

/cdef {
    {setrgbcolor} 3{curry}repeat
    def
} def
</code>```

This results in this procedure being defined for the values 1 2 3:

```<code>{ 1 { 2 { 3 { setrgbcolor } exec } exec } exec }
</code>```

So, perhaps some slight loss of micro-efficiency. But it could be used for all sorts of things.

ContentLicense: CC BY-SA 3.0

Body:
The purpose of this question is to understand PostScript a bit better from a programming perspective. The goal described below is just an example used for illustration.

In the PostScript language, I can define a procedure to set the current graphics color as follows:

/cRED { 1 0 0 setrgbcolor } def  % define a procedure to set the color to red.

I was wondering if there was a way to define a procedure that would define other color procedures. Assume that such a procedure called cdef were defined. I could use it as follows:

/cRED 1 0 0 cdef

This should have the same effect as the previous definition of cRED.
The problem is that I can't seem to figure out how to "capture" the literal value of items on the stack in a procedure passed to def.

I tried the following:

/cdef { /B exch def /G exch def /R exch def { R G B setrgbcolor } bind def } def
/cRED 1 0 0  cdef
/cGRN 0 1 0  cdef
/cBLU 0 0 1  cdef

My expectation was that by using bind the values of R G and B would be captured literally. I.e. I was expecting the code above to be equivalent to this:

/cRED { 1 0 0 setrgbcolor } def
/cGRN { 0 1 0 setrgbcolor } def
/cBLU { 0 0 1 setrgbcolor } def

Unfortunately the actual result is that cRED cGRN and cBLU all set the color to blue. This is because cRED cGRN and cBLU are still dependent on the R G and B objects (which are globals). And so the color is blue for all because cBLU defined last, setting R G and B. Apparently bind didn't work the way I expected.

Is there a way to define cdef to achieve this? The crux of the issue is being able to pop a value off the stack and store it literally using def. E.g. something like this pseudo-code:

/cdef { { $ $ $ setrgbcolor } bind def } def

Where $ woudl be replaced with the literal value of the item at the top of the stack when cdef is being evaluated. So /cCYN 0 1 1 cdef is evaluated as /cCYN { 0 1 1 setrgbcolor } bind def

Is there some operator that fulfills the purpose of the $ as described above? The operators pop, =, and index are close, but don't seem to work.
In addition, the use of Immediately Evaluated Names (e.g. //name) seems promising, but they seem to be evaluated even before cdef is executed.

Thanks

Body:
Stefan's answer is probably the best and simplest way for this case. But there are many more ways to construct procedures in postscript.

Since you know the exact number of elements, you can skip the stack juggling with the mark and do it like this:

/cdef { /setrgbcolor load 4 array astore cvx def } def

And a more complicated way might be useful for more complicated functions. You can define the arguments and substitute definitions into a string template. I think this is what you were striving toward with the immediately-evaluated names. Executing the string yield the procedure body, but the scanning and evaluation is performed at run-time.

/cdef {
    3 dict begin
        { b g r } { exch def } forall
        ({ //r //g //b setrgbcolor }) cvx exec
    end
    def
} def

And another way, which is perhaps clumsy but very flexible.

/curry {
    /exec cvx
    3 array astore cvx
} def

/cdef {
    {setrgbcolor} 3{curry}repeat
    def
} def

This results in this procedure being defined for the values 1 2 3:

{ 1 { 2 { 3 { setrgbcolor } exec } exec } exec }

So, perhaps some slight loss of micro-efficiency. But it could be used for all sorts of things.


问:
Dataframe to Oracle creates table with case sensitive column
Spark: 2.1.1

I am saving my dataframe as an Oracle table but the resultant Oracle table has "case sensitive" columns.

```<code>val properties = new java.util.Properties
    properties.setProperty("user", ora_username)
    properties.setProperty("password", ora_pwd)
    properties.setProperty("batchsize", "30000")
    properties.setProperty("driver", db_driver)
</code>```

```<code>spark.sql("select * from myTable").repartition(50).write.mode(SaveMode.Overwrite).jdbc(url,"myTable_oracle", properties)
</code>```

When I see in Oracle ,

Select * from myTable_oracle; => works

Select col1 from myTable_oracle; => Doesn't work

Select "col1" from myTable_oracle; => works , but is very annoying

Tried setting below, but still same issue:

```<code>spark.sqlContext.sql("set spark.sql.caseSensitive=false")
</code>```

Same code used to work in Spark 1.6.1 which creates Oracle table with case-insensitive columns. But with Spark 2.1.1 I am facing this issue.

答:
I found the issue and solution :
Starting Spark 2.x every columnName gets double quoted while creating table and hence the resultant Oracle table's columnNames become case-sensitive when you try to query them via sqlPlus.

dialect.quoteIdentifier

[https://github.com/apache/spark/blob/branch-2.1/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala#L645]

and this dialect.quoteIdentifier is Double quotes ["]

```<code>  def quoteIdentifier(colName: String): String = {
    s""""$colName""""
  }
</code>```

[https://github.com/apache/spark/blob/branch-2.1/sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala#L90]

Solution : De-register existing OracleDialect and Re-register while
  overriding dialect.quoteIdentifier along with other necessary stuff needed to work with Oracle Dialect

```<code>import java.sql.Types
import org.apache.spark.sql.types._
import org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils
import org.apache.spark.sql.jdbc.{ JdbcDialects, JdbcType, JdbcDialect }

val url= "jdbc:oracle:thin:@HOST:1567/SID"

val dialect = JdbcDialects
JdbcDialects.unregisterDialect(dialect.get(url))

val OracleDialect = new JdbcDialect {
  override def canHandle(url: String): Boolean = url.startsWith("jdbc:oracle") || url.contains("oracle")

  override def getCatalystType(sqlType: Int, typeName: String, size: Int, md: MetadataBuilder): Option[DataType] = {
    // Handle NUMBER fields that have no precision/scale in special way because JDBC ResultSetMetaData converts this to 0 procision and -127 scale
    if (sqlType == Types.NUMERIC && size == 0) {
      // This is sub-optimal as we have to pick a precision/scale in advance whereas the data in Oracle is allowed
      //  to have different precision/scale for each value.  This conversion works in our domain for now though we
      //  need a more durable solution.  Look into changing JDBCRDD (line 406):
      //    FROM:  mutableRow.update(i, Decimal(decimalVal, p, s))
      //    TO:  mutableRow.update(i, Decimal(decimalVal))
      Some(DecimalType(DecimalType.MAX_PRECISION, 10))
    } // Handle Timestamp with timezone (for now we are just converting this to a string with default format)
    //else if (sqlType == -101) {
    // Some(StringType)
    // }
    else None
  }

  override def getJDBCType(dt: DataType): Option[JdbcType] = dt match {
    case StringType            => Some(JdbcType("VARCHAR2(2000)", java.sql.Types.VARCHAR))
    case BooleanType           => Some(JdbcType("NUMBER(1)", java.sql.Types.NUMERIC))
    case IntegerType           => Some(JdbcType("NUMBER(10)", java.sql.Types.NUMERIC))
    case LongType              => Some(JdbcType("NUMBER(19)", java.sql.Types.NUMERIC))
    case DoubleType            => Some(JdbcType("NUMBER(19,4)", java.sql.Types.NUMERIC))
    case FloatType             => Some(JdbcType("NUMBER(19,4)", java.sql.Types.NUMERIC))
    case ShortType             => Some(JdbcType("NUMBER(5)", java.sql.Types.NUMERIC))
    case ByteType              => Some(JdbcType("NUMBER(3)", java.sql.Types.NUMERIC))
    case BinaryType            => Some(JdbcType("BLOB", java.sql.Types.BLOB))
    case TimestampType         => Some(JdbcType("DATE", java.sql.Types.TIMESTAMP))
    case DateType              => Some(JdbcType("DATE", java.sql.Types.DATE))
    //case DecimalType.Fixed(precision, scale) => Some(JdbcType("NUMBER(" + precision + "," + scale + ")", java.sql.Types.NUMERIC))
    //case DecimalType.Unlimited => Some(JdbcType("NUMBER(38,4)", java.sql.Types.NUMERIC))
    case _                     => None
  }

  //Imp from Spark2.0 since otherwise oracle table columns would be case-sensitive
  override def quoteIdentifier(colName: String): String = {
    colName
  }

}

JdbcDialects.registerDialect(OracleDialect)
</code>```

Body:
Spark: 2.1.1

I am saving my dataframe as an Oracle table but the resultant Oracle table has "case sensitive" columns.

val properties = new java.util.Properties
    properties.setProperty("user", ora_username)
    properties.setProperty("password", ora_pwd)
    properties.setProperty("batchsize", "30000")
    properties.setProperty("driver", db_driver)

spark.sql("select * from myTable").repartition(50).write.mode(SaveMode.Overwrite).jdbc(url,"myTable_oracle", properties)

When I see in Oracle ,

Select * from myTable_oracle; => works

Select col1 from myTable_oracle; => Doesn't work

Select "col1" from myTable_oracle; => works , but is very annoying

Tried setting below, but still same issue:

spark.sqlContext.sql("set spark.sql.caseSensitive=false")

Same code used to work in Spark 1.6.1 which creates Oracle table with case-insensitive columns. But with Spark 2.1.1 I am facing this issue.

Body:
I found the issue and solution :
Starting Spark 2.x every columnName gets double quoted while creating table and hence the resultant Oracle table's columnNames become case-sensitive when you try to query them via sqlPlus.

dialect.quoteIdentifier

[https://github.com/apache/spark/blob/branch-2.1/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala#L645]

and this dialect.quoteIdentifier is Double quotes ["]

  def quoteIdentifier(colName: String): String = {
    s""""$colName""""
  }

[https://github.com/apache/spark/blob/branch-2.1/sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala#L90]

Solution : De-register existing OracleDialect and Re-register while
  overriding dialect.quoteIdentifier along with other necessary stuff needed to work with Oracle Dialect

import java.sql.Types
import org.apache.spark.sql.types._
import org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils
import org.apache.spark.sql.jdbc.{ JdbcDialects, JdbcType, JdbcDialect }

val url= "jdbc:oracle:thin:@HOST:1567/SID"

val dialect = JdbcDialects
JdbcDialects.unregisterDialect(dialect.get(url))

val OracleDialect = new JdbcDialect {
  override def canHandle(url: String): Boolean = url.startsWith("jdbc:oracle") || url.contains("oracle")

  override def getCatalystType(sqlType: Int, typeName: String, size: Int, md: MetadataBuilder): Option[DataType] = {
    // Handle NUMBER fields that have no precision/scale in special way because JDBC ResultSetMetaData converts this to 0 procision and -127 scale
    if (sqlType == Types.NUMERIC && size == 0) {
      // This is sub-optimal as we have to pick a precision/scale in advance whereas the data in Oracle is allowed
      //  to have different precision/scale for each value.  This conversion works in our domain for now though we
      //  need a more durable solution.  Look into changing JDBCRDD (line 406):
      //    FROM:  mutableRow.update(i, Decimal(decimalVal, p, s))
      //    TO:  mutableRow.update(i, Decimal(decimalVal))
      Some(DecimalType(DecimalType.MAX_PRECISION, 10))
    } // Handle Timestamp with timezone (for now we are just converting this to a string with default format)
    //else if (sqlType == -101) {
    // Some(StringType)
    // }
    else None
  }

  override def getJDBCType(dt: DataType): Option[JdbcType] = dt match {
    case StringType            => Some(JdbcType("VARCHAR2(2000)", java.sql.Types.VARCHAR))
    case BooleanType           => Some(JdbcType("NUMBER(1)", java.sql.Types.NUMERIC))
    case IntegerType           => Some(JdbcType("NUMBER(10)", java.sql.Types.NUMERIC))
    case LongType              => Some(JdbcType("NUMBER(19)", java.sql.Types.NUMERIC))
    case DoubleType            => Some(JdbcType("NUMBER(19,4)", java.sql.Types.NUMERIC))
    case FloatType             => Some(JdbcType("NUMBER(19,4)", java.sql.Types.NUMERIC))
    case ShortType             => Some(JdbcType("NUMBER(5)", java.sql.Types.NUMERIC))
    case ByteType              => Some(JdbcType("NUMBER(3)", java.sql.Types.NUMERIC))
    case BinaryType            => Some(JdbcType("BLOB", java.sql.Types.BLOB))
    case TimestampType         => Some(JdbcType("DATE", java.sql.Types.TIMESTAMP))
    case DateType              => Some(JdbcType("DATE", java.sql.Types.DATE))
    //case DecimalType.Fixed(precision, scale) => Some(JdbcType("NUMBER(" + precision + "," + scale + ")", java.sql.Types.NUMERIC))
    //case DecimalType.Unlimited => Some(JdbcType("NUMBER(38,4)", java.sql.Types.NUMERIC))
    case _                     => None
  }

  //Imp from Spark2.0 since otherwise oracle table columns would be case-sensitive
  override def quoteIdentifier(colName: String): String = {
    colName
  }

}

JdbcDialects.registerDialect(OracleDialect)


问:
sed regular expression for escaped urls
why is sed not replacing anything:

```<code>sed -i '' 's/<a href="\.\.\/\.\.\/ja\/%E6%9C%88\/[^-]\+-page-[\d]\+.html"\/>//g' foo.htm
</code>```

I want it to match the following string:

```<code><a href="../../ja/%E6%9C%88/%E3%82%A2%E3%83%B3%E3%82%AE%E3%83%A9-page-2013.html"/>
</code>```

Title: sed regular expression for escaped urls

Body:
why is sed not replacing anything:

sed -i '' 's///g' foo.htm

I want it to match the following string:

Body:
You can't use \d to match digits with sed. Use [0-9] or [[:digit:]]:

sed -i '' 's/<a href="\.\.\/\.\.\/ja\/%E6%9C%88\/[^-]\+-page-[0-9]\+.html"\/>//g' foo.htm


问:
Android - Handle click and swipe on listview items
I am making a menu where the items have to respond to two types of events:

OnClick

  If the user clicks the item, it should start an Activity. Each button launches a different activity.

OnFling

  When the user swipes the item from right to left, its name should appear. Each item has a different name, and the name will show up just
  in the item that was swiped.

I tried a lot of different things, searched for many tutorials and questions here on StackOverflow but I couldn't find a decent answer and my implementation stills poor.

What I am doing right now is setting an OnClick handle for each item in the method getView of my custom adapter and setting a gestureListener on my listView and handling the method onFling, but it is not acting as expected: most of the time I try to swipe and the gesture is handled as a click...

I know I could use an implementation like this, but I think I can not use the onTouch event trick in this case, because I need the view position so I can handle which activity should be launched (onTouch/click) or which TextView should become visible.

Here are the snippets that I have so far:

```<code>    final GestureDetector gestureDetector = new GestureDetector(
            new GestureListener());

    lvMenu.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(final View view, final MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return false;
            }

            return true;
        }
    });
</code>```

The inner class:

```<code>class GestureListener extends SimpleOnGestureListener {
    protected MotionEvent mLastOnDownEvent = null;

    @Override
    public boolean onDown(final MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2,
            final float velocityX, final float velocityY) {
        Log.d("OnFling", "Called");
        final int SWIPE_MIN_DISTANCE = 20;
        final int SWIPE_MAX_OFF_PATH = 250;
        final int SWIPE_THRESHOLD_VELOCITY = 200;
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                return false;
            }
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.i("A", "Right to Left");
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.i("B", "Left to Right");
            }
        } catch (final Exception e) {
            // nothing
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }
}
</code>```

And the onClick() method inside my custom adapter:

```<code>public void onClick(final View v) {
                Intent i = null;
                switch (position) {
                case 0:
                    i = new Intent(parent.getContext(),
                            ProfileActivity.class);
                    break;
                case 1:
                    i = new Intent(parent.getContext(),
                            CatalogActivity.class);
                    break;
                case 2:
                    i = new Intent(parent.getContext(), GuideActivity.class);
                    break;
                case 3:
                    i = new Intent(parent.getContext(),
                            EventsActivity.class);
                    break;
                default:
                    Log.d("MenuActivity", "Switch default case.");
                    break;
                }
                if (i != null) {
                    parent.getContext().startActivity(i);
                }

            }
</code>```

Thank you :)

EDIT 1: now I am trying to set a OnTouchListener to each View in my custom adapter. But it is not working... I can't figure out the reason why.

This is how I am setting up the TouchListener:

```<code>            convertView.setOnTouchListener(new MenuGestureHandler() {

            @Override
            public boolean onSwipeRight() {
                Log.d("Swipe Right", "OK!");
                return true;
            }

            @Override
            public void onClick() {
                Log.d("Click", "OK!");
            }

        });
</code>```

And this is the class (with some useless code like swipeUp, swipeDown):

```<code>public class MenuGestureHandler implements OnTouchListener {

GestureDetector gestureDetector = new GestureDetector(new GestureListener());

@Override
public boolean onTouch(final View v, final MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends SimpleOnGestureListener {

    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onSingleTapConfirmed(final MotionEvent e) {
        onClick(); // my method
        return super.onSingleTapConfirmed(e);
    }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2,
            final float velocityX, final float velocityY) {
        boolean result = false;
        try {
            final float diffY = e2.getY() - e1.getY();
            final float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_THRESHOLD
                        && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        result = onSwipeRight();
                    } else {
                        result = onSwipeLeft();
                    }
                }
            } else {
                if (Math.abs(diffY) > SWIPE_THRESHOLD
                        && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        result = onSwipeBottom();
                    } else {
                        result = onSwipeTop();
                    }
                }
            }
        } catch (final Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}

public boolean onSwipeRight() {
    return false;
}

public boolean onSwipeLeft() {
    return false;
}

public void onClick() {
}

public boolean onSwipeTop() {
    return false;
}

public boolean onSwipeBottom() {
    return false;
}
</code>```

EDIT 2 I could get it to work by just overriding the method onDown() in my GestureListener class and setting it to always return true. I really don't understand why I need to do that, but it seems it is working now!

答:
I know this is an old question for here is the answer for future searches:

https://stackoverflow.com/a/44426980/6776960

Body:
I am making a menu where the items have to respond to two types of events:

OnClick

  If the user clicks the item, it should start an Activity. Each button launches a different activity.

OnFling

  When the user swipes the item from right to left, its name should appear. Each item has a different name, and the name will show up just
  in the item that was swiped.

I tried a lot of different things, searched for many tutorials and questions here on StackOverflow but I couldn't find a decent answer and my implementation stills poor.

What I am doing right now is setting an OnClick handle for each item in the method getView of my custom adapter and setting a gestureListener on my listView and handling the method onFling, but it is not acting as expected: most of the time I try to swipe and the gesture is handled as a click...

I know I could use an implementation like this, but I think I can not use the onTouch event trick in this case, because I need the view position so I can handle which activity should be launched (onTouch/click) or which TextView should become visible.

Here are the snippets that I have so far:

    final GestureDetector gestureDetector = new GestureDetector(
            new GestureListener());

    lvMenu.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(final View view, final MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return false;
            }

            return true;
        }
    });

The inner class:

class GestureListener extends SimpleOnGestureListener {
    protected MotionEvent mLastOnDownEvent = null;

    @Override
    public boolean onDown(final MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2,
            final float velocityX, final float velocityY) {
        Log.d("OnFling", "Called");
        final int SWIPE_MIN_DISTANCE = 20;
        final int SWIPE_MAX_OFF_PATH = 250;
        final int SWIPE_THRESHOLD_VELOCITY = 200;
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                return false;
            }
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.i("A", "Right to Left");
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.i("B", "Left to Right");
            }
        } catch (final Exception e) {
            // nothing
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }
}

And the onClick() method inside my custom adapter:

public void onClick(final View v) {
                Intent i = null;
                switch (position) {
                case 0:
                    i = new Intent(parent.getContext(),
                            ProfileActivity.class);
                    break;
                case 1:
                    i = new Intent(parent.getContext(),
                            CatalogActivity.class);
                    break;
                case 2:
                    i = new Intent(parent.getContext(), GuideActivity.class);
                    break;
                case 3:
                    i = new Intent(parent.getContext(),
                            EventsActivity.class);
                    break;
                default:
                    Log.d("MenuActivity", "Switch default case.");
                    break;
                }
                if (i != null) {
                    parent.getContext().startActivity(i);
                }

            }

Thank you :)

EDIT 1: now I am trying to set a OnTouchListener to each View in my custom adapter. But it is not working... I can't figure out the reason why.

This is how I am setting up the TouchListener:

            convertView.setOnTouchListener(new MenuGestureHandler() {

            @Override
            public boolean onSwipeRight() {
                Log.d("Swipe Right", "OK!");
                return true;
            }

            @Override
            public void onClick() {
                Log.d("Click", "OK!");
            }

        });

And this is the class (with some useless code like swipeUp, swipeDown):

public class MenuGestureHandler implements OnTouchListener {

GestureDetector gestureDetector = new GestureDetector(new GestureListener());

@Override
public boolean onTouch(final View v, final MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends SimpleOnGestureListener {

    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onSingleTapConfirmed(final MotionEvent e) {
        onClick(); // my method
        return super.onSingleTapConfirmed(e);
    }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2,
            final float velocityX, final float velocityY) {
        boolean result = false;
        try {
            final float diffY = e2.getY() - e1.getY();
            final float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_THRESHOLD
                        && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        result = onSwipeRight();
                    } else {
                        result = onSwipeLeft();
                    }
                }
            } else {
                if (Math.abs(diffY) > SWIPE_THRESHOLD
                        && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        result = onSwipeBottom();
                    } else {
                        result = onSwipeTop();
                    }
                }
            }
        } catch (final Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}

public boolean onSwipeRight() {
    return false;
}

public boolean onSwipeLeft() {
    return false;
}

public void onClick() {
}

public boolean onSwipeTop() {
    return false;
}

public boolean onSwipeBottom() {
    return false;
}

EDIT 2 I could get it to work by just overriding the method onDown() in my GestureListener class and setting it to always return true. I really don't understand why I need to do that, but it seems it is working now!


问:
PHP array returns nothing (OOP newbie needs some help)
I am trying to create an form validator class that will check to make sure that people have typed a particular number of characters into specified fields.  Here is my page:

```<code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('functions.php');
    require_once('formValidator.php');

    $validator = new FormValidator();
    $validator->setFirst($_POST['first']);
    $validator->setLast($_POST['last']);
    $validator->setEmail($_POST['email']);

    $errors = array();
    $validator->checkLength($errors);
    echo $errors;

    if (!empty($errors)) {
        echo '<p>' . $message . '</p>';
    }
}
</code>```

// form here (code above is in PHP tags, of course)

Here is my class:

```<code>class FormValidator {

    public $first;
    public $last;
    public $email;
    public $fields_with_lengths;

    public function setFirst($first) {
        $this->first = $first;
    }

    public function setLast($last) {
        $this->last = $last;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    function setLengths() {
        $this->fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);
    }

    function checkLength($fields_with_lengths) {
        $length_errors = array();

        foreach($fields_with_lengths as $fieldname => $maxlength) {
            if (strlen(trim($_POST[$fieldname])) > $maxlength) {
                $length_errors[] = $fieldname;
            }
        }

        if (!empty($length_errors)) {
            $message = 'There were no errors';
        } else {
            $message = 'There were errors';

        }
        return $message;
    }

}

$validator = new FormValidator();
$validator->setFirst($_POST['first']);
$validator->setLast($_POST['last']);
$validator->setEmail($_POST['email']);
</code>```

Can anyone see what I am doing wrong?  I'd be grateful for some help. Thanks.

答: You're defining $errors = array();, making the errors an empty array.  Nowhere do you attempt to set it to any other value, thus it remains an empty array.

Body:
I am trying to create an form validator class that will check to make sure that people have typed a particular number of characters into specified fields.  Here is my page:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('functions.php');
    require_once('formValidator.php');

    $validator = new FormValidator();
    $validator->setFirst($_POST['first']);
    $validator->setLast($_POST['last']);
    $validator->setEmail($_POST['email']);

    $errors = array();
    $validator->checkLength($errors);
    echo $errors;

    if (!empty($errors)) {
        echo '
' . $message . '
';
    }
}

// form here (code above is in PHP tags, of course)

Here is my class:

class FormValidator {

    public $first;
    public $last;
    public $email;
    public $fields_with_lengths;

    public function setFirst($first) {
        $this->first = $first;
    }

    public function setLast($last) {
        $this->last = $last;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    function setLengths() {
        $this->fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);
    }

    function checkLength($fields_with_lengths) {
        $length_errors = array();

        foreach($fields_with_lengths as $fieldname => $maxlength) {
            if (strlen(trim($_POST[$fieldname])) > $maxlength) {
                $length_errors[] = $fieldname;
            }
        }

        if (!empty($length_errors)) {
            $message = 'There were no errors';
        } else {
            $message = 'There were errors';

        }
        return $message;
    }

}

$validator = new FormValidator();
$validator->setFirst($_POST['first']);
$validator->setLast($_POST['last']);
$validator->setEmail($_POST['email']);

Can anyone see what I am doing wrong?  I'd be grateful for some help. Thanks.


问:
O_NONBLOCK SOCK_STREAM limited to 8192
I'm writing from c program into a SOCK_STREAM of a Unix Domain Socket that is being listened from a go program, using net.Listen("unix", sockname). When I set the socket to O_NONBLOCK using fcntl(), I see that the C program writes only 8192 bytes in the first write. After it fails, I monitor and write back the remaining data, but the read data on my server is not valid in this case.

When I do not use O_NONBLOCK, then the whole of 8762 bytes are written in a single write and everything works as expected.

C Client Socket Connection

```<code>    if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        return;
    }
   int flags = fcntl(fd, F_GETFL, 0);
   flags = flags|O_NONBLOCK;
   fcntl(fd, F_SETFL, flags);
   ...
    if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        return;
    }
</code>```

C Client Writing

```<code>        while (written < to_write) {
            int result;
            if ((result = write(fd, &buffer[written], to_write - written)) < 0) {
                if (errno == EINTR) {
                    continue;
                }
                if (errno == EAGAIN) {
                    struct pollfd pfd = { .fd = fd, .events = POLLOUT };
                    poll_count++;
                    if (poll_count > 3) {
                        goto end;
                    }
                    if ((poll(&pfd, 1, -1) <= 0) && (errno != EAGAIN)) {
                        goto end;
                    }
                    continue;
                }
end:
                return written ? written : result;
            }
            written += result;
            buffer += result;
        }
</code>```

Go Server Reading

```<code>buf := make([]byte, 0, count)
var tmpsize int32
for {
    if count <= 0 {
        break
    }

    if count > 100 {
        tmpsize = 100
    } else {
        tmpsize = count
    }

    tmp := make([]byte, tmpsize)
    nr, err = conn.Read(tmp)
    if err != nil {
        return
    }

    buf = append(buf, tmp[:nr]...)
    count = count - int32(nr)
}
</code>```

What am I missing here. I'm running it on OSX. I also tried setting the SO_SNDBUF in the Go Server to 10000, but it does not help

```<code>err = syscall.SetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF, 10000)
if err != nil {
    return
}
</code>```

答:
This is normal behaviour. A non-blocking write can only transfer as much data as will fit into the socket send buffer. If you get a short count, you need to either loop or select on writability and retry. A blocking write on the other hand always transfers the entire data.

Setting the send buffer size may not do anything on Unix domain sockets.

Title: O_NONBLOCK SOCK_STREAM limited to 8192

Body:
I'm writing from c program into a SOCK_STREAM of a Unix Domain Socket that is being listened from a go program, using net.Listen("unix", sockname). When I set the socket to O_NONBLOCK using fcntl(), I see that the C program writes only 8192 bytes in the first write. After it fails, I monitor and write back the remaining data, but the read data on my server is not valid in this case.

When I do not use O_NONBLOCK, then the whole of 8762 bytes are written in a single write and everything works as expected.

C Client Socket Connection

    if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        return;
    }
   int flags = fcntl(fd, F_GETFL, 0);
   flags = flags|O_NONBLOCK;
   fcntl(fd, F_SETFL, flags);
   ...
    if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        return;
    }

C Client Writing

        while (written < to_write) {
            int result;
            if ((result = write(fd, &buffer[written], to_write - written)) < 0) {
                if (errno == EINTR) {
                    continue;
                }
                if (errno == EAGAIN) {
                    struct pollfd pfd = { .fd = fd, .events = POLLOUT };
                    poll_count++;
                    if (poll_count > 3) {
                        goto end;
                    }
                    if ((poll(&pfd, 1, -1) <= 0) && (errno != EAGAIN)) {
                        goto end;
                    }
                    continue;
                }
end:
                return written ? written : result;
            }
            written += result;
            buffer += result;
        }

Go Server Reading

buf := make([]byte, 0, count)
var tmpsize int32
for {
    if count <= 0 {
        break
    }

    if count > 100 {
        tmpsize = 100
    } else {
        tmpsize = count
    }

    tmp := make([]byte, tmpsize)
    nr, err = conn.Read(tmp)
    if err != nil {
        return
    }

    buf = append(buf, tmp[:nr]...)
    count = count - int32(nr)
}

What am I missing here. I'm running it on OSX. I also tried setting the SO_SNDBUF in the Go Server to 10000, but it does not help

err = syscall.SetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF, 10000)
if err != nil {
    return
}


问:
Python: ImportError: cannot import name DataFrame
I am compiling this simple code (Using SublimeText 3 and Python 2.7(Already installed on my MAC)):

```<code>from pandas import DataFrame
data = {"a": [1, 2, 3], "b": [3, 2, 1]}
data_df = DataFrame(data)
</code>```

and I am getting the following error :

```<code>Traceback (most recent call last):
File "jj.py", line 1, in <module>
from pandas import DataFrame
ImportError: cannot import name DataFrame
</code>```

Note that I installed pandas package using :

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

By the way I looked for similar asked questions and answers, but did not solve my problem.

答:
The issue is the python executable running in sublime cannot find the pandas DataFrame module.

You can try running the python file from the command line using

```<code>python <file name.py>.
</code>```

Alternatively try pip install pandas, the sublime python package may not have access to the global python dist-packages

Body:
I am compiling this simple code (Using SublimeText 3 and Python 2.7(Already installed on my MAC)):

from pandas import DataFrame
data = {"a": [1, 2, 3], "b": [3, 2, 1]}
data_df = DataFrame(data)

and I am getting the following error :

Traceback (most recent call last):
File "jj.py", line 1, in <module>
from pandas import DataFrame
ImportError: cannot import name DataFrame

Note that I installed pandas package using :

sudo pip install pandas

By the way I looked for similar asked questions and answers, but did not solve my problem.

Body:
The issue is the python executable running in sublime cannot find the pandas DataFrame module.

You can try running the python file from the command line using

python <file name.py>.

Alternatively try pip install pandas, the sublime python package may not have access to the global python dist-packages


问:
How to validate console command prompt inputs
Following console command I'm prompting for input. I would like to validate the user input. How can I do that?

I have check the this plugin. But it looks like validating arguments & options. Not the interactive inputs.

CreateClient.php

```<code>namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateClient extends Command {
    ...

    public function handle() {
        $name   = $this->ask('Enter name ');
        $email  = $this->ask('Enter email ');
        $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

        // Validate user input
        $this->info('Validating user inputs');

       // How to validate email & date format ?
    }
}
</code>```

Update

Yes I'm aware of Validator, but the concern is the validation stops the user journey. User have restart from the beginning. Is it possible to attach a validation to each question, so the validation will be immediate and prompt to enter again.

Below is something I notice when I doesn't enter any value, I'm wondering how can I provide more validation rule.

Thanks in advance.

答:
One way would be to use FILTER_VALIDATE_EMAIL and Carbon

```<code>public function handle() {
    $name   = $this->ask('Enter name ');
    $email  = $this->ask('Enter email ');
    $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

    // Validate user input
    $this->info('Validating user inputs');

    // How to validate email & date format ?
    $email_status = filter_var($email, FILTER_VALIDATE_EMAIL);

    if (!$email_status) {
        // Invalid EMAIL
    }

    if (\Carbon::createFromFormat('YOUR DATE FORMAT', $date) === false) {
        // Invalid date
    }

}
</code>```

Another method would be as said by @btl using Validator

```<code>public function handle() {
    $name   = $this->ask('Enter name ');
    $email  = $this->ask('Enter email ');
    $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

    // Validate user input
    $this->info('Validating user inputs');

    $data = array(
        'email' => $email,
        'date'  => $date
    );

    $rules = array(
        'email' => 'required|email',
        'date'  => 'required|date',
    );

    $validator = \Validator::make($data, $rules);

    if ($validator->fails()) {
        $messages = $validator->messages();
    }

}
</code>```

Body:
Following console command I'm prompting for input. I would like to validate the user input. How can I do that?

I have check the this plugin. But it looks like validating arguments & options. Not the interactive inputs.

CreateClient.php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateClient extends Command {
    ...

    public function handle() {
        $name   = $this->ask('Enter name ');
        $email  = $this->ask('Enter email ');
        $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

        // Validate user input
        $this->info('Validating user inputs');

       // How to validate email & date format ?
    }
}

Update

Yes I'm aware of Validator, but the concern is the validation stops the user journey. User have restart from the beginning. Is it possible to attach a validation to each question, so the validation will be immediate and prompt to enter again.

Below is something I notice when I doesn't enter any value, I'm wondering how can I provide more validation rule.

Thanks in advance.

Body:
One way would be to use FILTER_VALIDATE_EMAIL and Carbon

public function handle() {
    $name   = $this->ask('Enter name ');
    $email  = $this->ask('Enter email ');
    $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

    // Validate user input
    $this->info('Validating user inputs');

    // How to validate email & date format ?
    $email_status = filter_var($email, FILTER_VALIDATE_EMAIL);

    if (!$email_status) {
        // Invalid EMAIL
    }

    if (\Carbon::createFromFormat('YOUR DATE FORMAT', $date) === false) {
        // Invalid date
    }

}

Another method would be as said by @btl using Validator

public function handle() {
    $name   = $this->ask('Enter name ');
    $email  = $this->ask('Enter email ');
    $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

    // Validate user input
    $this->info('Validating user inputs');

    $data = array(
        'email' => $email,
        'date'  => $date
    );

    $rules = array(
        'email' => 'required|email',
        'date'  => 'required|date',
    );

    $validator = \Validator::make($data, $rules);

    if ($validator->fails()) {
        $messages = $validator->messages();
    }

}


问:
Writing to Oracle Database using Apache Spark 1.4.0
I am trying to write some data to our Oracle database using Spark 1.4.0 DataFrame.write.jdbc() function.

The symmetric read.jdbc() function for reading data from Oracle Database to DataFrame objects works well. However while I am writing the dataframe back (I also tried to write exactly same object that I got from database setting CverWrite to true) gives the following exception:

```<code>Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00902: Ungültiger Datentyp

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1017)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:655)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:249)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:566)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:215)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:58)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:943)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1075)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3820)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3897)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1361)
    at org.apache.spark.sql.DataFrameWriter.jdbc(DataFrameWriter.scala:252)
    at main3$.main(main3.scala:72)
    at main3.main(main3.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
</code>```

The table has 2 basic string columns. When they are Integer, it can also write it.

Actually when I go deeper, I realize that it maps StringType to "TEXT" which is not recognized by Oracle (should be "VARCHAR" instead). The code is following from jdbc.scala which may be found at GitHub:

```<code>def schemaString(df: DataFrame, url: String): String = {
      val sb = new StringBuilder()
      val dialect = JdbcDialects.get(url)
      df.schema.fields foreach { field => {
        val name = field.name
        val typ: String =
          dialect.getJDBCType(field.dataType).map(_.databaseTypeDefinition).getOrElse(
          field.dataType match {
            case IntegerType => "INTEGER"
            case LongType => "BIGINT"
            case DoubleType => "DOUBLE PRECISION"
            case FloatType => "REAL"
            case ShortType => "INTEGER"
            case ByteType => "BYTE"
            case BooleanType => "BIT(1)"
            case StringType => "TEXT"
            case BinaryType => "BLOB"
            case TimestampType => "TIMESTAMP"
            case DateType => "DATE"
            case DecimalType.Unlimited => "DECIMAL(40,20)"
            case _ => throw new IllegalArgumentException(s"Don't know how to save $field to JDBC")
          })
        val nullable = if (field.nullable) "" else "NOT NULL"
        sb.append(s", $name $typ $nullable")
      }}
      if (sb.length < 2) "" else sb.substring(2)
    }
</code>```

So the question is am I mistaken somewhere or SparkSQL does not support Oracle and should I install a plug-in to use SparkSQL with Oracle?

My simple main is:

```<code>val conf = new SparkConf().setAppName("Parser").setMaster("local[*]")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)

val reader = sqlContext.read
val frame = reader.jdbc(url,"STUDENTS",connectionprop)

frame.printSchema()
frame.show()

val row = Row("3","4")

val struct =
  StructType(
    StructField("ONE", StringType, true) ::
      StructField("TWO", StringType, true) :: Nil)

val arr = Array(row)
val rddRow = sc.parallelize(arr)
val dframe = sqlContext.createDataFrame(rddRow,struct
)
dframe.printSchema()
dframe.show()

dframe.write.jdbc(url,"STUDENTS",connectionprop)
</code>```

答:
Update : Starting from Spark 2.x

There is an issue wherein every columnName is double quoted in Spark while creating jdbc table and hence all the Oracle table columnNames becomes case sensitive when you try to query them via sqlPlus.

```<code>select colA from myTable; => doesn't works anymore
select "colA" from myTable; =>  works
</code>```

[Solution]
Dataframe to Oracle creates table with case sensitive column

Body:
I am trying to write some data to our Oracle database using Spark 1.4.0 DataFrame.write.jdbc() function.

The symmetric read.jdbc() function for reading data from Oracle Database to DataFrame objects works well. However while I am writing the dataframe back (I also tried to write exactly same object that I got from database setting CverWrite to true) gives the following exception:

Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00902: Ungültiger Datentyp

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1017)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:655)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:249)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:566)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:215)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:58)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:943)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1075)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3820)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3897)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1361)
    at org.apache.spark.sql.DataFrameWriter.jdbc(DataFrameWriter.scala:252)
    at main3$.main(main3.scala:72)
    at main3.main(main3.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

The table has 2 basic string columns. When they are Integer, it can also write it.

Actually when I go deeper, I realize that it maps StringType to "TEXT" which is not recognized by Oracle (should be "VARCHAR" instead). The code is following from jdbc.scala which may be found at GitHub:

def schemaString(df: DataFrame, url: String): String = {
      val sb = new StringBuilder()
      val dialect = JdbcDialects.get(url)
      df.schema.fields foreach { field => {
        val name = field.name
        val typ: String =
          dialect.getJDBCType(field.dataType).map(_.databaseTypeDefinition).getOrElse(
          field.dataType match {
            case IntegerType => "INTEGER"
            case LongType => "BIGINT"
            case DoubleType => "DOUBLE PRECISION"
            case FloatType => "REAL"
            case ShortType => "INTEGER"
            case ByteType => "BYTE"
            case BooleanType => "BIT(1)"
            case StringType => "TEXT"
            case BinaryType => "BLOB"
            case TimestampType => "TIMESTAMP"
            case DateType => "DATE"
            case DecimalType.Unlimited => "DECIMAL(40,20)"
            case _ => throw new IllegalArgumentException(s"Don't know how to save $field to JDBC")
          })
        val nullable = if (field.nullable) "" else "NOT NULL"
        sb.append(s", $name $typ $nullable")
      }}
      if (sb.length < 2) "" else sb.substring(2)
    }

So the question is am I mistaken somewhere or SparkSQL does not support Oracle and should I install a plug-in to use SparkSQL with Oracle?

My simple main is:

val conf = new SparkConf().setAppName("Parser").setMaster("local[*]")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)

val reader = sqlContext.read
val frame = reader.jdbc(url,"STUDENTS",connectionprop)

frame.printSchema()
frame.show()

val row = Row("3","4")

val struct =
  StructType(
    StructField("ONE", StringType, true) ::
      StructField("TWO", StringType, true) :: Nil)

val arr = Array(row)
val rddRow = sc.parallelize(arr)
val dframe = sqlContext.createDataFrame(rddRow,struct
)
dframe.printSchema()
dframe.show()

dframe.write.jdbc(url,"STUDENTS",connectionprop)

Body:
Update : Starting from Spark 2.x

There is an issue wherein every columnName is double quoted in Spark while creating jdbc table and hence all the Oracle table columnNames becomes case sensitive when you try to query them via sqlPlus.

select colA from myTable; => doesn't works anymore
select "colA" from myTable; =>  works

[Solution]
Dataframe to Oracle creates table with case sensitive column


问:
How to get C++-template-like behavior but only allow two specific types to be instantiated?
I'm trying to get a specific type of behavior from an inline C++ function, and I'm not sure if there's a way to do it or not.

I want my function to accept either a signed or an unsigned 16-bit value as an argument, perform an operation on that value, and then return a value of that same type.  If the argument's signed/unsigned-ness is ambiguous (e.g. because it's a constant), then it's okay for the compiler to just pick the signed version.  Here's a toy program showing my first attempt at getting that behavior:

```<code> #include <iostream>
 #include <cstdint>

  int16_t getValuePlusOne( int16_t x) {return x+1;}
 uint16_t getValuePlusOne(uint16_t x) {return x+1;}

 using namespace std;

 int main(int, char **)
 {
     int16_t   signedVal = -15;
    uint16_t unsignedVal = 23;

    cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
    cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
    cout << getValuePlusOne(1234)        << endl;  // COMPILE ERROR, ambiguous!  D'oh!
    return 0;
 }
</code>```

So that almost worked, but it errors out on the getValuePlusOne(1234) since 1234 is ambiguous (it could be signed or unsigned).  Fair enough, but I'd like it not to do that.

So here's my second attempt:

```<code>#include <iostream>
#include <cstdint>

template <typename T> T getValuePlusOne(T val) {return val+1;}

using namespace std;

int main(int, char **)
{
    int16_t   signedVal = 5;
   uint16_t unsignedVal = 5;

   cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
   cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
   cout << getValuePlusOne(1234)        << endl;  // works, yay!

   uint32_t inappropriateType32 = 54321;
   cout << getValuePlusOne(inappropriateType32) << endl;  // works, but I want this to be a compile-time error!  D'oh!

   float inappropriateTypeFloat = 666.0;
   cout << getValuePlusOne(inappropriateTypeFloat) << endl;  // works, but I want this to be a compile-time error!

   return 0;
}
</code>```

This version works just how I want it to work for the first three calls to getValuePlusOne() -- they compile without errors and the template mechanism makes sure that getValuePlusOne()'s return type matches its argument type, and chooses a default argument/return type in the ambiguous case.  Yay!

But -- this version also allows the user to pass in inappropriate values (e.g. 32-bit integers, or even -- gasp -- floating point types) which don't make sense in the context of my application, so I want the compiler to flag those calls as compile-time errors, and that doesn't happen with this implementation.

Is there any way for me to have my cake and eat it too?

答:
You can use sfinae to limit the function to parameters that conform to certain criteria:</p>

```<code>template<typename T>
constexpr bool is_any_int16 = std::is_same<T, int16_t>::value || std::is_same<T, uint16_t>::value;

template<typename T>
auto getValuePlusOne(T x) -> std::enable_if_t<is_any_int16<T>, T> {
    return x + 1;
}
</code>```

Body:
I'm trying to get a specific type of behavior from an inline C++ function, and I'm not sure if there's a way to do it or not.

I want my function to accept either a signed or an unsigned 16-bit value as an argument, perform an operation on that value, and then return a value of that same type.  If the argument's signed/unsigned-ness is ambiguous (e.g. because it's a constant), then it's okay for the compiler to just pick the signed version.  Here's a toy program showing my first attempt at getting that behavior:

 #include <iostream>
 #include <cstdint>

  int16_t getValuePlusOne( int16_t x) {return x+1;}
 uint16_t getValuePlusOne(uint16_t x) {return x+1;}

 using namespace std;

 int main(int, char **)
 {
     int16_t   signedVal = -15;
    uint16_t unsignedVal = 23;

    cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
    cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
    cout << getValuePlusOne(1234)        << endl;  // COMPILE ERROR, ambiguous!  D'oh!
    return 0;
 }

So that almost worked, but it errors out on the getValuePlusOne(1234) since 1234 is ambiguous (it could be signed or unsigned).  Fair enough, but I'd like it not to do that.

So here's my second attempt:

#include <iostream>
#include <cstdint>

template <typename T> T getValuePlusOne(T val) {return val+1;}

using namespace std;

int main(int, char **)
{
    int16_t   signedVal = 5;
   uint16_t unsignedVal = 5;

   cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
   cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
   cout << getValuePlusOne(1234)        << endl;  // works, yay!

   uint32_t inappropriateType32 = 54321;
   cout << getValuePlusOne(inappropriateType32) << endl;  // works, but I want this to be a compile-time error!  D'oh!

   float inappropriateTypeFloat = 666.0;
   cout << getValuePlusOne(inappropriateTypeFloat) << endl;  // works, but I want this to be a compile-time error!

   return 0;
}

This version works just how I want it to work for the first three calls to getValuePlusOne() -- they compile without errors and the template mechanism makes sure that getValuePlusOne()'s return type matches its argument type, and chooses a default argument/return type in the ambiguous case.  Yay!

But -- this version also allows the user to pass in inappropriate values (e.g. 32-bit integers, or even -- gasp -- floating point types) which don't make sense in the context of my application, so I want the compiler to flag those calls as compile-time errors, and that doesn't happen with this implementation.

Is there any way for me to have my cake and eat it too?

Body:
You can use sfinae to limit the function to parameters that conform to certain criteria:

template<typename T>
constexpr bool is_any_int16 = std::is_same<T, int16_t>::value || std::is_same<T, uint16_t>::value;

template<typename T>
auto getValuePlusOne(T x) -> std::enable_if_t<is_any_int16<T>, T> {
    return x + 1;
}


问:
how do i connect to oracle with the info i have?
i have the info below from the oracle DBA and want to connect to oracle from a .net application. i just got done installing the oracle tools/ drivers for windows/ .net and now want to get a console app to connect tot he oracle DB and extract data from oracle into SQL server.

another solution would be to have SQL server pull from oracle all the records in the bugs table. i have no clue what the oracle connection string is and have tried to create a system DSN but failed at that prior to turning to the SO gurus...

ORACLE SQL user name is ‘USER_dev’,
  password is ‘welcome’.

Connection string is
  ‘jdbc:mercury:oracle://qct-ds2-p.apps.com:1139;sid=QCTRP1’

答:
i got lucky and found a simple solution that is all in .net and requires nothing more than this syntax by way of a connection string. all the .ora stuff is presented in the connection string and works well.</p>

```<code>static void getData()
        {
            string connectionString = GetConnectionString();
            using (OracleConnection connection = new OracleConnection())
            {
                connection.ConnectionString = connectionString;
                connection.Open();
                //Console.WriteLine("State: {0}", connection.State);
                //Console.WriteLine("ConnectionString: {0}", connection.ConnectionString);

                OracleCommand command = connection.CreateCommand();
                string sql = "SELECT * FROM BUG";
                //string sql = "SELECT table_name FROM user_tables";
                command.CommandText = sql;

                OracleDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    //string myField = (string)reader["Project"];
                    string myField = (string)reader[0];
                    Console.WriteLine(myField);
                }
            }

        }

        static private string GetConnectionString()
        {
            return "User Id=USER_dev;Password=welcome;Data Source=(DESCRIPTION=" +
                    "(ADDRESS=(PROTOCOL=TCP)(HOST=111.123.479.24)(PORT=1139))" +
                    "(CONNECT_DATA=(SID=QCTRP1)));";

        }
</code>```

Body:
i got lucky and found a simple solution that is all in .net and requires nothing more than this syntax by way of a connection string. all the .ora stuff is presented in the connection string and works well.

static void getData()
        {
            string connectionString = GetConnectionString();
            using (OracleConnection connection = new OracleConnection())
            {
                connection.ConnectionString = connectionString;
                connection.Open();
                //Console.WriteLine("State: {0}", connection.State);
                //Console.WriteLine("ConnectionString: {0}", connection.ConnectionString);

                OracleCommand command = connection.CreateCommand();
                string sql = "SELECT * FROM BUG";
                //string sql = "SELECT table_name FROM user_tables";
                command.CommandText = sql;

                OracleDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    //string myField = (string)reader["Project"];
                    string myField = (string)reader[0];
                    Console.WriteLine(myField);
                }
            }

        }

        static private string GetConnectionString()
        {
            return "User Id=USER_dev;Password=welcome;Data Source=(DESCRIPTION=" +
                    "(ADDRESS=(PROTOCOL=TCP)(HOST=111.123.479.24)(PORT=1139))" +
                    "(CONNECT_DATA=(SID=QCTRP1)));";

        }


问:
SQL(MSSQL/MariaDB) or NoSQL(MongoDB): XML search and processing
Current project situation.

Get lot of XML from outside system whose size is less than 50KB and if it contains an attachment, the size would be around 5MB MAX. XML structure complexity is medium because of inner nested elements. There are ~70 first level element and then its child and child of child... Storing that XML in String column of MS SQL server.

While storing XML, we read Search criteria field from XML and maintain them in new columns to improve search queries.

Search functionality to display these messages data in the form of list. Search criteria fields(optional ~10 fields) are from XML elements. Parse that XML to show the elements(around 10 -15) in lists

There are chances of reporting functionality too in future.

Challenge with this design: If new functionality introduced to search the list  based on new criteria, then need to add one more column in DB table and have to store that field value from XML which is not best part of this design.

Suggested Improvement: Instead of storing an XML in String format, plan is to store it as an XML column to get a rid of extra columns to keep value of search fields and use XML column query for search and fetch.

Question:

Which DB will give me optimum performance in case of search? I have to fetch only the XMLs which are fitting inside that search criteria.

SQL or NoSQL like MongoDB?

Is there any performance metrics available? Or any case study for same?

DB to manage Reporting load.

答: What client language are you using?  Java / PHP / C# / ...?  Most of them have XML libraries that do what you need.  A database is a data repository, not a data manipulator.</p>