问:
Spark/scala create empty dataset using generics in a trait
I have a trait called that takes a type parameter, and one of its methods needs to be able to create an empty typed dataset.

```<code>trait MyTrait[T] {
    val sparkSession: SparkSession
    val spark = sparkSession.session
    val sparkContext = spark.sparkContext

    def createEmptyDataset(): Dataset[T] = {
        import spark.implicits._ // to access .toDS() function
        // DOESN'T WORK.
        val emptyRDD = sparkContext.parallelize(Seq[T]())
        val accumulator = emptyRDD.toDS()
        ...
    }
}
</code>```

So far I have not gotten it to work. It complains no ClassTag for T, and that value toDS is not a member of org.apache.spark.rdd.RDD[T]

Any help would be appreciated. Thanks!

答:
You have to provide both ClassTag[T] and Encoder[T] in the same scope. For example:

```<code>import org.apache.spark.sql.{SparkSession, Dataset, Encoder}
import scala.reflect.ClassTag

trait MyTrait[T] {
    val ct: ClassTag[T]
    val enc: Encoder[T]

    val sparkSession: SparkSession
    val sparkContext = spark.sparkContext

    def createEmptyDataset(): Dataset[T] = {
        val emptyRDD = sparkContext.emptyRDD[T](ct)
        spark.createDataset(emptyRDD)(enc)
    }
}
</code>```

with concrete implementation:

```<code>class Foo extends MyTrait[Int] {
   val sparkSession = SparkSession.builder.getOrCreate()
   import sparkSession.implicits._

   val ct = implicitly[ClassTag[Int]]
   val enc = implicitly[Encoder[Int]]
}
</code>```

It is possible to skip RDD:

```<code>import org.apache.spark.sql.{SparkSession, Dataset, Encoder}

trait MyTrait[T] {
    val enc: Encoder[T]

    val sparkSession: SparkSession
    val sparkContext = spark.sparkContext

    def createEmptyDataset(): Dataset[T] = {
        spark.emptyDataset[T](enc)
    }
}
</code>```

Check How to declare traits as taking implicit "constructor parameters"?, specifically answer by Blaisorblade and another one by Alexey Romanov.

Body:
I have a trait called that takes a type parameter, and one of its methods needs to be able to create an empty typed dataset.

trait MyTrait[T] {
    val sparkSession: SparkSession
    val spark = sparkSession.session
    val sparkContext = spark.sparkContext

    def createEmptyDataset(): Dataset[T] = {
        import spark.implicits._ // to access .toDS() function
        // DOESN'T WORK.
        val emptyRDD = sparkContext.parallelize(Seq[T]())
        val accumulator = emptyRDD.toDS()
        ...
    }
}

So far I have not gotten it to work. It complains no ClassTag for T, and that value toDS is not a member of org.apache.spark.rdd.RDD[T]

Any help would be appreciated. Thanks!

Body:
You have to provide both ClassTag[T] and Encoder[T] in the same scope. For example:

import org.apache.spark.sql.{SparkSession, Dataset, Encoder}
import scala.reflect.ClassTag

trait MyTrait[T] {
    val ct: ClassTag[T]
    val enc: Encoder[T]

    val sparkSession: SparkSession
    val sparkContext = spark.sparkContext

    def createEmptyDataset(): Dataset[T] = {
        val emptyRDD = sparkContext.emptyRDD[T](ct)
        spark.createDataset(emptyRDD)(enc)
    }
}

with concrete implementation:

class Foo extends MyTrait[Int] {
   val sparkSession = SparkSession.builder.getOrCreate()
   import sparkSession.implicits._

   val ct = implicitly[ClassTag[Int]]
   val enc = implicitly[Encoder[Int]]
}

It is possible to skip RDD:

import org.apache.spark.sql.{SparkSession, Dataset, Encoder}

trait MyTrait[T] {
    val enc: Encoder[T]

    val sparkSession: SparkSession
    val sparkContext = spark.sparkContext

    def createEmptyDataset(): Dataset[T] = {
        spark.emptyDataset[T](enc)
    }
}

Check How to declare traits as taking implicit "constructor parameters"?, specifically answer by Blaisorblade and another one by Alexey Romanov.


来源: stackexchange

问:
How to add zero to a time
I have a function that receives a time, in a string, and another number to add to the time:

```<code>def get_hours(hm):
   return int(hm.split(':')[0])

def get_minutes(hm):
   return int(hm.split(':')[1])

def add_minutes(hm, incr):
"""Increment the given time by the given amount of minutes.

Requires:
- hm str with a time represented as HH:MM;
- incr int with the number of minutes.
Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes.
"""
if get_minutes(hm)+incr>=60:
    if get_hours(hm)==23:
        return '00:'+str((get_minutes(hm)+incr)-60)
    else:
        return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60)
else:
    return str(get_hours(hm))+':'+str((get_minutes(hm)+incr))
</code>```

The problem is when the time is 16:05 or 04:06, it doesn't display the zeros, so it's just 16:5 and 4:6. How can i make this work?

答:
Python has a function on the string class that may help you here;

```<code>"3".zfill(2)  # this will output 03
"20".zfill(2)  # this will output 20
</code>```

Simply cast your ints to a string, and call .zfill(2) prior to printing any results.

ContentLicense: CC BY-SA 3.0

Title: How to add zero to a time

Body:
I have a function that receives a time, in a string, and another number to add to the time:

def get_hours(hm):
   return int(hm.split(':')[0])

def get_minutes(hm):
   return int(hm.split(':')[1])

def add_minutes(hm, incr):
"""Increment the given time by the given amount of minutes.

Requires:
- hm str with a time represented as HH:MM;
- incr int with the number of minutes.
Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes.
"""
if get_minutes(hm)+incr>=60:
    if get_hours(hm)==23:
        return '00:'+str((get_minutes(hm)+incr)-60)
    else:
        return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60)
else:
    return str(get_hours(hm))+':'+str((get_minutes(hm)+incr))

The problem is when the time is 16:05 or 04:06, it doesn't display the zeros, so it's just 16:5 and 4:6. How can i make this work?

Body:
Python has a function on the string class that may help you here;

"3".zfill(2)  # this will output 03
"20".zfill(2)  # this will output 20

Simply cast your ints to a string, and call .zfill(2) prior to printing any results.


问:
Why an action is not defined in action-creator function in react-redux?
While trying to make a simple appointment app using react-redux, I get an error where one item (lastname) in the action is not defined. The other two items (firstname and id) are properly defined. Why would this action item be not defined while others are defined? I feel i am missing a key concept in react-redux. Can you explain why the action is not defined and how to correct it?
action-creator:

```<code>import { ADD_BOOKING, DELETE_BOOKING } from "../constants";

const uid = () => Math.random().toString(34)

export const addBooking=function (firstname,lastname){

    const action={
        type:ADD_BOOKING,
        payload:{firstname,
                lastname,
                id:uid()

        }
    }
console.log('action in addBooking',action);
return action;
}

export const deleteBooking = (id) => {
    const action = {
        type: DELETE_BOOKING,
        id: id
    };
    console.log("deleting in actions", action);
    return action;
};
</code>```

reducer:

```<code>import { ADD_BOOKING, DELETE_BOOKING} from "../constants";

const booking = action => {
    return {
        firstname: action.payload.firstname,
        lastname: action.payload.lastname,
        id: action.payload.id
    };
};

const removeById = (state = [], id) => {
    //filter those not clicked
    const bookings = state.filter(booking => booking.id !==id);
    console.log("new reduced bookings", bookings);
    return bookings;
};

const bookings = (state = [], action) => {
    let bookings = null;
    switch (action.type) {
        case ADD_BOOKING:
            bookings = [...state, booking(action)];
            console.log("bookings as state", bookings);
            return bookings;
        case DELETE_BOOKING:
            bookings = removeById(state, action.id);
            return bookings;

        default:
            return state;
    }
};
export {bookings};
</code>```

Console log:

Component (App.jsx):

```<code>import React, { Component } from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { addBooking, deleteBooking } from "../actions";
import { Header } from "./NavigationBar";
import { connect } from "react-redux";

class App extends Component {
  //Initialize the Component
  constructor(props) {
    super(props);
    this.state = {
      firstname: "",
      lastname: "",
      duedate: ""
    };
  }
  //add Booking
  addBooking() {
    this.props.addBooking(this.state.firstname);
    this.props.addBooking(this.state.lastname);

  }

  //delete Booking
  deleteBooking(id) {
    this.props.deleteBooking(id);
  }
  //render the bookings
  renderBookings() {
    //access our bookings

   const {bookings} = this.props;

    return (
      <ul className="list-group col-sm-4">
        { bookings.map(booking => {
            return (<li key={ booking.id } className="list-group item">
                      <div className="list-item">
                        { booking.firstname }
                      </div>
                      <div className="list-item">
                        { booking.lastname }
                      </div>

                      <div className="btn btn-danger" onClick={ () => this.deleteBooking(booking.id) }>
                        Cancel Booking

                      </div>
                    </li>)
          }) }
      </ul>)
  }
  render() {
    return (
      <div className="App">
        <Header />
        <div className="form-inline booking-form">
          <div className="form-group">
            <input
              className="form-control"
              placeholder="Enter First Name"
              onChange={event =>
                this.setState({
                  firstname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              placeholder="Enter Last Name"
              onChange={event =>
                this.setState({
                  lastname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              type="datetime-local"
              onChange={event =>
                this.setState({
                  duedate: event.target.value
                })
              }
            />

            <button
              type="button"
              className="btn btn-success"
              onClick={() => this.addBooking()}
            >
              Add Booking
            </button>
          </div>
        </div>
        {this.renderBookings()}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    bookings: state
  };
}

export default connect(mapStateToProps, {
  addBooking,
  deleteBooking
})(App);
</code>```

答:
Since you are wrapping App with connect, App now has the ability to dispatch actions. dispatch can be accessed via props with this.props.dispatch. So instead of this.props.addBooking use this.props.dispatch(addBooking()).

Also you can edit

```<code>export default connect(mapStateToProps, {
  addBooking,
  deleteBooking
})(App);
</code>```

to

```<code>export default connect()(App)
</code>```

More on connect here. Connect is used to cherry pick specific parts of the store and expose them to whatever component you are wrapping. In this case you just want to use your actions, and are importing them at the top of App.jsx

Even though you're calling addBooking()/deleteBooking() it is not flowing through the correct channels (dispatch) for Redux to know to update the store, so the values come back as undefined.

Body:
While trying to make a simple appointment app using react-redux, I get an error where one item (lastname) in the action is not defined. The other two items (firstname and id) are properly defined. Why would this action item be not defined while others are defined? I feel i am missing a key concept in react-redux. Can you explain why the action is not defined and how to correct it?
action-creator:

import { ADD_BOOKING, DELETE_BOOKING } from "../constants";

const uid = () => Math.random().toString(34)

export const addBooking=function (firstname,lastname){

    const action={
        type:ADD_BOOKING,
        payload:{firstname,
                lastname,
                id:uid()

        }
    }
console.log('action in addBooking',action);
return action;
}

export const deleteBooking = (id) => {
    const action = {
        type: DELETE_BOOKING,
        id: id
    };
    console.log("deleting in actions", action);
    return action;
};

reducer:

import { ADD_BOOKING, DELETE_BOOKING} from "../constants";

const booking = action => {
    return {
        firstname: action.payload.firstname,
        lastname: action.payload.lastname,
        id: action.payload.id
    };
};

const removeById = (state = [], id) => {
    //filter those not clicked
    const bookings = state.filter(booking => booking.id !==id);
    console.log("new reduced bookings", bookings);
    return bookings;
};

const bookings = (state = [], action) => {
    let bookings = null;
    switch (action.type) {
        case ADD_BOOKING:
            bookings = [...state, booking(action)];
            console.log("bookings as state", bookings);
            return bookings;
        case DELETE_BOOKING:
            bookings = removeById(state, action.id);
            return bookings;

        default:
            return state;
    }
};
export {bookings};

Console log:

Component (App.jsx):

import React, { Component } from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { addBooking, deleteBooking } from "../actions";
import { Header } from "./NavigationBar";
import { connect } from "react-redux";

class App extends Component {
  //Initialize the Component
  constructor(props) {
    super(props);
    this.state = {
      firstname: "",
      lastname: "",
      duedate: ""
    };
  }
  //add Booking
  addBooking() {
    this.props.addBooking(this.state.firstname);
    this.props.addBooking(this.state.lastname);

  }

  //delete Booking
  deleteBooking(id) {
    this.props.deleteBooking(id);
  }
  //render the bookings
  renderBookings() {
    //access our bookings

   const {bookings} = this.props;

    return (

        { bookings.map(booking => {
            return (

                        { booking.firstname }

                        { booking.lastname }

 this.deleteBooking(booking.id) }>
                        Cancel Booking

)
          }) }

)
  }
  render() {
    return (

            <input
              className="form-control"
              placeholder="Enter First Name"
              onChange={event =>
                this.setState({
                  firstname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              placeholder="Enter Last Name"
              onChange={event =>
                this.setState({
                  lastname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              type="datetime-local"
              onChange={event =>
                this.setState({
                  duedate: event.target.value
                })
              }
            />

            <button
              type="button"
              className="btn btn-success"
              onClick={() => this.addBooking()}
            >
              Add Booking
            </button>

        {this.renderBookings()}

    );
  }
}

function mapStateToProps(state) {
  return {
    bookings: state
  };
}

export default connect(mapStateToProps, {
  addBooking,
  deleteBooking
})(App);

Body:
Since you are wrapping App with connect, App now has the ability to dispatch actions. dispatch can be accessed via props with this.props.dispatch. So instead of this.props.addBooking use this.props.dispatch(addBooking()).

Also you can edit

export default connect(mapStateToProps, {
  addBooking,
  deleteBooking
})(App);

to

export default connect()(App)

More on connect here. Connect is used to cherry pick specific parts of the store and expose them to whatever component you are wrapping. In this case you just want to use your actions, and are importing them at the top of App.jsx

Even though you're calling addBooking()/deleteBooking() it is not flowing through the correct channels (dispatch) for Redux to know to update the store, so the values come back as undefined.


问:
How can I refactor this XSLT
I have an issue regarding some refactoring of som XSLT code on a project i'm working on. The XSLT I have now

```<code><pdf:sometext text="{$metadata/namespace:template
                     /namespace:template_collection
                     //namespace:option
                     [namespace:identificator
                      = $report_option_identifier]
                     /namespace:name}"/>
</code>```

The problem is that the XSLT needs to be extended to hit more nodes (a new version of the origianl XML, with slighty changed namespaces and slightly changed tags).

I came up with this code:

```<code><xsl:variable name="report_template_collection"
              select="$metadata
                      /namespace:template
                      /namespace:template_collection
                      |
                      $metadata
                      /namespace2:templateV2
                      /namespace2:template_collectionV2" />
<xsl:variable name="current_report_option"
              select="namespace:option | namespace2:optionV2" />
<xsl:variable name="incomplete_report_option_text"
              select="$report_template_collection
                      //$current_report_option
                      [namespace:identificator
                      = $report_option_identifier]
                      /namespace:name"/>

<pdf:sometext text="{$incomplete_report_option_text}"/>
</code>```

But when compiled it comes with ths error:

Unexpected token '$' in the expression.
$report_template_collection// -->$<-- current_report_option[namespace:opt...

So my question is: How can I refactor the XSLT to account for the new typs (named V2) and in another namespace. it's important that the same XSLT is compliant to all versions of the XML (both the old and the new version).

Thanks in advance!

答:
An XPath expression of the form A/B/$C is actually legal in XPath 2.0, but not in XPath 1.0. But it probably doesn't mean what you think it means. Like @ewh I suspect (without any evidence) that you are imagining that if the variable $C is bound to the expression D|E, then A/B/$C is another way of writing A/B/(D|E). That isn't the case; $C is bound to a value (a sequence of nodes), not to an expression.

You could use a function instead of a variable:

```<code><xsl:function name="f:current_report_option">
  <xsl:param name="node" as="node()"/>
  <xsl:sequence select="$node/(D|E)"/>
</xsl:function>

<xsl:variable name="X" select="A/B/f:current_report_option(.)"/>
</code>```

Title: How can I refactor this XSLT

Body:
I have an issue regarding some refactoring of som XSLT code on a project i'm working on. The XSLT I have now

<pdf:sometext text="{$metadata/namespace:template
                     /namespace:template_collection
                     //namespace:option
                     [namespace:identificator
                      = $report_option_identifier]
                     /namespace:name}"/>

The problem is that the XSLT needs to be extended to hit more nodes (a new version of the origianl XML, with slighty changed namespaces and slightly changed tags).

I came up with this code:

<xsl:variable name="report_template_collection"
              select="$metadata
                      /namespace:template
                      /namespace:template_collection
                      |
                      $metadata
                      /namespace2:templateV2
                      /namespace2:template_collectionV2" />
<xsl:variable name="current_report_option"
              select="namespace:option | namespace2:optionV2" />
<xsl:variable name="incomplete_report_option_text"
              select="$report_template_collection
                      //$current_report_option
                      [namespace:identificator
                      = $report_option_identifier]
                      /namespace:name"/>

<pdf:sometext text="{$incomplete_report_option_text}"/>

But when compiled it comes with ths error:

Unexpected token '$' in the expression.
$report_template_collection// -->$<-- current_report_option[namespace:opt...

So my question is: How can I refactor the XSLT to account for the new typs (named V2) and in another namespace. it's important that the same XSLT is compliant to all versions of the XML (both the old and the new version).

Thanks in advance!

Body:
An XPath expression of the form A/B/$C is actually legal in XPath 2.0, but not in XPath 1.0. But it probably doesn't mean what you think it means. Like @ewh I suspect (without any evidence) that you are imagining that if the variable $C is bound to the expression D|E, then A/B/$C is another way of writing A/B/(D|E). That isn't the case; $C is bound to a value (a sequence of nodes), not to an expression.

You could use a function instead of a variable:

<xsl:function name="f:current_report_option">
  <xsl:param name="node" as="node()"/>
  <xsl:sequence select="$node/(D|E)"/>
</xsl:function>

<xsl:variable name="X" select="A/B/f:current_report_option(.)"/>


问:
Combobox not working with SqlDataReader
```<code>private void comboBox45_SelectedIndexChanged(object sender, EventArgs e)
{
     baglanti.Open();

     string str = "select * from satilikkonutlar where ilanbasligi='" + comboBox45.Text.Trim() + "";

     SqlCommand com = new SqlCommand(str, baglanti);
     SqlDataReader reader = com.ExecuteReader(); ``

     while (reader.Read())
     {
         textBox4.Text = reader["fiyat"].ToString();
     }

     reader.Close();
     baglanti.Close();
}
</code>```

The reader is not working help me guys ty.

答:
Your statement is incorrect

```<code>string str = "select * from satilikkonutlar where ilanbasligi='" +
comboBox45.Text.Trim() + "'";
</code>```

You need the ending '

However, you should consider parameter-izing the query.

```<code>SqlCommand command = new SqlCommand(
         "select * from satilikkonutlar where ilanbasligi=@value",connection)
command.Parameters.Add(new SqlParameter("value",comboBox45.Text.Trim()));
SqlDataReader reader = command.ExecuteReader();
</code>```

Title: Combobox not working with SqlDataReader

Body:
private void comboBox45_SelectedIndexChanged(object sender, EventArgs e)
{
     baglanti.Open();

     string str = "select * from satilikkonutlar where ilanbasligi='" + comboBox45.Text.Trim() + "";

     SqlCommand com = new SqlCommand(str, baglanti);
     SqlDataReader reader = com.ExecuteReader(); ``

     while (reader.Read())
     {
         textBox4.Text = reader["fiyat"].ToString();
     }

     reader.Close();
     baglanti.Close();
}

The reader is not working help me guys ty.

Body:
Your statement is incorrect

string str = "select * from satilikkonutlar where ilanbasligi='" +
comboBox45.Text.Trim() + "'";

You need the ending '

However, you should consider parameter-izing the query.

SqlCommand command = new SqlCommand(
         "select * from satilikkonutlar where ilanbasligi=@value",connection)
command.Parameters.Add(new SqlParameter("value",comboBox45.Text.Trim()));
SqlDataReader reader = command.ExecuteReader();


问:
How to add button to PHP file
my friend asked me to improve his site. He needs to add button to job list post but I don't know how, I am using only HTML/CSS, not PHP.

There is a code:

```<code><?php if( $permalink ) : ?>
            <a href="<?php echo esc_url($permalink);?>"><?php echo $thumbnail_image_output;?></a>
        <?php else:?>
            <?php echo $thumbnail_image_output;?>
        <?php endif;?>
    </div>
</div>
<?php endif;?>

<div class="person_data">

    <?php if( $permalink ) : ?>
        <h5 class="person_name"><a href="<?php echo esc_url($permalink);?>"><?php the_title();?></a></h5>
    <?php else:?>
        <h5 class="person_name"><?php the_title();?></h5>
    <?php endif;?>

    <?php if(! empty( $position )) : ?>
        <span class="position"><?php echo apply_filters( "rtframework_team_position", esc_attr( $position ) );?></span>
    <?php endif;?>

    <?php if(! empty( $short_data )) : ?>
    <div class="profile">
        <?php echo apply_filters( "the_content", $short_data );?>
    </div>
    <?php endif;?>

    <?php do_action("rtframework_staff_media_links",$post->ID); ?>
</div>
</code>```

The question is, how to add button with link to the full post above the "the_content"?

I will be very happy if you show me the way.

Sorry for my English and have nice day :-)

答:
You can choose to wrap the a tag around your div

```<code><a href="<?php echo $permalink ?>">
    <div class="person_data">
        <!-- Other HTML tags -->
    </div>
</a>
</code>```

Having an anchor around a div can be tricky sometimes (especially if you have no experience)

Read about block and inline terms in CSS as well as in HTML.

Here's a good starting point to a SO question.

Title: How to add button to PHP file

Body:
my friend asked me to improve his site. He needs to add button to job list post but I don't know how, I am using only HTML/CSS, not PHP.

There is a code:

<?php if( $permalink ) : ?>
            <a href="<?php echo esc_url($permalink);?>"><?php echo $thumbnail_image_output;?>
        <?php else:?>
            <?php echo $thumbnail_image_output;?>
        <?php endif;?>

<?php endif;?>

    <?php if( $permalink ) : ?>

<a href="<?php echo esc_url($permalink);?>"><?php the_title();?>

    <?php else:?>

<?php the_title();?>

    <?php endif;?>

    <?php if(! empty( $position )) : ?>
        <?php echo apply_filters( "rtframework_team_position", esc_attr( $position ) );?>
    <?php endif;?>

    <?php if(! empty( $short_data )) : ?>

        <?php echo apply_filters( "the_content", $short_data );?>

    <?php endif;?>

    <?php do_action("rtframework_staff_media_links",$post->ID); ?>

The question is, how to add button with link to the full post above the "the_content"?

I will be very happy if you show me the way.

Sorry for my English and have nice day :-)

Body:
You can choose to wrap the a tag around your div

<a href="<?php echo $permalink ?>">
    <div class="person_data">
        <!-- Other HTML tags -->
    </div>
</a>

Having an anchor around a div can be tricky sometimes (especially if you have no experience)

Read about block and inline terms in CSS as well as in HTML.

Here's a good starting point to a SO question.


问:
Scroll UICollectionView to bottom
I would like to scroll the UICollectionView to the bottom so the last item is in the view. I have tried to use scrollToItemAtIndexPath but it does not seem to be working. I want this to happen after I have completed a query with Parse.com

Thanks

```<code>    var query = PFQuery(className:"Chat")
    //        query.whereKey("user", equalTo:currentUser)
    query.whereKey("rideId", equalTo:currentObjectId)
    query.orderByDescending("createdAt")
    query.includeKey("user")

    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {
            // The find succeeded.
            NSLog("Successfully retrieved \(objects.count) scores.")
            // Do something with the found objects
            for object in objects {
                NSLog("%@", object.objectId)

                var testId = object.objectId

                println(testId)

                self.orderedIdArray.append(testId)

                var message = object.objectForKey("message") as String
                self.messageString = message
                self.messageArray.append(self.messageString)
                println(message)

                var nameId = object.objectForKey("user") as PFUser
                var username = nameId.username as String
                self.nameString = username
                self.namesArray.append(self.nameString)

                println("username: \(username)")

                self.collectionView?.reloadData()
            }

        } else {
            // Log details of the failure
            NSLog("Error: %@ %@", error, error.userInfo!)
        }
                    NSLog("Ordered: %@", self.orderedIdArray)
    }
</code>```

答:
You can track top and bottom of your visible view and load next page of items  </p>

```<code>  func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
        print("bottom")
    }

    if (scrollView.contentOffset.y <= 0) {
        print("top")
    }
}
</code>```

Title: Scroll UICollectionView to bottom

Body:
I would like to scroll the UICollectionView to the bottom so the last item is in the view. I have tried to use scrollToItemAtIndexPath but it does not seem to be working. I want this to happen after I have completed a query with Parse.com

Thanks

    var query = PFQuery(className:"Chat")
    //        query.whereKey("user", equalTo:currentUser)
    query.whereKey("rideId", equalTo:currentObjectId)
    query.orderByDescending("createdAt")
    query.includeKey("user")

    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {
            // The find succeeded.
            NSLog("Successfully retrieved \(objects.count) scores.")
            // Do something with the found objects
            for object in objects {
                NSLog("%@", object.objectId)

                var testId = object.objectId

                println(testId)

                self.orderedIdArray.append(testId)

                var message = object.objectForKey("message") as String
                self.messageString = message
                self.messageArray.append(self.messageString)
                println(message)

                var nameId = object.objectForKey("user") as PFUser
                var username = nameId.username as String
                self.nameString = username
                self.namesArray.append(self.nameString)

                println("username: \(username)")

                self.collectionView?.reloadData()
            }

        } else {
            // Log details of the failure
            NSLog("Error: %@ %@", error, error.userInfo!)
        }
                    NSLog("Ordered: %@", self.orderedIdArray)
    }

Body:
You can track top and bottom of your visible view and load next page of items

  func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
        print("bottom")
    }

    if (scrollView.contentOffset.y <= 0) {
        print("top")
    }
}


问:
What is the test credit card number for Converge Payment Api?
I have tried with lot of test credit card number but always get back the result is 'INVALID CARD'.

Request Url:

https://demo.myvirtualmerchant.com/VirtualMerchantDemo/processxml.do

Here is my Sample Xml Request:

```<code>"xmldata=<txn>
<ssl_merchant_ID>******</ssl_merchant_ID>
<ssl_user_id>***</ssl_user_id>
<ssl_pin>******</ssl_pin>
<ssl_transaction_type>ccsale</ssl_transaction_type>
<ssl_card_number>4111111111111111</ssl_card_number>
<ssl_exp_date>0120</ssl_exp_date>
<ssl_amount>7</ssl_amount>
<ssl_cvv2cvc2>123</ssl_cvv2cvc2>
<ssl_avs_address>test</ssl_avs_address>
<ssl_avs_zip>9999</ssl_avs_zip>
<ssl_first_name>test</ssl_first_name>
<ssl_last_name>test</ssl_last_name>
</txn>"
</code>```

My Result:

```<code><txn>
<ssl_approval_code />
<ssl_email />
<ssl_card_short_description>VISA</ssl_card_short_description>
<ssl_cvv2_response />
<ssl_last_name>test</ssl_last_name>
<ssl_avs_zip>9999</ssl_avs_zip>
<ssl_exp_date>0120</ssl_exp_date>
<ssl_account_balance>0.00</ssl_account_balance>
<Additional_Information />
<ssl_result_message>INVALID CARD</ssl_result_message>
<ssl_card_type>CREDITCARD</ssl_card_type>
<ssl_city />
<ssl_phone />
<ssl_avs_address>test</ssl_avs_address>
<ssl_first_name>test</ssl_first_name>
<Customer_Account />
<ssl_amount>7.00</ssl_amount>
<ssl_state />
<ssl_txn_id>230317B39-CA1A68F1-63A9-44C8-9812-88AD8DBA7D37</ssl_txn_id>
<ssl_result>1</ssl_result>
<ssl_card_number>41**********1111</ssl_card_number>
<ssl_txn_time>03/23/2017 12:13:37 AM</ssl_txn_time>
<ssl_avs_response />
<ssl_transaction_type>SALE</ssl_transaction_type>
</txn>
</code>```

In This Example I have tried with 4111111111111111 Visa Card. Please tell me Converge have any other Test number. Thanks in advance!.

答: If you are using production the 4111 visa number will give a decline. To get an approval you should use 5000300020003003 . Be sure to void these test cards as they will actually cause a real batch to fail. If you are using the demo environment call and get a test card number as they change periodically. </p>

Body:
I have tried with lot of test credit card number but always get back the result is 'INVALID CARD'.

Request Url:

https://demo.myvirtualmerchant.com/VirtualMerchantDemo/processxml.do

Here is my Sample Xml Request:

"xmldata=<txn>
<ssl_merchant_ID>******</ssl_merchant_ID>
<ssl_user_id>***</ssl_user_id>
<ssl_pin>******</ssl_pin>
<ssl_transaction_type>ccsale</ssl_transaction_type>
<ssl_card_number>4111111111111111</ssl_card_number>
<ssl_exp_date>0120</ssl_exp_date>
<ssl_amount>7</ssl_amount>
<ssl_cvv2cvc2>123</ssl_cvv2cvc2>
<ssl_avs_address>test</ssl_avs_address>
<ssl_avs_zip>9999</ssl_avs_zip>
<ssl_first_name>test</ssl_first_name>
<ssl_last_name>test</ssl_last_name>
</txn>"

My Result:

<txn>
<ssl_approval_code />
<ssl_email />
<ssl_card_short_description>VISA</ssl_card_short_description>
<ssl_cvv2_response />
<ssl_last_name>test</ssl_last_name>
<ssl_avs_zip>9999</ssl_avs_zip>
<ssl_exp_date>0120</ssl_exp_date>
<ssl_account_balance>0.00</ssl_account_balance>
<Additional_Information />
<ssl_result_message>INVALID CARD</ssl_result_message>
<ssl_card_type>CREDITCARD</ssl_card_type>
<ssl_city />
<ssl_phone />
<ssl_avs_address>test</ssl_avs_address>
<ssl_first_name>test</ssl_first_name>
<Customer_Account />
<ssl_amount>7.00</ssl_amount>
<ssl_state />
<ssl_txn_id>230317B39-CA1A68F1-63A9-44C8-9812-88AD8DBA7D37</ssl_txn_id>
<ssl_result>1</ssl_result>
<ssl_card_number>41**********1111</ssl_card_number>
<ssl_txn_time>03/23/2017 12:13:37 AM</ssl_txn_time>
<ssl_avs_response />
<ssl_transaction_type>SALE</ssl_transaction_type>
</txn>

In This Example I have tried with 4111111111111111 Visa Card. Please tell me Converge have any other Test number. Thanks in advance!.


问:
"ORDER BY" in subquery - not avaliable in MonetDB?
I found that, when using order-by directly, it is ok.

```<code>SELECT t0."D" AS fd,
  SUM(t0."SD") AS top
FROM "mock_table_1" AS t0
GROUP BY t0."D"
ORDER BY top ASC
LIMIT 10
</code>```

but when using it in a subquery, an syntax error is reported.

```<code>SELECT * FROM (
  SELECT t0."D" AS fd,
    SUM(t0."SD") AS top
  FROM "mock_table_1" AS t0
  GROUP BY t0."D"
  ORDER BY top ASC
  LIMIT 10
)
</code>```

here is the error message.

```<code>syntax error, unexpected ORDER, expecting UNION or EXCEPT or INTERSECT or ')' in: "select t0."A" as d0,
</code>```

So, I wonder if monetdb is designed to be like this, or it is a bug?

答:
SQL-conforming DBMSes are not supposed to allow ORDER BY in subqueries, because it contradicts the conceptual model of a relational DBMS. See:

Is order by clause allowed in a subquery

for details. A way around that, however, is to use Window Functions, which MonetDB does support. Specifically, in your subquery, instead of, say,

```<code>SELECT c1 FROM t1;
</code>```

you can

```<code>SELECT c1, ROW_NUMBER() OVER () as rownum from t1;
</code>```

and now you have the relative order of the inner query result available to the outer query.

Body:
I found that, when using order-by directly, it is ok.

SELECT t0."D" AS fd,
  SUM(t0."SD") AS top
FROM "mock_table_1" AS t0
GROUP BY t0."D"
ORDER BY top ASC
LIMIT 10

but when using it in a subquery, an syntax error is reported.

SELECT * FROM (
  SELECT t0."D" AS fd,
    SUM(t0."SD") AS top
  FROM "mock_table_1" AS t0
  GROUP BY t0."D"
  ORDER BY top ASC
  LIMIT 10
)

here is the error message.

syntax error, unexpected ORDER, expecting UNION or EXCEPT or INTERSECT or ')' in: "select t0."A" as d0,

So, I wonder if monetdb is designed to be like this, or it is a bug?

Body:
SQL-conforming DBMSes are not supposed to allow ORDER BY in subqueries, because it contradicts the conceptual model of a relational DBMS. See:

Is order by clause allowed in a subquery

for details. A way around that, however, is to use Window Functions, which MonetDB does support. Specifically, in your subquery, instead of, say,

SELECT c1 FROM t1;

you can

SELECT c1, ROW_NUMBER() OVER () as rownum from t1;

and now you have the relative order of the inner query result available to the outer query.


问:
How to export data from SQL without using the import/export wizard?
I need to export data from SQL to csv or Excel without using the wizard. It must be done through query. I looked a lot online, but could not find a solution. The best solution I found was to use a command code to export the data, but this returns the data without headers. Please help !

Edit:
I am new to SQL, and really been researching this for a while. I therefore would be grateful if you can give me the code to do this in SQL management studio (if possible). Many thanks !!!

答:
Rather than pushing the data out from SQL Management Studio, you could create a connection to the database within Excel and pull the data in.

In Excel, choose Data > From Other Sources > From SQL Server (or Data > New Query > From Database > From SQL Database)

Select the database, database table etc.

If you need to filter or otherwise manipulate the data rather than pull in the whole table, then you can go to the Connection Properties dialog afterwards and enter whatever SQL you want into the Definition tab. For instance select * from
 where <field> = "value".

Body:
Rather than pushing the data out from SQL Management Studio, you could create a connection to the database within Excel and pull the data in.

In Excel, choose Data > From Other Sources > From SQL Server (or Data > New Query > From Database > From SQL Database)

Select the database, database table etc.

If you need to filter or otherwise manipulate the data rather than pull in the whole table, then you can go to the Connection Properties dialog afterwards and enter whatever SQL you want into the Definition tab. For instance select * from <table> where <field> = "value".


问:
Bootstrap 4 tabs break in AngularJS
I found when using bootstrap tab with pills, the:

```<code><a class="nav-link" id="tabItem" data-toggle="pill" href="#tabItem"> example </a>
</code>```

breaks the angular application causing it to navigate back to the page loading the first tab and selecting the first default pill.

I tried adding:

```<code>_target="self"
</code>```

...adding this fixes navigation only for the first four clicks, and then it breaks again. When I inspect the page I see that the 'active' class never gets cleared with this is set.

I also tried adding:

```<code>"dependencies": {
     "angular1-ui-bootstrap4": "2.4.22"
 }
</code>```

via npm, but the amount of work needed to create a layout and modify some of the pre-designed behavior wasn't worth my time.

It was a long path to find a minimal-code, tight solution, but I am posting this question to help others.

答:
I fixed this behavior by adding a custom directive in angular that removes the old active class and shows the tab clicked on:

```<code>//
// when bootstrap adds the # to pills it ruins everything!!
// fix that with this:
//
app.directive('tabFix', function () {
    return function (scope, element, attrs) {
        $(element).click(function (event) {
        $(this).siblings("a").removeClass('active');
        event.preventDefault();
        $(this).tab('show');
        });
    }
});
</code>```

then to call the directive, add tab-fix onto the anchor element:

```<code><a class="nav-link" id="tabItem" data-toggle="pill" href="#tabItem" tab-fix> example </a>
</code>```

It fixes everything!

ContentLicense: CC BY-SA 4.0

Title: Bootstrap 4 tabs break in AngularJS

Body:
I found when using bootstrap tab with pills, the:

 example

breaks the angular application causing it to navigate back to the page loading the first tab and selecting the first default pill.

I tried adding:

_target="self"

...adding this fixes navigation only for the first four clicks, and then it breaks again. When I inspect the page I see that the 'active' class never gets cleared with this is set.

I also tried adding:

"dependencies": {
     "angular1-ui-bootstrap4": "2.4.22"
 }

via npm, but the amount of work needed to create a layout and modify some of the pre-designed behavior wasn't worth my time.

It was a long path to find a minimal-code, tight solution, but I am posting this question to help others.

Body:
I fixed this behavior by adding a custom directive in angular that removes the old active class and shows the tab clicked on:

//
// when bootstrap adds the # to pills it ruins everything!!
// fix that with this:
//
app.directive('tabFix', function () {
    return function (scope, element, attrs) {
        $(element).click(function (event) {
        $(this).siblings("a").removeClass('active');
        event.preventDefault();
        $(this).tab('show');
        });
    }
});

then to call the directive, add tab-fix onto the anchor element:

<a class="nav-link" id="tabItem" data-toggle="pill" href="#tabItem" tab-fix> example </a>

It fixes everything!


问:
Learning Clojure coming from Lisp
I'm thinking seriously of making Clojure my new hacking language since I love Lisp but have some problems with CL and Scheme. I've never worked in the Java environment before and my lisp experience is limited to working through "SICP" and "The Little Schemer."

What do I need to know? Are there any good resources on "The Clojure way?" Any resources on Clojure style? I've found Mark Volkmann's excellent page, but the books I've looked through seem a little spare.

Also, what do I need to know about Java? I'd rather not learn Java just to learn Clojure, but I imagine I'll have to know at least a little. Also, what is the workflow like? My experience is limited to dynamic languages, so I have no idea what I'd have to do to distribute an application without source on the JVM.

I've googled this obviously, but there's a large amount of information and not very much "clojure specific" stuff.

I guess I'm looking for some sensible suggestions on the kind of literature I should read in some sort of logical sequence.

答:
You can't go wrong watching as many of the Clojure videos on Blip.tv as you can handle, especially those by Rich Hickey himself. These really help drive home the conceptual points and aspects unique to Clojure.

If you are sufficiently familiar with Lisp concepts, you may want to initially focus on learning how Clojure "maps" to the Lisps you've played with. Watch the videos by Rich Hickey on "Clojure for Lisp Programmers."

You do need to have some familiarity with Java, because Clojure doesn't shy away from using it. It's not somehow un-Clojurey (as far as I can tell) to use Java where it's smart. I'd at least skim through the API docs for the java.lang and java.io packages, because java.lang is automatically available within your Clojure programs and java.io is used frequently.

With my Clojure-to-Lisp dictionary in my head and my Java basics behind me, I'd pick a small project to work on. Keep the Clojure and Clojure-contrib API docs handy (either on the web or use the (doc) command from the REPL), and peruse the many, many Clojure blogs out there. Two of my favorites are http://nakkaya.com/ and http://stuartsierra.com/. If you use Diigo, a whole slew of blogs have been bookmarked to the clojure group.

NOTE: don't get hung up on your dev environment. There are a multitude of options listed on the Getting Started wiki page. For learning Clojure and your first small projects, I'd just pick your plain text editor of choice, learn and use the basics of Leiningen to get a nice project directory setup with all your paths and dependencies taken care of, then use the command "lein repl" to startup a REPL with all of your dependencies loaded and available. In assuming you use Emacs (based on your previous Lisp experience), you can describe-variable your inferior-lisp-program to be lein repl, and just start Emacs from the root of your example project for everything to work automagically.

There are books you can read, notably The Joy of Clojure, Programming Clojure and Practical Clojure. The latter two are more "practical" than the first, which is more "philosophical" (excuse the gross generalizations). Practical Clojure is up-to-date with Clojure 1.2, whereas Programming Clojure is a little bit older.

Finally, get on the #clojure IRC channel and use the Clojure Google group, because there's a bunch of smart, friendly folk who enjoy helping others.

ContentLicense: CC BY-SA 2.5

Title: Learning Clojure coming from Lisp


问:
Take a quote, and show how many characters, words, and average of each word
I am kinda new to Java, please do not tell me to use methods, etc. because I do not know how to do them. But I do know some charAt things, so can anyone help me find the amount of words, and avg of each word, i did the first part. Here is my code.</p>

```<code>import java.util.Scanner;
public class FavouriteQuote {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String sQuote;
        int counter = 0;

        Scanner input = new Scanner (System.in);
        System.out.print("Enter one of your favourite quotes: ");
        sQuote = input.nextLine();
        input.close();

        for (int i = 0; i < sQuote.length(); i ++) {
            counter ++;
        }
        System.out.println(counter);
    }

}
</code>```

答:
But what average do you need? average word length in quote?
 then your code may look like:

```<code>    ...
    input.close();

    System.out.println("Characters in quote:" + sQuote.length());

    String[] words = sQuote.split("\\s");
    // or
    // String[] words = sQuote.split(" ");

    System.out.println("words in quote:" + words.length);

    int totalWordsLength =0;
    for (String word: words)
    {
        totalWordsLength = totalWordsLength + word.length();
    }
//or with loop counter
//      for (int i=0; i < words.length; i++)
//      {
//          totalWordsLength += words[i].length();
//      }

    System.out.println("average word length in quote:" + (totalWordsLength/ words.length));
</code>```

Keep in mind: here average is int so it will be only integer portion of divide result. i.e. 11/3 = 3
BTW (aside of question) - You do not need your for loop. It does not make any sense.
counter = sQuote.length() does the same.

Body:
I am kinda new to Java, please do not tell me to use methods, etc. because I do not know how to do them. But I do know some charAt things, so can anyone help me find the amount of words, and avg of each word, i did the first part. Here is my code.

import java.util.Scanner;
public class FavouriteQuote {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String sQuote;
        int counter = 0;

        Scanner input = new Scanner (System.in);
        System.out.print("Enter one of your favourite quotes: ");
        sQuote = input.nextLine();
        input.close();

        for (int i = 0; i < sQuote.length(); i ++) {
            counter ++;
        }
        System.out.println(counter);
    }

}

Body:
But what average do you need? average word length in quote?
 then your code may look like:

    ...
    input.close();

    System.out.println("Characters in quote:" + sQuote.length());

    String[] words = sQuote.split("\\s");
    // or
    // String[] words = sQuote.split(" ");

    System.out.println("words in quote:" + words.length);

    int totalWordsLength =0;
    for (String word: words)
    {
        totalWordsLength = totalWordsLength + word.length();
    }
//or with loop counter
//      for (int i=0; i < words.length; i++)
//      {
//          totalWordsLength += words[i].length();
//      }

    System.out.println("average word length in quote:" + (totalWordsLength/ words.length));

Keep in mind: here average is int so it will be only integer portion of divide result. i.e. 11/3 = 3
BTW (aside of question) - You do not need your for loop. It does not make any sense.
counter = sQuote.length() does the same.


问:
Laravel: Whats the difference between these two route api approach
This

```<code>Route::middleware(['cors'])->group(function () {

    Route::post('/login', 'AuthController@APIstore');

    Route::middleware(['auth:api'])->group(function () {

        Route::post('/logout', 'AuthController@APIdestroy');

        Route::get('/projects', 'ProjectController@getAll');

    });

});
</code>```

And this

```<code>Route::group(['middleware' => 'cors'], function() {

    Route::post('/login', 'AuthController@APIstore');

    Route::group(['middleware' => 'auth:api'], function() {

        Route::post('/logout', 'AuthController@APIdestroy');

        Route::get('/projects', 'ProjectController@getAll');

    });

});
</code>```

On the first code, CORS middleware works with /login but does not work for /logout and /projects

On the second code, the CORS middleware does not work at all

is there a reason behind this?

答:
So, as per the Laravel Routing Doc, the top level middleware is applied to all groups in the group. So using Route::middleware(['cors']) will mean this middleware will be applied to Route::middleware(['auth:api']).

However Route::group(['middleware' => 'cors'] is a group route not a middleware route, so the middle is not applied to child groups.

Body:
This

Route::middleware(['cors'])->group(function () {

    Route::post('/login', 'AuthController@APIstore');

    Route::middleware(['auth:api'])->group(function () {

        Route::post('/logout', 'AuthController@APIdestroy');

        Route::get('/projects', 'ProjectController@getAll');

    });

});

And this

Route::group(['middleware' => 'cors'], function() {

    Route::post('/login', 'AuthController@APIstore');

    Route::group(['middleware' => 'auth:api'], function() {

        Route::post('/logout', 'AuthController@APIdestroy');

        Route::get('/projects', 'ProjectController@getAll');

    });

});

On the first code, CORS middleware works with /login but does not work for /logout and /projects

On the second code, the CORS middleware does not work at all

is there a reason behind this?


问:
How to make data accessible to a React Component when data exists outside of states scope
. .

I am currently using React VR for a school project, but incorporating vanilla javascript into the index.html to create a static HTML UI. In this case I am using an HTML5 form to post data to my back end, yet still, I would like to optimistically render the data using a React component rather than have to retrieve the data from the server.

My data is created in the HTML element, and it needs to make its way into a React Component.

I don't think refs will work, as the research I have done shows that they are for accessing data which is being generated by a React component, and in my case, I am looking for the data to flow from the HTML to the React Component.

```<code>    ~ JAVASCRIPT & HTML ~

     //Accepts the Input
        <form id='idea-form'>
          <input type="text" id="hiddenInput" maxlength=95 autocomplete=off>
        </form>

          // Initialize the React VR application.
        ReactVR.init(
         '../index.vr.bundle?platform=vr&dev=true',
          document.body
        );
</code>```

I've included my component here, minus imports and exports.

The component maps an array of strings, converts them to JSX, then renders  components with the array elements as the text props for the component.

In my case,

```<code>//========== IdeaContainer Component ==========
class IdeaContainer extends Component {

  //---------- Other Methods ----------
  mapIdeasContentToJSX(ideasObjArr) {
    newIdeas = [...ideasObjArr]enter code here
    ideasJSX = newIdeas.map((idea) => {return (<IdeaText
      text={idea.content}
      y={Math.random() * 30}
      z={Math.random() * -80}
    />)})
    return ideasJSX
  }

  //---------- Lifecycle Methods ----------
  componentDidMount(){
    this.props.preLoadIdeas()
  }

  render(){

    return(
      <View>
        {this.mapIdeasContentToJSX(this.props.ideaList)}
      </View>
    )
  }
}
</code>```

This is the code which lives in the index.html, which exists outside the scope of my React components, meaning I cannot pass it as props or set it to state, as far as I know.

The element with id of 'container' is where the data is being entered, which then needs to make its way to the React Component

```<code><div>
  <div id='logoDIV'class="relative" >
  <img id='logoIMG' src='./logo.png' draggable="false">
  </div>
</div>
<div id="container" style='position: fixed; z-index: 2; bottom: 1%; right: 22%;'>
    <div id="input"></div>
      <form id='idea-form'>
        <input type="text" id="hiddenInput" maxlength=95 autocomplete=off>
      </form>
</div>
      <canvas id="cloudCover"></canvas>
<!-- When you're ready to deploy your app, update this line to point to your compiled client.bundle.js -->
<script src="./client.bundle?platform=vr"></script>
<script src="./input.js"></script>
<script src='./clouds.js'></script>
<script>
  ReactVR.init(
    // When you're ready to deploy your app, update this line to point to
    // your compiled index.bundle.js
    '../index.vr.bundle?platform=vr&dev=true',
    document.body
  );
</script>
<script>
  let x = document.body.querySelector('body > div:nth-child(8) > div > a:nth-child(2)')
  x.style.bottom = '100px'
</script>
</code>```

答:
You are looking for refs.

```<code><input
   type="text"
   id="hiddenInput"
   maxlength=95
   autocomplete=off
   ref={(input) => { this.textInput = input; }} />
</code>```

Then you can access the input value like this:

```<code>this.textInput.value
</code>```

https://reactjs.org/docs/refs-and-the-dom.html

Body:
. .

I am currently using React VR for a school project, but incorporating vanilla javascript into the index.html to create a static HTML UI. In this case I am using an HTML5 form to post data to my back end, yet still, I would like to optimistically render the data using a React component rather than have to retrieve the data from the server.

My data is created in the HTML element, and it needs to make its way into a React Component.

I don't think refs will work, as the research I have done shows that they are for accessing data which is being generated by a React component, and in my case, I am looking for the data to flow from the HTML to the React Component.

    ~ JAVASCRIPT & HTML ~

     //Accepts the Input
        <form id='idea-form'>
          <input type="text" id="hiddenInput" maxlength=95 autocomplete=off>
        </form>

          // Initialize the React VR application.
        ReactVR.init(
         '../index.vr.bundle?platform=vr&dev=true',
          document.body
        );

I've included my component here, minus imports and exports.

The component maps an array of strings, converts them to JSX, then renders  components with the array elements as the text props for the component.

In my case,

//========== IdeaContainer Component ==========
class IdeaContainer extends Component {

  //---------- Other Methods ----------
  mapIdeasContentToJSX(ideasObjArr) {
    newIdeas = [...ideasObjArr]enter code here
    ideasJSX = newIdeas.map((idea) => {return (<IdeaText
      text={idea.content}
      y={Math.random() * 30}
      z={Math.random() * -80}
    />)})
    return ideasJSX
  }

  //---------- Lifecycle Methods ----------
  componentDidMount(){
    this.props.preLoadIdeas()
  }

  render(){

    return(
      <View>
        {this.mapIdeasContentToJSX(this.props.ideaList)}
      </View>
    )
  }
}

This is the code which lives in the index.html, which exists outside the scope of my React components, meaning I cannot pass it as props or set it to state, as far as I know.

The element with id of 'container' is where the data is being entered, which then needs to make its way to the React Component

      <form id='idea-form'>
        <input type="text" id="hiddenInput" maxlength=95 autocomplete=off>
      </form>

      <canvas id="cloudCover"></canvas>

Body:
You are looking for refs.

<input
   type="text"
   id="hiddenInput"
   maxlength=95
   autocomplete=off
   ref={(input) => { this.textInput = input; }} />

Then you can access the input value like this:

this.textInput.value

https://reactjs.org/docs/refs-and-the-dom.html


问:
Create a popup inside chrome extension
I need to have a small div like a popup
on my chrome extension.
This div needs to have a simple animation and not to have menu bar at all.
Is it possible to do it with chrome.windows.create
Method ? Is there another way to do it ?
What I need is similar to pocket's extension popup.
https://chrome.google.com/webstore/detail/save-to-pocket/niloccemoadcdkdjlinkgdfekeahmflj?hl=en</p>

答: You need to use content scripts. If you have made a trigger the content script is able to change the page. By using that to your advantage you can add a div filled with all of the html you want to add. You can find a in depth example here.</p>

Title: Create a popup inside chrome extension


Title: Calculate distance based on a lookup dataframe

Body:
I have a DataFrame and a lookup table. For a key in the DataFrame I would like to lookup the corresponding row in the lookup table and calculate the Euclidian distance for a number of columns. Mock data looks like

import pandas as pd
import numpy.random as rand

df = pd.DataFrame({'key':rand.randint(0, 5, 10),
                    'X': rand.randn(10),
                    'Y': rand.randn(10),
                    'Z': rand.randn(10)})

          X         Y         Z  key
0  0.163142  0.387871 -0.433157    3
1 -2.020957 -1.537615 -1.996704    0
2  1.249118  1.633246  0.028222    1
3 -0.019601  1.757136  0.787936    2
4 -0.039649  1.380557  0.123677    0
5  0.500814 -1.049591 -1.261868    3
6  1.175576 -0.310895  0.549420    0
7 -0.152696  0.139020  0.887219    2
8  0.491099  0.434652  0.791038    2
9 -0.231334  0.264414  0.913475    4

lookup = pd.DataFrame({'X': rand.randn(5),
                    'Y': rand.randn(5),
                    'Z': rand.randn(5)})

          X         Y         Z
0  0.242419 -0.630230 -0.254344
1  0.799573  0.354169  1.099456
2 -0.754582 -1.882192 -1.270382
3 -1.645707 -0.131905 -0.445954
4  0.743351  0.456220  0.975457
5  0.136197  0.278329 -2.336110

For example, the zeroth column has values

df.loc[0,'X':'Z'].values
[0.163142,0.387871,-0.433157]

the key is 3 so the row in the lookup is

lookup.iloc[3,:].values
[-1.645707 -0.131905 -0.445954]

The distance is

import numpy as np
np.linalg.norm(np.array([0.163142,0.387871,-0.433157]) - np.array([-0.754582, -1.882192, -1.270382]))
2.5877304853423202

I would like to do this for every row in df and return the value as a new column. Is there a slick way to do this?

Body:
Vectorized approach:

In [88]: (df.merge(lookup, left_on='key', right_index=True, suffixes=['1','2'])
    ...:    .eval("sqrt((X1-X2)**2 + (Y1-Y2)**2 + (Z1-Z2)**2)"))
    ...:
Out[88]:
0    1.041056
5    2.381120
1    2.832168
4    1.549664
6    1.725080
2    2.593081
3    3.096872
7    2.211651
8    1.800886
9    2.976105
dtype: float64


问:
Grant read to Elasticache on S3 object with boto3
I have a script that uploads a file to S3 then starts an Elasticache server seeded with the file. Elasticache documentation says to provide read and read permission permissions to 540804c33a284a299d2547575ce1010f2312ef3da9b3a053c8bc45bf233e4353 which represents the canonical ID for any region that's not GovCloud or China.

Here is my code:

```<code>import boto3
s3_cl = boto3.client('s3')
s3_cl.put_object_acl(Bucket='bucket-name', Key='file.rdb', GrantRead='540804c33a284a299d2547575ce1010f2312ef3da9b3a053c8bc45bf233e4353')
</code>```

Here is the error I get:

```<code>ClientError: An error occurred (InvalidArgument) when calling the PutObjectAcl operation: Argument format not recognized
</code>```

What parameter am I supposed to provide to GrantRead? My understanding was that it's a grantee, which can be a canonical ID, so what am I doing wrong?

答:
I believe that you should provide grantees in one of the following formats:

id=<canonical user ID of the grantee>

email=<email address of the grantee>

uri=<URI of the grantee group>

displayname=<screen name of the grantee>

type=<type of grantee>

I inferred this information from the awscli put-object-acl documentation.

Body:
I have a script that uploads a file to S3 then starts an Elasticache server seeded with the file. Elasticache documentation says to provide read and read permission permissions to 540804c33a284a299d2547575ce1010f2312ef3da9b3a053c8bc45bf233e4353 which represents the canonical ID for any region that's not GovCloud or China.

Here is my code:

import boto3
s3_cl = boto3.client('s3')
s3_cl.put_object_acl(Bucket='bucket-name', Key='file.rdb', GrantRead='540804c33a284a299d2547575ce1010f2312ef3da9b3a053c8bc45bf233e4353')

Here is the error I get:

ClientError: An error occurred (InvalidArgument) when calling the PutObjectAcl operation: Argument format not recognized

What parameter am I supposed to provide to GrantRead? My understanding was that it's a grantee, which can be a canonical ID, so what am I doing wrong?


问:
Is it better for performance to dynamically change transition in JS directly, or using css classes instead?
I have two elements that do a simple intro animation when scrolling. And I want to reverse the transition speed when going back.

Both these approaches work, but the site is kinda laggy so I was wondering which one is better for performance. Doing it in javascript like this..

```<code>function startAnimation(){
   elem1.classList.add('transformClass');
   elem2.classList.add('transformClass');

   elem1.style.transition = 'transform 0.6s';
   elem2.style.transition = 'transform 1.4s';
}

function exitAnimation(){
   elem1.classList.remove('transformClass');
   elem2.classList.remove('transformClass');

   elem1.style.transition = 'transform 1.4s'; //elem1 is now 1.4s instead of 0.6s
   elem2.style.transition = 'transform 0.6s';
}
</code>```

or would it better to incorporate the transition into the added classes and using !important

```<code>function startAnimation(){
   elem1.classList.add('transformClass1');
   elem2.classList.add('transformClass2');
}

function exitAnimation(){
   elem1.classList.remove('transformClass1');
   elem2.classList.remove('transformClass2');
}

//CSS:

#elem1 {
   transition: transform 0.6s
}

#elem2 {
   transition: transform 1.4s
}

.transformClass1 {
   transition: transform 1.4s !important;
}

.transformClass2 {
   transition: transform 0.6s !important;
}
</code>```

答:
There're some conditions in this test that I've done with your code.

There's no HTML codes given to me - I had to make my own HTML codes, which means, this result might not be the one from the same source.

The website I've used to test JavaScript codes does not support to make an external CSS file, which means, I had to put  tag with HTML, so it might be different from adding an external CSS file.

The number of executing each codes is about 3,000.

[Related to #2] Since I had to put  in HTML, that means, the codes that is consist of only JavaScript couldn't be run with the codes consist of JavaScript and CSS, together, because as I mentioned

Body:
I have two elements that do a simple intro animation when scrolling. And I want to reverse the transition speed when going back.

Both these approaches work, but the site is kinda laggy so I was wondering which one is better for performance. Doing it in javascript like this..

function startAnimation(){
   elem1.classList.add('transformClass');
   elem2.classList.add('transformClass');

   elem1.style.transition = 'transform 0.6s';
   elem2.style.transition = 'transform 1.4s';
}

function exitAnimation(){
   elem1.classList.remove('transformClass');
   elem2.classList.remove('transformClass');

   elem1.style.transition = 'transform 1.4s'; //elem1 is now 1.4s instead of 0.6s
   elem2.style.transition = 'transform 0.6s';
}

or would it better to incorporate the transition into the added classes and using !important

function startAnimation(){
   elem1.classList.add('transformClass1');
   elem2.classList.add('transformClass2');
}

function exitAnimation(){
   elem1.classList.remove('transformClass1');
   elem2.classList.remove('transformClass2');
}

//CSS:

#elem1 {
   transition: transform 0.6s
}

#elem2 {
   transition: transform 1.4s
}

.transformClass1 {
   transition: transform 1.4s !important;
}

.transformClass2 {
   transition: transform 0.6s !important;
}

Body:
There're some conditions in this test that I've done with your code.

There's no HTML codes given to me - I had to make my own HTML codes, which means, this result might not be the one from the same source.

The website I've used to test JavaScript codes does not support to make an external CSS file, which means, I had to put <style></style> tag with HTML, so it might be different from adding an external CSS file.

The number of executing each codes is about 3,000.

[Related to #2] Since I had to put <style></style> in HTML, that means, the codes that is consist of only JavaScript couldn't be run with the codes consist of JavaScript and CSS, together, because as I mentioned <style> tag, it affects both. So I had to run them separately.

Here's HTML I made:

<div id="elem1"></div>
<div id="elem2"></div>
<div class="transformClass1"></div>
<div class="transformClass2"></div>

And here's the result I've got:

Gray - Only JavaScript

Green - JavaScript + CSS

Lower is better

※ Website I've used - http://jindo.dev.naver.com/jsMatch

made by Naver, from South Korea


问:
CFEclipse and Eclipse PDT coexisting?
Is it possible to have Eclipse PDT and CFEclipse installed on the same machine? Seems that PDT gets overwritten when I install CFEclipse on OSX.</p>

答: I tried to have them both installed, but it messed up my perspectives and config settings. I suppose I'll have to use Dreamweaver unless there is another way to have this work (not buying CFBuilder).</p>

Title: CFEclipse and Eclipse PDT coexisting?


问:
Circe - Use default fields in case class when decoding/encoding json
Lets say I have this case class:

case class Foo(bar: String, baz: Boolean = false)

which is used in when decoding/encoding API requests/responses using akka-http-json

in an example similar to this:

```<code>import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives
import akka.stream.{ ActorMaterializer, Materializer }
import scala.io.StdIn

object ExampleApp {

  private final case class Foo(bar: String, baz: Boolean = false)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    implicit val mat    = ActorMaterializer()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    system.terminate()
  }

  private def route(implicit mat: Materializer) = {
    import Directives._
    import FailFastCirceSupport._
    import io.circe.generic.auto._

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    }
  }
}
</code>```

This works fine as long as the json message includes the baz field. However, I want to be able to send a json message {bar: "something"} and let the result use Foo's default value for baz. Is there any configuration in circe or akka-http-json that could make this work?

Also, would be nice to ignore the baz field when encoding to json again, but this is not that important.

Edit:

I know I can do something like this:

```<code>implicit val fooEncoder: Encoder[Foo] = new Encoder[Foo] {
    final def apply(a: Foo): Json = Json.obj(
      ("id", Json.fromString(a.bar))
    )
  }

implicit val fooDecoder: Decoder[Foo] = new Decoder[Decoder] {
  final def apply(c: HCursor): Decoder.Result[Decoder] =
    for {
      bar <- c.downField("bar").as[String]
    } yield {
      Foo(bar)
    }
}
</code>```

but was hoping for an easier-to-maintain solution, solving the general case of not requiring the default fields in the json message.

答:
You can do this using the circe-generic-extras package.  It's a separate dependency you have to put in your build.  For sbt, that's:

```<code>libraryDependencies += "io.circe" %% "circe-generic-extras" % "0.8.0"
</code>```

Then, in your route function, replace

```<code>import io.circe.generic.extras.Configuration
import io.circe.generic.auto._
</code>```

with:

```<code>import io.circe.generic.extras.auto._
implicit val customConfig: Configuration = Configuration.default.withDefaults
</code>```

The encoders this generates will always include the default fields.

For more info see the circe release notes at: https://github.com/circe/circe/releases/tag/v0.6.0-RC1

Body:
Lets say I have this case class:

case class Foo(bar: String, baz: Boolean = false)

which is used in when decoding/encoding API requests/responses using akka-http-json

in an example similar to this:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives
import akka.stream.{ ActorMaterializer, Materializer }
import scala.io.StdIn

object ExampleApp {

  private final case class Foo(bar: String, baz: Boolean = false)

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    implicit val mat    = ActorMaterializer()

    Http().bindAndHandle(route, "127.0.0.1", 8000)

    StdIn.readLine("Hit ENTER to exit")
    system.terminate()
  }

  private def route(implicit mat: Materializer) = {
    import Directives._
    import FailFastCirceSupport._
    import io.circe.generic.auto._

    pathSingleSlash {
      post {
        entity(as[Foo]) { foo =>
          complete {
            foo
          }
        }
      }
    }
  }
}

This works fine as long as the json message includes the baz field. However, I want to be able to send a json message {bar: "something"} and let the result use Foo's default value for baz. Is there any configuration in circe or akka-http-json that could make this work?

Also, would be nice to ignore the baz field when encoding to json again, but this is not that important.

Edit:

I know I can do something like this:

implicit val fooEncoder: Encoder[Foo] = new Encoder[Foo] {
    final def apply(a: Foo): Json = Json.obj(
      ("id", Json.fromString(a.bar))
    )
  }

implicit val fooDecoder: Decoder[Foo] = new Decoder[Decoder] {
  final def apply(c: HCursor): Decoder.Result[Decoder] =
    for {
      bar <- c.downField("bar").as[String]
    } yield {
      Foo(bar)
    }
}

but was hoping for an easier-to-maintain solution, solving the general case of not requiring the default fields in the json message.

Body:
You can do this using the circe-generic-extras package.  It's a separate dependency you have to put in your build.  For sbt, that's:

libraryDependencies += "io.circe" %% "circe-generic-extras" % "0.8.0"

Then, in your route function, replace

import io.circe.generic.extras.Configuration
import io.circe.generic.auto._

with:

import io.circe.generic.extras.auto._
implicit val customConfig: Configuration = Configuration.default.withDefaults

The encoders this generates will always include the default fields.

For more info see the circe release notes at: https://github.com/circe/circe/releases/tag/v0.6.0-RC1


问:
Verify Elavon Converge payment gateway Api credential in php
I am using Elavon Converge payment gateway.

I want to verify the merchant account credential (like merchant_id, user_id, pin) before submit the card details.

Here is my code :

```<code>$url = 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/process.do';
$fields = array(
'ssl_merchant_id'=>'XXXXXXXX',
'ssl_user_id'=>'XXXX',
'ssl_pin'=>'XXXXXXX',
'ssl_first_name'=>'Heapdrip',
'ssl_last_name'=>'Heap',
'ssl_show_form'=>'false',
'ssl_result_format'=>'html',
'ssl_test_mode'=>'false',
'ssl_receipt_apprvl_method'=>'redg',
'ssl_receipt_decl_method'=>'REDG',
'ssl_receipt_decl_get_url'=>'RETURN URL AFTER PAYMENT DECLINED',
'ssl_error_url'=>'RETURN URL AFTER PAYMENT ERROR',
'ssl_receipt_apprvl_get_url'=>'RETURN URL AFTER PAYMENT APPROVAL',
'ssl_transaction_type'=>'ccsale',
'ssl_amount'=>'5000',
'ssl_card_number'=>'xxxxxxxxxxxxxxx',
'ssl_exp_date'=>'122022',
'ssl_cvv2cvc2_indicator'=>1,
'ssl_cvv2cvc2'=>123
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
curl_close($ch);
</code>```

This is direct payment method but I want to check the merchant_id, user_id and pin are correct or not.

答: If you post to the process.do url and the payment form comes up then the credentials are validated as the form does not pull if they don't. </p>

Body:
I am using Elavon Converge payment gateway.

I want to verify the merchant account credential (like merchant_id, user_id, pin) before submit the card details.

Here is my code :

$url = 'https://demo.myvirtualmerchant.com/VirtualMerchantDemo/process.do';
$fields = array(
'ssl_merchant_id'=>'XXXXXXXX',
'ssl_user_id'=>'XXXX',
'ssl_pin'=>'XXXXXXX',
'ssl_first_name'=>'Heapdrip',
'ssl_last_name'=>'Heap',
'ssl_show_form'=>'false',
'ssl_result_format'=>'html',
'ssl_test_mode'=>'false',
'ssl_receipt_apprvl_method'=>'redg',
'ssl_receipt_decl_method'=>'REDG',
'ssl_receipt_decl_get_url'=>'RETURN URL AFTER PAYMENT DECLINED',
'ssl_error_url'=>'RETURN URL AFTER PAYMENT ERROR',
'ssl_receipt_apprvl_get_url'=>'RETURN URL AFTER PAYMENT APPROVAL',
'ssl_transaction_type'=>'ccsale',
'ssl_amount'=>'5000',
'ssl_card_number'=>'xxxxxxxxxxxxxxx',
'ssl_exp_date'=>'122022',
'ssl_cvv2cvc2_indicator'=>1,
'ssl_cvv2cvc2'=>123
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
curl_close($ch);

This is direct payment method but I want to check the merchant_id, user_id and pin are correct or not.


问:
Executing dynamic Java code over JSR-223
I have been executing dynamic code in my application over JSR-223 for a while now. The basics logic is:

```<code>ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(engineName);
final CompiledScript compiled = ((Compilable) scriptEngine).compile(script);
Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("key", value);
compiled.eval(bindings);
</code>```

This works great for Nashorn and Groovy scripting engines. However it would be great if extending the logic of the application would not require knowing the syntax and tricks of another language - the base code is in Java after all.

When listing the built-in engines there do not seem to be any present for Java:

```<code>ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factoryList = manager.getEngineFactories();
for (ScriptEngineFactory factory : factoryList) {
    log.debug(factory.getLanguageName());
}
</code>```

I have found a few dynamic Java libraries but they do not seem to be maintained any more. I guess it is possible to write something together using the javax.tools.JavaCompiler but I am hoping that maybe I am missing something basic and there are working options for such a thing already in existence. I am also aware of the basics about jshell coming in Java 9 but I have not heard anything about it allowing code execution using the ScriptEngineManager.

How should I go about implementing scripting using the Java language itself? Are there any options beyond starting to implement my own javax.script.ScriptEngine with the help of javax.tools.JavaCompiler?

答:
Check out the SciJava Java Scripting plugin

Docs are a bit thin. See the Maven Repository and note that the resolver is the ImageJ Releases repository (http://maven.imagej.net/content/repositories/releases/)

Body:
I have been executing dynamic code in my application over JSR-223 for a while now. The basics logic is:

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(engineName);
final CompiledScript compiled = ((Compilable) scriptEngine).compile(script);
Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("key", value);
compiled.eval(bindings);

This works great for Nashorn and Groovy scripting engines. However it would be great if extending the logic of the application would not require knowing the syntax and tricks of another language - the base code is in Java after all.

When listing the built-in engines there do not seem to be any present for Java:

ScriptEngineManager manager = new ScriptEngineManager();
List


问:
BackgroundWorker component in services
I know the BackgroundWorker should not be used in Windows Services but would anyone have a good online reference explaining why?</p>

答:
Well, it's okayish to use a BGW in a service, it just doesn't do anything especially useful.  Its reason for being is its ability to raise the ProgressChanged and RunWorkerCompleted events on a specific thread.  Getting code to run on a specific thread is a very non-trivial thing to do.  You cannot simply inject a call into the thread while it is executing code.  That causes horrible re-entrancy problems.  The thread has to be 'idle', in a state where inject code doesn't cause trouble.

Having a thread in an idle state is a fairly unnatural condition.  You use threads to run code, not for them to be idly spinning its heels.  This is however the way a UI thread works.  It spends 99% of its time in the message loop, waiting for Windows to tell it to do something.  A button click, a paint request, a keyboard press, that sort of thing.  While it is inside the message loop, it is in fact idle.  A very good time to execute injected code.

Which is what Winforms' Control.Begin/Invoke and WPF's Dispatcher.Begin/Invoke do.  They put a delegate in a queue, the queue is emptied and the delegate targets executed by the message loop.  The WindowsFormsSynchronizationContext and DispatcherSynchronizationContext classes are the synchronization providers that uses them.  Winforms and WPF replace SynchronizationContext.Current with an instance of them.  Which in turn gets used by BGW to raise the events.  Which makes them run on the UI thread.  Which allows you to update the non thread-safe user interface components from a worker thread.

You can probably see where this is heading, a service uses neither.  The default synchronization provider doesn't synchronize anything.  It simply uses a threadpool thread to call the Send or Post callback.  Which is what will happen when you use BGW in a service.  Now there is actually no point at all in having these events.  You might as well let the DoWork handler call the event handling methods directly.  After all, the thread on which DoWork runs is just another threadpool thread as well.

Well, no real harm done, other than making it quite a bit slower.

Title: BackgroundWorker component in services


问:
Elasticsearch, HOW to make phrase suggester return the exact suggestion?
I am using elasticsearch 5.5.2

I am trying phrase suggester and NOT able to configure it to return the exact suggestion that is in the index already. My index settings, type mappings and phrase suggest query are given below. Please help.

My index settings and type mappings are

```<code>PUT test
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "trigram_analyzer": {
            "type": "custom",
            "tokenizer": "standard",
            "filter": ["shingle"]
          }
        },
        "filter": {
          "shingle": {
            "type": "shingle",
            "min_shingle_size": 2,
            "max_shingle_size": 3
          }
        }
      }
    }
  },
  "mappings": {
    "test": {
      "properties": {
        "title": {
          "type": "text",
          "fields": {
            "trigram": {
              "type": "text",
              "analyzer": "trigram_analyzer"
            }
          }
        }
      }
    }
  }
}
</code>```

Indexed document using

```<code>POST test/test?refresh=true
{"title": "noble prize"}
</code>```

The phrase suggester I am using

```<code>POST test/_search
{
  "suggest": {
    "text": "nobe priz",
    "simple_phrase": {
      "phrase": {
        "field": "title.trigram",
        "size": 1,
        "gram_size": 3,
        "direct_generator": [ {
          "field": "title.trigram",
          "suggest_mode": "always"
        } ],
        "highlight": {
          "pre_tag": "<em>",
          "post_tag": "</em>"
        }
      }
    }
  }
}
</code>```

The result I am getting is

```<code>"suggest": {
    "simple_phrase": [
      {
        "text": "nobe priz",
        "offset": 0,
        "length": 9,
        "options": [
          {
            "text": "noble priz",
            "highlighted": "<em>noble</em> priz",
            "score": 0.09049256
          }
        ]
      }
    ]
  }
</code>```

My question is, for the search text - 'nobe priz' - why I am NOT getting 'noble prize' as the suggestion. Instead why I am just getting 'noble priz'?

If we see, 'noble prize' is the document I have saved.

And if I increase the value of size to '2', then also I am NOT getting 'noble prize' as one of the suggestions.

With size as 2, for the search text 'nobe priz' I am getting the below response

```<code>"suggest": {
    "simple_phrase": [
      {
        "text": "nobe priz",
        "offset": 0,
        "length": 9,
        "options": [
          {
            "text": "noble priz",
            "highlighted": "<em>nobel</em> priz",
            "score": 0.09049256
          },
          {
            "text": "nobe prize",
            "highlighted": "nobe <em>prize</em>",
            "score": 0.09049256
          }
        ]
      }
    ]
  }
</code>```

What should I do to get 'noble prize' as the suggestion?
Please help.

答:
I found the answer myself. Need to tell ES how many terms in the search text are misspelled using the parameter 'max_errors'. 'max_errors' can be given as a percentage value in the form of float or an absolute number.

"click below for ES documentation on Phrase suggester with max_errors parameter"
https://www.elastic.co/guide/en/elasticsearch/reference/master/search-suggesters-phrase.html

Accordingly I added 'max_errors' parameter value as 2 like below

```<code>POST test/_search
{
  "suggest": {
    "text": "nobe priz",
    "simple_phrase": {
      "phrase": {
        "field": "title.trigram",
        "size": 1,
        "gram_size": 3,
        "max_errors": 2,
        "direct_generator": [ {
          "field": "title.trigram",
          "suggest_mode": "always"
        } ],
        "highlight": {
          "pre_tag": "<em>",
          "post_tag": "</em>"
        }
      }
    }
  }
}
</code>```

And I got the exact matching phrase suggestion as below

```<code>"suggest": {
    "simple_phrase": [
      {
        "text": "nobe priz",
        "offset": 0,
        "length": 9,
        "options": [
          {
            "text": "noble prize",
            "highlighted": "<em>noble prize</em>",
            "score": 0.4833575
          }
        ]
      }
    ]
  }
</code>```

So with max_errors as 2, the suggestion 'noble prize' is getting returned.

Cheers :)

Body:
I am using elasticsearch 5.5.2

I am trying phrase suggester and NOT able to configure it to return the exact suggestion that is in the index already. My index settings, type mappings and phrase suggest query are given below. Please help.

My index settings and type mappings are

PUT test
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "trigram_analyzer": {
            "type": "custom",
            "tokenizer": "standard",
            "filter": ["shingle"]
          }
        },
        "filter": {
          "shingle": {
            "type": "shingle",
            "min_shingle_size": 2,
            "max_shingle_size": 3
          }
        }
      }
    }
  },
  "mappings": {
    "test": {
      "properties": {
        "title": {
          "type": "text",
          "fields": {
            "trigram": {
              "type": "text",
              "analyzer": "trigram_analyzer"
            }
          }
        }
      }
    }
  }
}

Indexed document using

POST test/test?refresh=true
{"title": "noble prize"}

The phrase suggester I am using

POST test/_search
{
  "suggest": {
    "text": "nobe priz",
    "simple_phrase": {
      "phrase": {
        "field": "title.trigram",
        "size": 1,
        "gram_size": 3,
        "direct_generator": [ {
          "field": "title.trigram",
          "suggest_mode": "always"
        } ],
        "highlight": {
          "pre_tag": "",
          "post_tag": ""
        }
      }
    }
  }
}

The result I am getting is

"suggest": {
    "simple_phrase": [
      {
        "text": "nobe priz",
        "offset": 0,
        "length": 9,
        "options": [
          {
            "text": "noble priz",
            "highlighted": "noble priz",
            "score": 0.09049256
          }
        ]
      }
    ]
  }

My question is, for the search text - 'nobe priz' - why I am NOT getting 'noble prize' as the suggestion. Instead why I am just getting 'noble priz'?

If we see, 'noble prize' is the document I have saved.

And if I increase the value of size to '2', then also I am NOT getting 'noble prize' as one of the suggestions.

With size as 2, for the search text 'nobe priz' I am getting the below response

"suggest": {
    "simple_phrase": [
      {
        "text": "nobe priz",
        "offset": 0,
        "length": 9,
        "options": [
          {
            "text": "noble priz",
            "highlighted": "nobel priz",
            "score": 0.09049256
          },
          {
            "text": "nobe prize",
            "highlighted": "nobe prize",
            "score": 0.09049256
          }
        ]
      }
    ]
  }

What should I do to get 'noble prize' as the suggestion?
Please help.

Body:
I found the answer myself. Need to tell ES how many terms in the search text are misspelled using the parameter 'max_errors'. 'max_errors' can be given as a percentage value in the form of float or an absolute number.

"click below for ES documentation on Phrase suggester with max_errors parameter"
https://www.elastic.co/guide/en/elasticsearch/reference/master/search-suggesters-phrase.html

Accordingly I added 'max_errors' parameter value as 2 like below

POST test/_search
{
  "suggest": {
    "text": "nobe priz",
    "simple_phrase": {
      "phrase": {
        "field": "title.trigram",
        "size": 1,
        "gram_size": 3,
        "max_errors": 2,
        "direct_generator": [ {
          "field": "title.trigram",
          "suggest_mode": "always"
        } ],
        "highlight": {
          "pre_tag": "<em>",
          "post_tag": "</em>"
        }
      }
    }
  }
}

And I got the exact matching phrase suggestion as below

"suggest": {
    "simple_phrase": [
      {
        "text": "nobe priz",
        "offset": 0,
        "length": 9,
        "options": [
          {
            "text": "noble prize",
            "highlighted": "<em>noble prize</em>",
            "score": 0.4833575
          }
        ]
      }
    ]
  }

So with max_errors as 2, the suggestion 'noble prize' is getting returned.

Cheers :)


问:
Angular - issue with ng-Click and submit
Needed some help with AngularJS as I'm new to it.

I have a form which has a button to display a dialog box, and then once that dialog box pops up, user must submit the form from the button on the Dialog box.

But currently if the user hits enter in a textBox before the dialog box has been opened, the form gets submitted without the dialog generating.

The button on the main form looks like this :

```<code><button type="button" class="xyz xyz-one" ng-Click="popDialog()">
</code>```

And the button on the dialog which finally submits the form looks like this :

```<code><button type="submit" class="xyz xyz-one">
</code>```

Is there any way that on the UI when the user hits enter, the form is blocked from automatic submission and only the dialog pops up?

答:
Change the button in the main form to </p>

```<code><button type="button" ng-click="submit()">
</code>```

Body:
Needed some help with AngularJS as I'm new to it.

I have a form which has a button to display a dialog box, and then once that dialog box pops up, user must submit the form from the button on the Dialog box.

But currently if the user hits enter in a textBox before the dialog box has been opened, the form gets submitted without the dialog generating.

The button on the main form looks like this :

<button type="button" class="xyz xyz-one" ng-Click="popDialog()">

And the button on the dialog which finally submits the form looks like this :

<button type="submit" class="xyz xyz-one">

Is there any way that on the UI when the user hits enter, the form is blocked from automatic submission and only the dialog pops up?

Body:
Change the button in the main form to

<button type="button" ng-click="submit()">