问:
Codeigniter object not found error
I have made a login system, but when i click on "login" i got this error message:
"error 404 object not found".

I do not know whatto do now :S.

Here is my code:

My login file (the main file with the buttons)

```<code><!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WELCOME! » Jaranguda.com</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</head>

    <body>
        <div class="container">
        <h3>Login</h3>
        <hr>
        <form action="<?php echo base_url('Login/user')?>" method="POST">
            <div class="form-group">
                <label for="cari">USERNAME</label>
                <input type="text" name="usuario" id="usuario" class="form-control">

            </div>

            <div class="form-group">
                <label for="cari">PASSWORD</label>
                <input type="password" name="contrasena" id="contrasena" class="form-control">

            </div>

            <input class="btn btn-primary" type="submit" value="Login">
            <input class="btn btn-primary" type="reset" value="Reset">

        </form>
            </div>

    </body>
</code>```

The controller file:

```<code><?php

    class Login extends CI_Controller{

     public function __construct(){
         parent::__construct();
         $this->load->model("Login_model");

    }

    public function index(){

        $this->load->view("login");

    }

    public function user(){

        $data['login']=$this->Login_model->login();
        $this->load->view('user', $data);

    }

    }

?>
</code>```

The model file:

```<code><?php

class Login_model extends CI_Model{

    public function __construct(){

     $this->load->database();

    }

    public function login(){

        $usuario=$this->input->POST('usuario', TRUE);
        $contrasena=md5($this->input->POST('contrasena', TRUE));
        $data=$this->db->query("SELECT * from usuarios where usuario=$usuario and contrasena=$contrasena LIMIT 1");
        return $data=row();

      }

}

?>
</code>```

The user file:

```<code>    <!DOCTYPE html>
    <html lang="">

    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>BIENVENIDO! » Jaranguda.com</title>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js">
    </script>

    </head>

        <body>
            <div class="container">
            <h3>Login</h3>
            <hr>

<?php
if(count($login)>0)
{
    if($login->tipo=='0')
        echo "<p>YOU LOGGED AS: <b>".$login->tipo."</p>"

}

    elseif($login->tipo =='1'){

        echo "<p>usuario <b>".$login->usuario."</b> LOGGED AS: <b>".$login->tipo."</p>"

    }

    else{

        echo "<p>usuario <b>".$login->usuario."</b> SOMETHING WENT WRONG WHILE LOGGING</p>"

    }

?>

<?php

}
else
{

    echo "<p>USERNAME/PASSWORD INVALID.</p>"

}

?>

    </div>

<script src="//code.jquery.com/jquery.js"></script>

<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

</body>

</html>
</code>```

Hope you can help me :S

答:
The URL shown in the image above is typical of what happens if a $config['base_url'] is not set in application/config/config.php.

You MUST set a value for that config item. It must contain the protocol http or https

```<code>$config['base_url'] = 'http://example.com/';
</code>```

On an unnamed virtual server it would probably be

```<code>$config['base_url'] = 'http://localhost/';
</code>```

or maybe

```<code>$config['base_url'] = 'localhost';
</code>```

I cannot remember. Also, the above might need a trailing '/' e.g. localhost/

Title: Codeigniter object not found error

Body:
I have made a login system, but when i click on "login" i got this error message:
"error 404 object not found".

I do not know whatto do now :S.

Here is my code:

My login file (the main file with the buttons)

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WELCOME! » Jaranguda.com</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Login

        <form action="<?php echo base_url('Login/user')?>" method="POST">

                USERNAME
                <input type="text" name="usuario" id="usuario" class="form-control">

                PASSWORD
                <input type="password" name="contrasena" id="contrasena" class="form-control">

            <input class="btn btn-primary" type="submit" value="Login">
            <input class="btn btn-primary" type="reset" value="Reset">

        </form>

The controller file:

<?php

    class Login extends CI_Controller{

     public function __construct(){
         parent::__construct();
         $this->load->model("Login_model");

    }

    public function index(){

        $this->load->view("login");

    }

    public function user(){

        $data['login']=$this->Login_model->login();
        $this->load->view('user', $data);

    }

    }

?>

The model file:

<?php

class Login_model extends CI_Model{

    public function __construct(){

     $this->load->database();

    }

    public function login(){

        $usuario=$this->input->POST('usuario', TRUE);
        $contrasena=md5($this->input->POST('contrasena', TRUE));
        $data=$this->db->query("SELECT * from usuarios where usuario=$usuario and contrasena=$contrasena LIMIT 1");
        return $data=row();

      }

}

?>

The user file:

    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>BIENVENIDO! » Jaranguda.com</title>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Login

<?php
if(count($login)>0)
{
    if($login->tipo=='0')
        echo "
YOU LOGGED AS: ".$login->tipo."
"

}

    elseif($login->tipo =='1'){

        echo "
usuario ".$login->usuario." LOGGED AS: ".$login->tipo."
"

    }

    else{

        echo "
usuario ".$login->usuario." SOMETHING WENT WRONG WHILE LOGGING
"

    }

?>

<?php

}
else
{

    echo "
USERNAME/PASSWORD INVALID.
"

}

?>

Hope you can help me :S

Body:
The URL shown in the image above is typical of what happens if a $config['base_url'] is not set in application/config/config.php.

You MUST set a value for that config item. It must contain the protocol http or https

$config['base_url'] = 'http://example.com/';

On an unnamed virtual server it would probably be

$config['base_url'] = 'http://localhost/';

or maybe

$config['base_url'] = 'localhost';

I cannot remember. Also, the above might need a trailing '/' e.g. localhost/


来源: stackexchange

问:
Does Vaadin 8 `Binder::bindInstanceFields` only work with String data types?
Using the Vaadin 8 @PropertyId annotation with the Binder::bindInstanceFields is certainly shorter and sweeter than writing a line of code for each field-property binding.

```<code>Person person;  // `name` is String, `yearOfBirth` is Integer.
…
@PropertyId ( "name" )
final TextField nameField = new TextField ( "Full name:" ); // Bean property.

@PropertyId ( "yearOfBirth" )
final TextField yearOfBirthField = new TextField ( "Year of Birth:" ); // Bean property.
…
// Binding
Binder < Person > binder = new Binder <> ( Person.class );
binder.bindInstanceFields ( this );
binder.setBean ( person );
</code>```

But we get an Exception thrown because the yearOfBirth property is an Integer, and this easy-does-it binding approach lacks an converter.

SEVERE:

java.lang.IllegalStateException: Property type 'java.lang.Integer' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

Does that mean Binder::bindInstanceFields can be used only a beans made entirely of properties of String data type?

Is there a way to specify a Converter such as StringToIntegerConverter without having to itemize each and every binding in code?

答:
See Vaadin Framework, Vaadin Data Model, Binding Data to Forms:

Conversions

You can also bind application data to a UI field component even though the types do not match.

Binder#bindInstanceFields() says:

It's not always possible to bind a field to a property because their types are incompatible. E.g. custom converter is required to bind HasValue<String> and Integer property (that would be a case of "age" property). In such case IllegalStateException will be thrown unless the field has been configured manually before calling the bindInstanceFields(Object) method.

[...]: the bindInstanceFields(Object) method doesn't override existing bindings.

[Emphases by me.]

So, AFAIU, this should work:

```<code>private final TextField siblingsCount = new TextField( "№ of Siblings" );

...

binder.forField( siblingsCount )
    .withNullRepresentation( "" )
    .withConverter(
        new StringToIntegerConverter( Integer.valueOf( 0 ), "integers only" ) )
    .bind( Child::getSiblingsCount, Child::setSiblingsCount );
binder.bindInstanceFields( this );
</code>```

But it still throws:

java.lang.IllegalStateException: Property type 'java.lang.Integer' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.
  ...
  at com.vaadin.data.Binder.bindInstanceFields(Binder.java:2135)
  ...

Are you kidding me? That's what I did, didn't I? I rather doubt about "doesn't override existing bindings". Or, if not actually overridden, it seems they are ignored in bindInstanceFields(), at least.

The same manual binding configuration works when not using Binder#bindInstanceFields() but the approach with individual bindings for each field.

See also the thread Binding from Integer not working in the Vaadin Framework Data Binding forum and issue #8858 Binder.bindInstanceFields() overwrites existing bindings.

Workaround

Less convoluted than @cfrick's answer:

```<code>/** Used for workaround for Vaadin issue #8858
 *  'Binder.bindInstanceFields() overwrites existing bindings'
 *  https://github.com/vaadin/framework/issues/8858
 */
private final Map<String, Component> manualBoundComponents = new HashMap<>();
...
// Commented here and declared local below for workaround for Vaadin issue #8858
//private final TextField siblingsCount = new TextField( "№ of Siblings" );
...

public ChildView() {
    ...

    // Workaround for Vaadin issue #8858
    // Declared local here to prevent processing by Binder#bindInstanceFields()
    final TextField siblingsCount = new TextField( "№ of Siblings" );
    manualBoundComponents.put( "siblingsCount", siblingsCount );
    binder.forField( siblingsCount )
            .withNullRepresentation( "" )
            .withConverter( new StringToIntegerConverter( Integer.valueOf( 0 ), "integers only" ) )
            .bind( Child::getSiblingsCount, Child::setSiblingsCount );
    binder.bindInstanceFields( this );

    ...

    // Workaround for Vaadin issue #8858
    addComponent( manualBoundComponents.get( "siblingsCount" ) );
    //addComponent( siblingsCount );

    ...
}
</code>```

UPDATE

Fix #8998 Make bindInstanceFields not bind fields already bound using functions.

The source code for that fix appears at least in Vaadin 8.1.0 alpha 4 pre-release (and perhaps others).

Update by Basil Bourque…

Your idea, shown above, to use Binder::bindInstanceFields after a manual binding for the non-compatible (Integer) property does indeed seem to be working for me. You complained that in your experimental code the call to Binder::bindInstanceFields failed to follow the documented behavior where the call “doesn't override existing bindings”.

But it seems to work for me. Here is an example app for Vaadin 8.1.0 alpha 3. First I manually bind yearOfBirth property. Then I use binder.bindInstanceFields to bind the @PropertyId annotated name property. The field for both properties appear populated and respond to user-edits.

Did I miss something or is this working properly as documented? If I made a mistake, please delete this section.

```<code>package com.example.vaadin.ex_formatinteger;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Binder;
import com.vaadin.data.converter.StringToIntegerConverter;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;

import javax.servlet.annotation.WebServlet;

/**
 * This UI is the application entry point. A UI may either represent a browser window
 * (or tab) or some part of a html page where a Vaadin application is embedded.
 * <p>
 * The UI is initialized using {@link #init(VaadinRequest)}. This method is intended to be
 * overridden to add component to the user interface and initialize non-component functionality.
 */
@Theme ( "mytheme" )
public class MyUI extends UI {
    Person person;

    //@PropertyId ( "honorific" )
    final TextField honorific = new TextField ( "Honorific:" ); // Bean property.

    //@PropertyId ( "name" )
    final TextField name = new TextField ( "Full name:" ); // Bean property.

    // Manually bind property to field.
    final TextField yearOfBirthField = new TextField ( "Year of Birth:" ); // Bean property.

    final Label spillTheBeanLabel = new Label ( ); // Debug. Not a property.

    @Override
    protected void init ( VaadinRequest vaadinRequest ) {
        this.person = new Person ( "Ms.", "Margaret Hamilton", Integer.valueOf ( 1936 ) );

        Button button = new Button ( "Spill" );
        button.addClickListener ( ( Button.ClickEvent e ) -> {
            spillTheBeanLabel.setValue ( person.toString ( ) );
        } );

        // Binding
        Binder < Person > binder = new Binder <> ( Person.class );
        binder.forField ( this.yearOfBirthField )
              .withNullRepresentation ( "" )
              .withConverter ( new StringToIntegerConverter ( Integer.valueOf ( 0 ), "integers only" ) )
              .bind ( Person:: getYearOfBirth, Person:: setYearOfBirth );
        binder.bindInstanceFields ( this );
        binder.setBean ( person );

        setContent ( new VerticalLayout ( honorific, name, yearOfBirthField, button, spillTheBeanLabel ) );
    }

    @WebServlet ( urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true )
    @VaadinServletConfiguration ( ui = MyUI.class, productionMode = false )
    public static class MyUIServlet extends VaadinServlet {
    }
}
</code>```

And simple Person class.

```<code>package com.example.vaadin.ex_formatinteger;

import java.time.LocalDate;
import java.time.ZoneId;

/**
 * Created by Basil Bourque on 2017-03-31.
 */
public class Person {

    private String honorific ;
    private String name;
    private Integer yearOfBirth;

    // Constructor
    public Person ( String honorificArg , String nameArg , Integer yearOfBirthArg ) {
        this.honorific = honorificArg;
        this.name = nameArg;
        this.yearOfBirth = yearOfBirthArg;
    }

    public String getHonorific ( ) {
        return honorific;
    }

    public void setHonorific ( String honorific ) {
        this.honorific = honorific;
    }

    // name property
    public String getName ( ) {
        return name;
    }

    public void setName ( String nameArg ) {
        this.name = nameArg;
    }

    // yearOfBirth property
    public Integer getYearOfBirth ( ) {
        return yearOfBirth;
    }

    public void setYearOfBirth ( Integer yearOfBirth ) {
        this.yearOfBirth = yearOfBirth;
    }

    // age property. Calculated, so getter only, no setter.
    public Integer getAge ( ) {
        int age = ( LocalDate.now ( ZoneId.systemDefault ( ) )
                             .getYear ( ) - this.yearOfBirth );
        return age;
    }

    @Override
    public String toString ( ) {
        return "Person{ " +
                "honorific='" + this.getHonorific () + '\'' +
                ", name='" + this.getName ()  +
                ", yearOfBirth=" + this.yearOfBirth +
                ", age=" + this.getAge () +
                " }";
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using the Vaadin 8 @PropertyId annotation with the Binder::bindInstanceFields is certainly shorter and sweeter than writing a line of code for each field-property binding.

Person person;  // `name` is String, `yearOfBirth` is Integer.
…
@PropertyId ( "name" )
final TextField nameField = new TextField ( "Full name:" ); // Bean property.

@PropertyId ( "yearOfBirth" )
final TextField yearOfBirthField = new TextField ( "Year of Birth:" ); // Bean property.
…
// Binding
Binder < Person > binder = new Binder <> ( Person.class );
binder.bindInstanceFields ( this );
binder.setBean ( person );

But we get an Exception thrown because the yearOfBirth property is an Integer, and this easy-does-it binding approach lacks an converter.

SEVERE:

java.lang.IllegalStateException: Property type 'java.lang.Integer' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

Does that mean Binder::bindInstanceFields can be used only a beans made entirely of properties of String data type?

Is there a way to specify a Converter such as StringToIntegerConverter without having to itemize each and every binding in code?

Body:
See Vaadin Framework, Vaadin Data Model, Binding Data to Forms:

Conversions

You can also bind application data to a UI field component even though the types do not match.

Binder#bindInstanceFields() says:

It's not always possible to bind a field to a property because their types are incompatible. E.g. custom converter is required to bind HasValue<String> and Integer property (that would be a case of "age" property). In such case IllegalStateException will be thrown unless the field has been configured manually before calling the bindInstanceFields(Object) method.

[...]: the bindInstanceFields(Object) method doesn't override existing bindings.

[Emphases by me.]

So, AFAIU, this should work:

private final TextField siblingsCount = new TextField( "№ of Siblings" );

...

binder.forField( siblingsCount )
    .withNullRepresentation( "" )
    .withConverter(
        new StringToIntegerConverter( Integer.valueOf( 0 ), "integers only" ) )
    .bind( Child::getSiblingsCount, Child::setSiblingsCount );
binder.bindInstanceFields( this );

But it still throws:

java.lang.IllegalStateException: Property type 'java.lang.Integer' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.
  ...
  at com.vaadin.data.Binder.bindInstanceFields(Binder.java:2135)
  ...

Are you kidding me? That's what I did, didn't I? I rather doubt about "doesn't override existing bindings". Or, if not actually overridden, it seems they are ignored in bindInstanceFields(), at least.

The same manual binding configuration works when not using Binder#bindInstanceFields() but the approach with individual bindings for each field.

See also the thread Binding from Integer not working in the Vaadin Framework Data Binding forum and issue #8858 Binder.bindInstanceFields() overwrites existing bindings.

Workaround

Less convoluted than @cfrick's answer:

/** Used for workaround for Vaadin issue #8858
 *  'Binder.bindInstanceFields() overwrites existing bindings'
 *  https://github.com/vaadin/framework/issues/8858
 */
private final Map<String, Component> manualBoundComponents = new HashMap<>();
...
// Commented here and declared local below for workaround for Vaadin issue #8858
//private final TextField siblingsCount = new TextField( "№ of Siblings" );
...

public ChildView() {
    ...

    // Workaround for Vaadin issue #8858
    // Declared local here to prevent processing by Binder#bindInstanceFields()
    final TextField siblingsCount = new TextField( "№ of Siblings" );
    manualBoundComponents.put( "siblingsCount", siblingsCount );
    binder.forField( siblingsCount )
            .withNullRepresentation( "" )
            .withConverter( new StringToIntegerConverter( Integer.valueOf( 0 ), "integers only" ) )
            .bind( Child::getSiblingsCount, Child::setSiblingsCount );
    binder.bindInstanceFields( this );

    ...

    // Workaround for Vaadin issue #8858
    addComponent( manualBoundComponents.get( "siblingsCount" ) );
    //addComponent( siblingsCount );

    ...
}

UPDATE

Fix #8998 Make bindInstanceFields not bind fields already bound using functions.

The source code for that fix appears at least in Vaadin 8.1.0 alpha 4 pre-release (and perhaps others).

Update by Basil Bourque…

Your idea, shown above, to use Binder::bindInstanceFields after a manual binding for the non-compatible (Integer) property does indeed seem to be working for me. You complained that in your experimental code the call to Binder::bindInstanceFields failed to follow the documented behavior where the call “doesn't override existing bindings”.

But it seems to work for me. Here is an example app for Vaadin 8.1.0 alpha 3. First I manually bind yearOfBirth property. Then I use binder.bindInstanceFields to bind the @PropertyId annotated name property. The field for both properties appear populated and respond to user-edits.

Did I miss something or is this working properly as documented? If I made a mistake, please delete this section.

package com.example.vaadin.ex_formatinteger;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Binder;
import com.vaadin.data.converter.StringToIntegerConverter;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;

import javax.servlet.annotation.WebServlet;

/**
 * This UI is the application entry point. A UI may either represent a browser window
 * (or tab) or some part of a html page where a Vaadin application is embedded.
 * <p>
 * The UI is initialized using {@link #init(VaadinRequest)}. This method is intended to be
 * overridden to add component to the user interface and initialize non-component functionality.
 */
@Theme ( "mytheme" )
public class MyUI extends UI {
    Person person;

    //@PropertyId ( "honorific" )
    final TextField honorific = new TextField ( "Honorific:" ); // Bean property.

    //@PropertyId ( "name" )
    final TextField name = new TextField ( "Full name:" ); // Bean property.

    // Manually bind property to field.
    final TextField yearOfBirthField = new TextField ( "Year of Birth:" ); // Bean property.

    final Label spillTheBeanLabel = new Label ( ); // Debug. Not a property.

    @Override
    protected void init ( VaadinRequest vaadinRequest ) {
        this.person = new Person ( "Ms.", "Margaret Hamilton", Integer.valueOf ( 1936 ) );

        Button button = new Button ( "Spill" );
        button.addClickListener ( ( Button.ClickEvent e ) -> {
            spillTheBeanLabel.setValue ( person.toString ( ) );
        } );

        // Binding
        Binder < Person > binder = new Binder <> ( Person.class );
        binder.forField ( this.yearOfBirthField )
              .withNullRepresentation ( "" )
              .withConverter ( new StringToIntegerConverter ( Integer.valueOf ( 0 ), "integers only" ) )
              .bind ( Person:: getYearOfBirth, Person:: setYearOfBirth );
        binder.bindInstanceFields ( this );
        binder.setBean ( person );

        setContent ( new VerticalLayout ( honorific, name, yearOfBirthField, button, spillTheBeanLabel ) );
    }

    @WebServlet ( urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true )
    @VaadinServletConfiguration ( ui = MyUI.class, productionMode = false )
    public static class MyUIServlet extends VaadinServlet {
    }
}

And simple Person class.

package com.example.vaadin.ex_formatinteger;

import java.time.LocalDate;
import java.time.ZoneId;

/**
 * Created by Basil Bourque on 2017-03-31.
 */
public class Person {

    private String honorific ;
    private String name;
    private Integer yearOfBirth;

    // Constructor
    public Person ( String honorificArg , String nameArg , Integer yearOfBirthArg ) {
        this.honorific = honorificArg;
        this.name = nameArg;
        this.yearOfBirth = yearOfBirthArg;
    }

    public String getHonorific ( ) {
        return honorific;
    }

    public void setHonorific ( String honorific ) {
        this.honorific = honorific;
    }

    // name property
    public String getName ( ) {
        return name;
    }

    public void setName ( String nameArg ) {
        this.name = nameArg;
    }

    // yearOfBirth property
    public Integer getYearOfBirth ( ) {
        return yearOfBirth;
    }

    public void setYearOfBirth ( Integer yearOfBirth ) {
        this.yearOfBirth = yearOfBirth;
    }

    // age property. Calculated, so getter only, no setter.
    public Integer getAge ( ) {
        int age = ( LocalDate.now ( ZoneId.systemDefault ( ) )
                             .getYear ( ) - this.yearOfBirth );
        return age;
    }

    @Override
    public String toString ( ) {
        return "Person{ " +
                "honorific='" + this.getHonorific () + '\'' +
                ", name='" + this.getName ()  +
                ", yearOfBirth=" + this.yearOfBirth +
                ", age=" + this.getAge () +
                " }";
    }
}


问:
MYSQL - STRIP Spaces using a procedure
How would I strip spaces from a string from an added column in a database by using a function in MySQL?

Something like this format.

```<code>CREATE FUNCTION clean_string (str VARCHAR (50))
    RETURNS VARCHAR(50) DETERMINISTIC
BEGIN
    SQL statements/queries
END
</code>```

I'm very new with this stuff, so any help would be greatly appreciated.

答:
No need to write your own, you can simply use REPLACE:

```<code>mysql> SELECT REPLACE('foo bar qux', ' ', '');
+---------------------------------+
| REPLACE('foo bar qux', ' ', '') |
+---------------------------------+
| foobarqux                       |
+---------------------------------+
</code>```

So you can use:

```<code>UPDATE `table` SET `column` = REPLACE(`column`, ' ', '');
</code>```

to remove all spaces from the specified column of specified table.

Or you can define a function:

```<code>CREATE FUNCTION clean_string (str VARCHAR (50))
   RETURNS VARCHAR(50) DETERMINISTIC
   <b>RETURN REPLACE(str, ' ', '');</b></code>```

and then you an update with:

```<code>UPDATE `table` SET `column` = clean_string(`column`);
</code>```

But since here you only substitute one function call for another there is not much added value here.

Title: MYSQL - STRIP Spaces using a procedure

Body:
How would I strip spaces from a string from an added column in a database by using a function in MySQL?

Something like this format.

CREATE FUNCTION clean_string (str VARCHAR (50))
    RETURNS VARCHAR(50) DETERMINISTIC
BEGIN
    SQL statements/queries
END

I'm very new with this stuff, so any help would be greatly appreciated.

Body:
No need to write your own, you can simply use REPLACE:

mysql> SELECT REPLACE('foo bar qux', ' ', '');
+---------------------------------+
| REPLACE('foo bar qux', ' ', '') |
+---------------------------------+
| foobarqux                       |
+---------------------------------+

So you can use:

UPDATE `table` SET `column` = REPLACE(`column`, ' ', '');

to remove all spaces from the specified column of specified table.

Or you can define a function:

CREATE FUNCTION clean_string (str VARCHAR (50))
   RETURNS VARCHAR(50) DETERMINISTIC
   RETURN REPLACE(str, ' ', '');

and then you an update with:

UPDATE `table` SET `column` = clean_string(`column`);

But since here you only substitute one function call for another there is not much added value here.


问:
Type annotate a function parameter as derived from multiple abstract base classes in Python
I'm trying to type annotate a function in Python 2 according to PEP 484. The function accepts a container which should implement both __len__ and __iter__. The original code where I want to add this annotation is quite complex, so consider an example function  which returns the product of all ints in a container s if len(s) is even and returns 1 otherwise.

If I wanted to annotate a container where only __len__ is needed, I would have annotated it as type: (Sized) -> int. If I wanted to annotate a container where only __iter__ is needed, I would have annotated it as type: (Iterable[int]) -> int. But how do I perfectly annotate a container where I need both?

I tried this as per Piotr-Ćwiek's suggestion:

from __future__ import print_function
from typing import Sized, Iterable

class SizedIterable(Sized, Iterable[int]):
    pass

def product2(numbers):
    # type: (SizedIterable) -> int
    if len(numbers)%2 == 1:
        return 1
    else:
        p = 1
        for n in numbers:
            p*= n
        return p

print(product2([1, 2, 3, 4]))
print(product2({1, 2, 3, 4}))
```

<p>but this failed with this error:</p>

<pre class="lang-none prettyprint-override"><code>prod2.py:17: error: Argument 1 to "product2" has incompatible type List[int]; expected "SizedIterable"
prod2.py:18: error: Argument 1 to "product2" has incompatible type Set[int]; expected "SizedIterable"
</code>```

答:
In python 3.6, there's typing.Collection that works almost perfectly for your use case (it also derives from Container, but realistically anything that you want to use will likely have __contains__). Unfortunately, there's no solution for python 2.

The reason SizedIterable doesn't work is that by deriving it from Sized and Iterable, you are only telling mypy that it's a subtype of those two types; mypy does not conclude that any type that's a subtype of Sized and Iterable is also a subtype of SizedIterable.

Mypy's is perfectly logical; after all, you wouldn't want this code to type check:

```<code>class A(Sized, Iterable[int]):
  def g(self) -> None:
    ...

def f(x: A) -> None:
  a.g()

# passes type check because [1, 2] is Sized and Iterable
# but fails in run-time
f([1, 2])
</code>```

It would be too tricky if mypy treated your class definition differently just because its class body is empty.

In order for mypy to understand your intent, mypy would need to add a new feature to its type system.

Two options for such a feature are being considered at the moment:

intersections (as pointed out by  @PiotrĆwiek); what you're asking for is an intersection of Iterable and Sized

structural typing; this is much simpler than general intersections, but sufficient for your use case, since all you need is for the numbers argument to have __len__ and __iter__ methods

Mimicking typing class definitions or using __instancecheck__ won't work because (as someone explained to me just recently) under no condition will mypy ever run the code you wrote (i.e., it will never import your module, never call your function, etc.). This is because mypy is a static analysis tool that doesn't assume that the environment to run your code is even available during its execution (e.g., python version, libraries, etc.).

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to type annotate a function in Python 2 according to PEP 484. The function accepts a container which should implement both __len__ and __iter__. The original code where I want to add this annotation is quite complex, so consider an example function  which returns the product of all ints in a container s if len(s) is even and returns 1 otherwise.

If I wanted to annotate a container where only __len__ is needed, I would have annotated it as type: (Sized) -> int. If I wanted to annotate a container where only __iter__ is needed, I would have annotated it as type: (Iterable[int]) -> int. But how do I perfectly annotate a container where I need both?

I tried this as per Piotr-Ćwiek's suggestion:

from __future__ import print_function
from typing import Sized, Iterable

class SizedIterable(Sized, Iterable[int]):
    pass

def product2(numbers):
    # type: (SizedIterable) -> int
    if len(numbers)%2 == 1:
        return 1
    else:
        p = 1
        for n in numbers:
            p*= n
        return p

print(product2([1, 2, 3, 4]))
print(product2({1, 2, 3, 4}))

but this failed with this error:

prod2.py:17: error: Argument 1 to "product2" has incompatible type List[int]; expected "SizedIterable"
prod2.py:18: error: Argument 1 to "product2" has incompatible type Set[int]; expected "SizedIterable"

Body:
In python 3.6, there's typing.Collection that works almost perfectly for your use case (it also derives from Container, but realistically anything that you want to use will likely have __contains__). Unfortunately, there's no solution for python 2.

The reason SizedIterable doesn't work is that by deriving it from Sized and Iterable, you are only telling mypy that it's a subtype of those two types; mypy does not conclude that any type that's a subtype of Sized and Iterable is also a subtype of SizedIterable.

Mypy's is perfectly logical; after all, you wouldn't want this code to type check:

class A(Sized, Iterable[int]):
  def g(self) -> None:
    ...

def f(x: A) -> None:
  a.g()

# passes type check because [1, 2] is Sized and Iterable
# but fails in run-time
f([1, 2])

It would be too tricky if mypy treated your class definition differently just because its class body is empty.

In order for mypy to understand your intent, mypy would need to add a new feature to its type system.

Two options for such a feature are being considered at the moment:

intersections (as pointed out by  @PiotrĆwiek); what you're asking for is an intersection of Iterable and Sized

structural typing; this is much simpler than general intersections, but sufficient for your use case, since all you need is for the numbers argument to have __len__ and __iter__ methods

Mimicking typing class definitions or using __instancecheck__ won't work because (as someone explained to me just recently) under no condition will mypy ever run the code you wrote (i.e., it will never import your module, never call your function, etc.). This is because mypy is a static analysis tool that doesn't assume that the environment to run your code is even available during its execution (e.g., python version, libraries, etc.).


问:
My nested for loop number pattern doesn't out put the correct pattern
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

```<code>Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1
</code>```

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

```<code>import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }
</code>```

This is the Output I'm Getting

```<code>run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6
</code>```

答:
```<code>    int a = 654321;
    String str = new Integer(a).toString();

    for (int i = str.length() - 1; i >= 0  ; i--) {
        String g = String.format("%6s", str.substring(i));
        System.out.println(g.replaceAll(".(?=.)", "$0 "));
    }

    System.out.println();

    str = new StringBuffer(str).reverse().toString();
    for (int i = str.length() - 1; i >= 0  ; i--) {
        String g = String.format("%6s", str.substring(0, i+1));
        System.out.println(g.replaceAll(".(?=.)", "$0 "));
    }
</code>```

Body:
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }

This is the Output I'm Getting

run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6


问:
Android main thread stalls when exiting ASyncTasks
I am currently trying to figure out how to avoid a stall in my main thread when exiting ASyncTasks, and I'll try to explain with skeleton code where the problem is specifically. I'm sorry if this is a duplicate, I wasn't seeing anything other than posts about ASyncTasks stalling the main thread during execution. I have a hypothesis of what's causing the problem, but I have no idea if it's right. If it is right, or if it's wrong, I'd like to know the "proper" way to handle the situation.

```<code>public class AST extends ASyncTask<String, Integer, Void> {
  private Activity mActivity;
  private interfaceObject mInterface;

  public AST(Activity activity, interfaceObject interface) {
    mActivity = activity;
    mInterface = interface;
  }

  @Override
  protected void onPreExecute() {
    //mInterface.setStatus("Starting...");
    mInterface.setStatus("Doing Stuff...");
  }

  @Override
  protected String doInBackground(Void... params) {
    String string = doStuff();

    //mInterface.setStatus("Did Stuff."); As mentioned this shouldn't be done.

    return string;
  }

  @Override
  protected void onProgressUpdate(Integer... progress) {
    //mInterface.setStatus("Doing Stuff...");
    mInterface.progressUpdate(progress[0], progress[1]);
  }

  @Override
  protected void onPostExecute(String result) {
    mInterface.setStatus("Finished.");
    mInterface.astDone(result);
  }

  private String doStuff() {
    StringBuilder string = "";
    for(int i=0; i<10000; i++) {
      string.append("A");
      publishProgress(i, 10000);
    }
    return string.toString();
  }
}
</code>```

For specifics, setStatus(String status) edits the text of a textView on the main thread. progressUpdate(int progress, int max) does the same thing for a progressbar. At around 90% the progress bar freezes with the whole UI (despite a Log.d outputting the correct values). The message "Did Stuff." never appears, and there are ~200 skipped frames that get larger as the string gets larger. After the 200 skipped frames, "Finished." appears and astDone gets called (which starts another ASyncTask).

Now why would this hang?

My theory is that when the main thread has to read in the large string, it's stalling, but I don't know if I'm way off base on that? Is there a "proper" way to pass large data from one ASyncTask to another? I suppose I could write to a file in one and read from it in the other, but is that what's considered proper?

Thank you for your time!

Also, just as an aside question, if I slow down the doStuff() method, by adding in an additional loop, the progress bar will make it to 100% and "Finished." does appear. Shouldn't the main thread always receive these before stalling on my large string? Does the main thread not have an order handler, so it is ideal for me to make my publishProgress calls take as long or longer than the main thread takes to actually display the progress? I just don't understand how the main thread can stall at different points in my ASyncTask's calls to the main thread. Shouldn't the main thread execute the calls from ASyncTask as they are received, then hit the variable read and stall?

Edit1: I have changed the code to match Melquiades's suggestions, unfortunately I'm still skipping 200 frames.

Edit2: Since it's coming up I'll include the code for setStatus and progressUpdate:

```<code>@Override
public void progressUpdate(int cur, int max) {
    progressBar.setMax(max);
    progressBar.setProgress(cur);
}

@Override
public void setStatus(String status) {
    statusBar.setText(status);
}
</code>```

progressBar and statusBar are both member variables that are initialized onCreate(), although looking now there's probably no reason they need to be. Is this wrong?

```<code>private ProgressBar progressBar;
private TextView statusBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    statusBar = (TextView) findViewById(R.id.textView);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
</code>```

Edit3: Moved setStatus() out of onProgressUpdate() as suggested.

答:
setStatus(String status) edits the text of a textView on the main thread.

How do you do that exactly (what's the body if this method?) Keep in mind that in AsyncTask, one should not attempt accessing UI elements from doInBackground() - this methods does not run on UI thread, as opposed to 3 other callbacks (onPreExecute, onPublishProgress, and onPostExecute).

Another thing -  this innocent line:

```<code>string += "A";
</code>```

actually creates new string 10k times as Strings are immutable.

Things to try:

see what happens when you comment out setStatus call in doInBackground()

use StringBuilder instead of String in your doStuff() method

Body:
I am currently trying to figure out how to avoid a stall in my main thread when exiting ASyncTasks, and I'll try to explain with skeleton code where the problem is specifically. I'm sorry if this is a duplicate, I wasn't seeing anything other than posts about ASyncTasks stalling the main thread during execution. I have a hypothesis of what's causing the problem, but I have no idea if it's right. If it is right, or if it's wrong, I'd like to know the "proper" way to handle the situation.

public class AST extends ASyncTask<String, Integer, Void> {
  private Activity mActivity;
  private interfaceObject mInterface;

  public AST(Activity activity, interfaceObject interface) {
    mActivity = activity;
    mInterface = interface;
  }

  @Override
  protected void onPreExecute() {
    //mInterface.setStatus("Starting...");
    mInterface.setStatus("Doing Stuff...");
  }

  @Override
  protected String doInBackground(Void... params) {
    String string = doStuff();

    //mInterface.setStatus("Did Stuff."); As mentioned this shouldn't be done.

    return string;
  }

  @Override
  protected void onProgressUpdate(Integer... progress) {
    //mInterface.setStatus("Doing Stuff...");
    mInterface.progressUpdate(progress[0], progress[1]);
  }

  @Override
  protected void onPostExecute(String result) {
    mInterface.setStatus("Finished.");
    mInterface.astDone(result);
  }

  private String doStuff() {
    StringBuilder string = "";
    for(int i=0; i<10000; i++) {
      string.append("A");
      publishProgress(i, 10000);
    }
    return string.toString();
  }
}

For specifics, setStatus(String status) edits the text of a textView on the main thread. progressUpdate(int progress, int max) does the same thing for a progressbar. At around 90% the progress bar freezes with the whole UI (despite a Log.d outputting the correct values). The message "Did Stuff." never appears, and there are ~200 skipped frames that get larger as the string gets larger. After the 200 skipped frames, "Finished." appears and astDone gets called (which starts another ASyncTask).

Now why would this hang?

My theory is that when the main thread has to read in the large string, it's stalling, but I don't know if I'm way off base on that? Is there a "proper" way to pass large data from one ASyncTask to another? I suppose I could write to a file in one and read from it in the other, but is that what's considered proper?

Thank you for your time!

Also, just as an aside question, if I slow down the doStuff() method, by adding in an additional loop, the progress bar will make it to 100% and "Finished." does appear. Shouldn't the main thread always receive these before stalling on my large string? Does the main thread not have an order handler, so it is ideal for me to make my publishProgress calls take as long or longer than the main thread takes to actually display the progress? I just don't understand how the main thread can stall at different points in my ASyncTask's calls to the main thread. Shouldn't the main thread execute the calls from ASyncTask as they are received, then hit the variable read and stall?

Edit1: I have changed the code to match Melquiades's suggestions, unfortunately I'm still skipping 200 frames.

Edit2: Since it's coming up I'll include the code for setStatus and progressUpdate:

@Override
public void progressUpdate(int cur, int max) {
    progressBar.setMax(max);
    progressBar.setProgress(cur);
}

@Override
public void setStatus(String status) {
    statusBar.setText(status);
}

progressBar and statusBar are both member variables that are initialized onCreate(), although looking now there's probably no reason they need to be. Is this wrong?

private ProgressBar progressBar;
private TextView statusBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    statusBar = (TextView) findViewById(R.id.textView);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
}

Edit3: Moved setStatus() out of onProgressUpdate() as suggested.

Body:
setStatus(String status) edits the text of a textView on the main thread.

How do you do that exactly (what's the body if this method?) Keep in mind that in AsyncTask, one should not attempt accessing UI elements from doInBackground() - this methods does not run on UI thread, as opposed to 3 other callbacks (onPreExecute, onPublishProgress, and onPostExecute).

Another thing -  this innocent line:

string += "A";

actually creates new string 10k times as Strings are immutable.

Things to try:

see what happens when you comment out setStatus call in doInBackground()

use StringBuilder instead of String in your doStuff() method


问:
Is it possible to see a log of changes made to Firebase db?
One of my firebase objects was deleted and I was trying to figure out when this happened.  Does Firebase have a log that shows you when the changes occurred?

Some people have said this exists in Analytics but i was unable to locate it.

Thanks in advance.

答:
firebaser here

There is no publicly accessible log of all changes that were made to your Firebase Realtime Database.


问:
Why it is common to use anchor inside list item for navbar?
I could not find any information, why it is common to use anchor in list item in navbar?

```<code><ul>
    <li><a href="/one">One</a></li>
    <li><a href="/two">Two</a></li>
</ul>
</code>```

Even navbar in Bootstrap 3 is implemented in such way

```<code><ul class="nav navbar-nav">
  <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
  <li><a href="#">Link</a></li>
  <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
    <ul class="dropdown-menu">
      <li><a href="#">Action</a></li>
      <li><a href="#">Another action</a></li>
      <li><a href="#">Something else here</a></li>
      <li role="separator" class="divider"></li>
      <li><a href="#">Separated link</a></li>
      <li role="separator" class="divider"></li>
      <li><a href="#">One more separated link</a></li>
    </ul>
  </li>
</ul>
</code>```

Even now some HTML-coders use it and teach to do it.
Why should I use this awkward markup? Then I have to "clean" all browser-default styles for list-items list-style-type: none; and put inside each list item an anchor for navigation link?

What is wrong with this, below?

```<code><div class="nav">
  <span><a href="/one">One</a></span>
  <span><a href="/two">Two</a></span>
</div>
</code>```

 or
 does not matter.
It is already 3 years of HTML5, what is wrong with this, below?

```<code><nav>
  <a href="/one">One</a>
  <a href="/two">Two</a>
</nav>
</code>```

Is it connected some-how with old browsers? If yes, give me a link to read what was wrong, please.

答: Because the lis (= "list items") list  the available pages of that website. That's a semantic concept in HTML, its inherent logic works well mainly for accessibility on websites and for search engines (again: listing  the pages of that website).

Body:
I could not find any information, why it is common to use anchor in list item in navbar?

One

Two

Even navbar in Bootstrap 3 is implemented in such way

Link (current)

Link

    Dropdown

Action

Another action

Something else here

Separated link

One more separated link

Even now some HTML-coders use it and teach to do it.
Why should I use this awkward markup? Then I have to "clean" all browser-default styles for list-items list-style-type: none; and put inside each list item an anchor for navigation link?

What is wrong with this, below?

  One
  Two

 or
 does not matter.
It is already 3 years of HTML5, what is wrong with this, below?

  One
  Two

Is it connected some-how with old browsers? If yes, give me a link to read what was wrong, please.


问:
Adding plots to a pdf file
My code reads all the text file in the folder, turns it into an array and plots a histogram of each data using a for cycle, pretty simple stuf, but I want to save all it returns, all the histograms into a single pdf file. I know the function:

```<code>plt.savefig('file.pdf')
</code>```

works but since it's in a for cycle it will only save the last one, I mean it overwrites on it. Is there a function to add the other histograms or should I change the code?

答:
You essentially have two options.

1. Create multiple pdf files, merge them afterwards

Merge PDF files

append page to existing pdf file using python

2. Write all plots directly to a single pdf file.

Example from the matplotlib page: http://matplotlib.org/examples/pylab_examples/multipage_pdf.html

Output a Document (preferably a PDF) from Python

why does no picture show

Title: Adding plots to a pdf file

Body:
My code reads all the text file in the folder, turns it into an array and plots a histogram of each data using a for cycle, pretty simple stuf, but I want to save all it returns, all the histograms into a single pdf file. I know the function:

plt.savefig('file.pdf')

works but since it's in a for cycle it will only save the last one, I mean it overwrites on it. Is there a function to add the other histograms or should I change the code?


问:
Preserving login session across multiple Android apps
I have two apps that both log in to the same system but they have separate functions and may not both be installed at the same time. I can sign the two apps with the same signature no problem, even make them run in the same process.

How can I store the login cookie (among other things) in such a way that it is shared by both apps and still be secured from unknown apps?

答:
Err... what's it called... a data provider?  Nope. I'm getting "Service" and "Content Provider" mixed up.

Put both apps and the login service in the same process.  Either app should be able to start the service or query it for session info and anything else you might want to put there.

Alternatively, you can put all that information into a shared database.

The login dialog itself probably has to be an activity, and I'm not sure if you can have an activity within a service.  You may need duplicate login screens in your apps that could then pass the session data to your service for sharing purposes.

I'm not sure if the service would have to be a separate install, or something that could be bundled with both apps.

ContentLicense: CC BY-SA 2.5


问:
Convert string to object
I'M making an angular2 application and right now i'm trying to parse a string into a object. Basically what is happening is I'm passing back a string, and i want to convert it into a unique object called IDate.
I get a string in this format "2017-02-27T00:00:00", but i want it as IDate(). So what i have done so far is created a IDate class, that takes a string and converts it to a date. I created a Mock class to map the response to an object. However, when i print the object, i see the value stays a string. Anyone know how to achieve what I'm talking about? I'm basically trying to map the string to an object when i map the response from the controller. I could do this in an operation like, resposne.map(r.time => new Date(r.time));  But i rather have it mapped in the response, because i call this controllers in other places and i dont want to repeat the process on separate pages. Can this be done?

Controller

```<code>        return Json(new { Number = 1, Time= "2017-02-27T00:00:00" });
</code>```

Client

```<code>class IDate {
    value: Date;
    contructor(value) {
        this.value = new Date(value);
    }
}
class Mock {
    number: number;
    time: IDate;
}
mock: Mock = null;

 this.service.get()
            .subscribe(
            response => {
                console.log("Test response");
                this.mock = response;
                console.log(this.mock);
            },
</code>```

Console

```<code>Object
  number:1
  time:"2017-02-27T00:00:00"
  __proto__:Object
</code>```

答:
I am assuming that you are getting a JSON string from your REST API. If this holds true for your case, you may use a reviver. Here is a simplistic approach to use the reviver:

```<code>JSON.parse(jsonString, function (key, value) {
    if (key === "time")
        return new Date(value);
    return value;
})
</code>```

Here is the link to a running fiddle: https://jsfiddle.net/sayan751/Lzb8u638/.

Updated based on OP's comment

Converting a generic object to an instance of a specific class is not very straight forward. Note that this.mock = response; does not covert response to an instance of Mock class (refer the new fiddle link).

You may use Object.assign, but it might not work with type conversion.

Also I think in your case, the schema of the json object {Number:number, Time:string} received in your JavaScript code does not match with the schema of Mock:{number:number, time:{value:Date}}.

In this case, it would be best (as per my opinion) to write a custom converter for Mock. One simplistic approach can be as below. For detailed code, refer the new fiddle link.

```<code>class Mock {
    number: number;
    time: IDate;

    public static create(obj):Mock{
        let retVal = new Mock();
      retVal.number=obj.number;

      if(typeof obj.time === "string")
        retVal.time = new Date(obj.time); //better to use moment in this case, if possible
      else if(obj.time instanceof Date)
        retVal.time = obj.time;

      return retVal;
    }
}

var jsonObj = { number: 1, time: "2017-02-27T00:00:00" };

var obj = Mock.create(jsonObj);
</code>```

Link to fiddle: https://jsfiddle.net/sayan751/mxoqqc5a/

Hope this helps.

Title: Convert string to object

Body:
I'M making an angular2 application and right now i'm trying to parse a string into a object. Basically what is happening is I'm passing back a string, and i want to convert it into a unique object called IDate.
I get a string in this format "2017-02-27T00:00:00", but i want it as IDate(). So what i have done so far is created a IDate class, that takes a string and converts it to a date. I created a Mock class to map the response to an object. However, when i print the object, i see the value stays a string. Anyone know how to achieve what I'm talking about? I'm basically trying to map the string to an object when i map the response from the controller. I could do this in an operation like, resposne.map(r.time => new Date(r.time));  But i rather have it mapped in the response, because i call this controllers in other places and i dont want to repeat the process on separate pages. Can this be done?

Controller

        return Json(new { Number = 1, Time= "2017-02-27T00:00:00" });

Client

class IDate {
    value: Date;
    contructor(value) {
        this.value = new Date(value);
    }
}
class Mock {
    number: number;
    time: IDate;
}
mock: Mock = null;

 this.service.get()
            .subscribe(
            response => {
                console.log("Test response");
                this.mock = response;
                console.log(this.mock);
            },

Console

Object
  number:1
  time:"2017-02-27T00:00:00"
  __proto__:Object

Body:
I am assuming that you are getting a JSON string from your REST API. If this holds true for your case, you may use a reviver. Here is a simplistic approach to use the reviver:

JSON.parse(jsonString, function (key, value) {
    if (key === "time")
        return new Date(value);
    return value;
})

Here is the link to a running fiddle: https://jsfiddle.net/sayan751/Lzb8u638/.

Updated based on OP's comment

Converting a generic object to an instance of a specific class is not very straight forward. Note that this.mock = response; does not covert response to an instance of Mock class (refer the new fiddle link).

You may use Object.assign, but it might not work with type conversion.

Also I think in your case, the schema of the json object {Number:number, Time:string} received in your JavaScript code does not match with the schema of Mock:{number:number, time:{value:Date}}.

In this case, it would be best (as per my opinion) to write a custom converter for Mock. One simplistic approach can be as below. For detailed code, refer the new fiddle link.

class Mock {
    number: number;
    time: IDate;

    public static create(obj):Mock{
        let retVal = new Mock();
      retVal.number=obj.number;

      if(typeof obj.time === "string")
        retVal.time = new Date(obj.time); //better to use moment in this case, if possible
      else if(obj.time instanceof Date)
        retVal.time = obj.time;

      return retVal;
    }
}

var jsonObj = { number: 1, time: "2017-02-27T00:00:00" };

var obj = Mock.create(jsonObj);

Link to fiddle: https://jsfiddle.net/sayan751/mxoqqc5a/

Hope this helps.


答:
There is no need to write your own function, use mysql's own replace() function to remove spaces by substituting them with an empty string:</p>

```<code>replace(field_name, ' ','')
</code>```

Title: MYSQL - STRIP Spaces using a procedure

Body:
There is no need to write your own function, use mysql's own replace() function to remove spaces by substituting them with an empty string:

replace(field_name, ' ','')


问:
How to make pseudo 3D or 2.5D effect?
After using Unity for over a year now for creating 3D games I'd like to do my first pseudo 3D or 2.5D game (or whatever it's called). What I mean is games like Clash of Clans or Boom Beach where objects are really 2D images rendered to give 3D feeling. Because I don't even know the correct word for that type of games it's really hard to get started. What I can think of is giving Camera rotation of (45, -45, 0) so that it looks down at the ground from the upper right corner and then creating empty gameObjects with Sprite Renderers and setting their rotation to (22.5, -45, 0) so that they face the camera. I don't know if that's how it's really done so could somebody give me a link to some neat tutorial or something because I'm stuck.</p>

答:
The keyword you are looking for is isometric projection.

You can use Unity to create that effect with 3D graphics. You need to set the camera rotation to (45, -45, 0) and set the Camera Projection to Orthographic.

If you want to only use 2D graphics then the graphics are made in such a way that they are drawn in an angle that it looks like you are looking at them in 45 degrees.

If you search for isometric unity then you should find a ton of tutorials for Unity.

Title: How to make pseudo 3D or 2.5D effect?


问:
onpaste event not fired on textarea for image data
I have a working page for <textarea> description with <input type="file"> upload.  I added screenshot onpaste support to the textarea which works in Firefox 52 and should work in Chrome.

However, in IE onpaste won't fire with a <textarea> focused for non-text data.

HTML test page (IE only for brevity):

```<code><!DOCTYPE html><html><head><meta charset="UTF-8"/></head><body><form>
<script type="text/ecmascript">
function tb_pasted(e) {
   document.getElementById('txtTest').value += ' evtfired ';
   var s = "data: " + clipboardData.getData("Text") + "\n";
   var numFinished = 0; var numStarted = 0;
   for( var i=0; i<clipboardData.files.length; ++i ) {
      ++numStarted;
      var file = clipboardData.files[i];
      var fileReader = new FileReader();
      fileReader.onload = function () {
          var base64Data = fileReader.result
          s += " s:" + file.size + " d:" + fileReader.result.substring(10, 30) + "\n";
          ++numFinished;
      }
      fileReader.readAsDataURL(file);
   }
   function alertWhenDone() {
      if( numFinished >= numStarted ) alert(s);
      else setTimeout(alertWhenDone, 100);
   }
   alertWhenDone();
   return false;
}
</script>
nofire on image: <br/><textarea id="txtTest" onpaste="return tb_pasted(event);"></textarea>
<br/><br/>always fires: <br/><div id="divTest" contenteditable="true"
     style="background-color:yellow; width:100px; height:100px;"
     onpaste="return tb_pasted(event);"></div>
</form></body></html>
</code>```

Is there some way I can get onpaste to fire anyways for "text only" fields regardless of content type or do I have to eradicate all <textarea> and text fields from this page?  I've read about using
 as text entry, which might work, but I'm hoping there's a better way.

EDIT: I tried returning false from onbeforepaste and that doesn't seem to help at all.  Below won't fire an onpaste event in IE for non-text:

```<code>Enter some text:
<textarea id="txtTest"
          onbeforepaste="alert('before paste'); return false;"
          onpaste="alert('pasting'); return true;"
          ></textarea>
</code>```

答:
```<code><!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<style type="text/css">
html,body{
    margin:0px;padding:0px;height:100%; background-color:black;
}
#divtoolbar{
    position:fixed;
    top:0;left:0;width:100%;
}
#divContent{

}
#preview{

}
img.obj{
    max-width:320px;
}
img.obj.fullscreen{
    max-width:none;width:auto;height:auto;margin:auto;overflow:visible!important;
}
ul{
    padding:0px;list-style:none;background-color:black;
}
*:hover{
    outline:red dotted thick;
}
</style>
<script type="text/javascript">
function toggleFullScreen(evt) {
var el=evt.target;
  if (!document.fullscreenElement &&    // alternative standard method
      !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
    el.className='obj fullscreen';
    el.oncontextmenu=function(){return false;}
    if (el.requestFullscreen) {
      el.requestFullscreen();
    } else if (el.msRequestFullscreen) {
      el.msRequestFullscreen();
    } else if (el.mozRequestFullScreen) {
      el.mozRequestFullScreen();
    } else if (el.webkitRequestFullscreen) {
      el.webkitRequestFullscreen(el.ALLOW_KEYBOARD_INPUT);
    }
  } else {
    el.className='obj';
    el.oncontextmenu=null;
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
  evt.stopPropagation();
  evt.preventDefault();
}

function handleFiles(files) {
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    var imageType = /image.*/;

    if (!file.type.match(imageType)) {
      continue;
    }

    var img = document.createElement("img");
    var el= document.createElement('li');
    img.classList.add("obj");
    img.file = file;
    img.addEventListener('dblclick',toggleFullScreen,false);
    el.appendChild(img)
    preview.appendChild(el); // Assuming that "preview" is a the div output where the content will be displayed.
    var reader = new FileReader();
    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result;aImg.scrollIntoView(true); }; })(img);
    reader.readAsDataURL(file);
  }
}
</script>
<title>filereader</title>
</head>

<body>
<div id="divtoolbar">
<input type="file" name="filselect" id="filselect" multiple accept="image/*,audio/*,video/*" style="width:100%" onchange="handleFiles(this.files);"/>
</div>
<div id="divContent">
<ul id="preview"></ul>
</div>
</body>

</html>
</code>```

Body:
I have a working page for <textarea> description with <input type="file"> upload.  I added screenshot onpaste support to the textarea which works in Firefox 52 and should work in Chrome.

However, in IE onpaste won't fire with a <textarea> focused for non-text data.

HTML test page (IE only for brevity):

<!DOCTYPE html><meta charset="UTF-8"/><form>

nofire on image:
<textarea id="txtTest" onpaste="return tb_pasted(event);"></textarea>

always fires:

</form>

Is there some way I can get onpaste to fire anyways for "text only" fields regardless of content type or do I have to eradicate all <textarea> and text fields from this page?  I've read about using
 as text entry, which might work, but I'm hoping there's a better way.

EDIT: I tried returning false from onbeforepaste and that doesn't seem to help at all.  Below won't fire an onpaste event in IE for non-text:

Enter some text:
<textarea id="txtTest"
          onbeforepaste="alert('before paste'); return false;"
          onpaste="alert('pasting'); return true;"
          ></textarea>


问:
How to setup printing in cocoa, swift?
I have made printing functionality for custom NSView of NSPopover by the assigning the following action to button for this NSView in mainController:

```<code>@IBOutlet var plasmidMapIBOutlet: PlasmidMapView!

@IBAction func actionPrintfMap(sender: AnyObject)
{
    plasmidMapIBOutlet.print(sender)
}
</code>```

It is working, but the print window has no option for Paper Size and Orientation, see screenshot below.

What should I do to get these options in the print window?

And, how to make the NSView fitting to the printable area? Now it is not fitting.

I have figured out some moments, but not completely. So, I can setup the printing by the following code

```<code> @IBAction func actionPrintMap(sender: AnyObject)
 {
    let printInfo = NSPrintInfo.sharedPrintInfo()
    let operation: NSPrintOperation = NSPrintOperation(view: plasmidMapIBOutlet, printInfo: printInfo)
    operation.printPanel.options = NSPrintPanelOptions.ShowsPaperSize
    operation.printPanel.options = NSPrintPanelOptions.ShowsOrientation
    operation.runOperation()

    //plasmidMapIBOutlet.print(sender)
 }
</code>```

But, I still have problem. From the code above I can get only orientation (the last, ShowsOrientation), but not both PaperSize and Orientation. How can I manage both ShowsPaperSize and ShowsOrientation?

答:
Finally I have found the answer which is simple to write but it is not really obvious from apple documentation. </p>

```<code>    operation.printPanel.options.insert(NSPrintPanelOptions.showsPaperSize)
    operation.printPanel.options.insert(NSPrintPanelOptions.showsOrientation)
</code>```

Title: How to setup printing in cocoa, swift?

Body:
I have made printing functionality for custom NSView of NSPopover by the assigning the following action to button for this NSView in mainController:

@IBOutlet var plasmidMapIBOutlet: PlasmidMapView!

@IBAction func actionPrintfMap(sender: AnyObject)
{
    plasmidMapIBOutlet.print(sender)
}

It is working, but the print window has no option for Paper Size and Orientation, see screenshot below.

What should I do to get these options in the print window?

And, how to make the NSView fitting to the printable area? Now it is not fitting.

I have figured out some moments, but not completely. So, I can setup the printing by the following code

 @IBAction func actionPrintMap(sender: AnyObject)
 {
    let printInfo = NSPrintInfo.sharedPrintInfo()
    let operation: NSPrintOperation = NSPrintOperation(view: plasmidMapIBOutlet, printInfo: printInfo)
    operation.printPanel.options = NSPrintPanelOptions.ShowsPaperSize
    operation.printPanel.options = NSPrintPanelOptions.ShowsOrientation
    operation.runOperation()

    //plasmidMapIBOutlet.print(sender)
 }

But, I still have problem. From the code above I can get only orientation (the last, ShowsOrientation), but not both PaperSize and Orientation. How can I manage both ShowsPaperSize and ShowsOrientation?

Body:
Finally I have found the answer which is simple to write but it is not really obvious from apple documentation.

    operation.printPanel.options.insert(NSPrintPanelOptions.showsPaperSize)
    operation.printPanel.options.insert(NSPrintPanelOptions.showsOrientation)


问:
How to plot decision boundary from linear SVM after PCA in Matlab?
I have conducted a linear SVM on a large dataset, however in order to reduce the number of dimensions I performed a PCA, than conducted the SVM on a subset of the component scores (the first 650 components which explained 99.5% of the variance). Now I want to plot the decision boundary in the original variable space using the beta weights and bias from the SVM created in PCA space. But I can't figure out how to project the bias term from the SVM into the original variable space. I've written a demo using the fisher iris data to illustrate:

```<code>clear; clc; close all

% load data
load fisheriris
inds = ~strcmp(species,'setosa');
X = meas(inds,3:4);
Y = species(inds);
mu = mean(X)

% perform the PCA
[eigenvectors, scores] = pca(X);

% train the svm
SVMModel = fitcsvm(scores,Y);

% plot the result
figure(1)
gscatter(scores(:,1),scores(:,2),Y,'rgb','osd')
title('PCA space')

% now plot the decision boundary
betas = SVMModel.Beta;
m = -betas(1)/betas(2); % my gradient
b = -SVMModel.Bias;     % my y-intercept
f = @(x) m.*x + b;      % my linear equation
hold on
fplot(f,'k')
hold off
axis equal
xlim([-1.5 2.5])
ylim([-2 2])

% inverse transform the PCA
Xhat = scores * eigenvectors';
Xhat = bsxfun(@plus, Xhat, mu);

% plot the result
figure(2)
hold on
gscatter(Xhat(:,1),Xhat(:,2),Y,'rgb','osd')

% and the decision boundary
betaHat = betas' * eigenvectors';
mHat = -betaHat(1)/betaHat(2);
bHat = b * eigenvectors';
bHat = bHat + mu;    % I know I have to add mu somewhere...
bHat = bHat/betaHat(2);
bHat = sum(sum(bHat)); % sum to reduce the matrix to a single value
% the correct value of bHat should be 6.3962

f = @(x) mHat.*x + bHat;
fplot(f,'k')
hold off

axis equal
title('Recovered feature space')
xlim([3 7])
ylim([0 4])
</code>```

Any guidance on how I'm calculating bHat incorrectly would be much appreciated.

答:
Just in case anyone else comes across this problem, the solution is the bias term can be used to find the y-intercept, b = -SVMModel.Bias/betas(2). And the y-intercept is just another point in space [0 b] which can be recovered/unrotated by inverse transforming it through the PCA. This new point can then be used to solve the linear equation y = mx + b (i.e., b = y - mx). So the code should be:

```<code>% and the decision boundary
betaHat = betas' * eigenvectors';
mHat = -betaHat(1)/betaHat(2);
yint = b/betas(2);                   % y-intercept in PCA space
yintHat = [0 b] * eigenvectors';     % recover in original space
yintHat = yintHat + mu;
bHat = yintHat(2) - mHat*yintHat(1); % solve the linear equation
% the correct value of bHat is now 6.3962
</code>```

Body:
I have conducted a linear SVM on a large dataset, however in order to reduce the number of dimensions I performed a PCA, than conducted the SVM on a subset of the component scores (the first 650 components which explained 99.5% of the variance). Now I want to plot the decision boundary in the original variable space using the beta weights and bias from the SVM created in PCA space. But I can't figure out how to project the bias term from the SVM into the original variable space. I've written a demo using the fisher iris data to illustrate:

clear; clc; close all

% load data
load fisheriris
inds = ~strcmp(species,'setosa');
X = meas(inds,3:4);
Y = species(inds);
mu = mean(X)

% perform the PCA
[eigenvectors, scores] = pca(X);

% train the svm
SVMModel = fitcsvm(scores,Y);

% plot the result
figure(1)
gscatter(scores(:,1),scores(:,2),Y,'rgb','osd')
title('PCA space')

% now plot the decision boundary
betas = SVMModel.Beta;
m = -betas(1)/betas(2); % my gradient
b = -SVMModel.Bias;     % my y-intercept
f = @(x) m.*x + b;      % my linear equation
hold on
fplot(f,'k')
hold off
axis equal
xlim([-1.5 2.5])
ylim([-2 2])

% inverse transform the PCA
Xhat = scores * eigenvectors';
Xhat = bsxfun(@plus, Xhat, mu);

% plot the result
figure(2)
hold on
gscatter(Xhat(:,1),Xhat(:,2),Y,'rgb','osd')

% and the decision boundary
betaHat = betas' * eigenvectors';
mHat = -betaHat(1)/betaHat(2);
bHat = b * eigenvectors';
bHat = bHat + mu;    % I know I have to add mu somewhere...
bHat = bHat/betaHat(2);
bHat = sum(sum(bHat)); % sum to reduce the matrix to a single value
% the correct value of bHat should be 6.3962

f = @(x) mHat.*x + bHat;
fplot(f,'k')
hold off

axis equal
title('Recovered feature space')
xlim([3 7])
ylim([0 4])

Any guidance on how I'm calculating bHat incorrectly would be much appreciated.

Body:
Just in case anyone else comes across this problem, the solution is the bias term can be used to find the y-intercept, b = -SVMModel.Bias/betas(2). And the y-intercept is just another point in space [0 b] which can be recovered/unrotated by inverse transforming it through the PCA. This new point can then be used to solve the linear equation y = mx + b (i.e., b = y - mx). So the code should be:

% and the decision boundary
betaHat = betas' * eigenvectors';
mHat = -betaHat(1)/betaHat(2);
yint = b/betas(2);                   % y-intercept in PCA space
yintHat = [0 b] * eigenvectors';     % recover in original space
yintHat = yintHat + mu;
bHat = yintHat(2) - mHat*yintHat(1); % solve the linear equation
% the correct value of bHat is now 6.3962


问:
Rails - How to add values in seperate objects together
You have an array of objects which contain a key-value reference.

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I am thinking:

```<code>objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}
</code>```

Does that work and if so how do I then return them back out of the group_by state?

答:
Whenever you can use Enumerable#group_by you can use some form of Hash#merge or Hash#update (aka merge!), and vice-versa. Others have used group_by, so here's a hash-merge answer.

Letting the variable bookings equal your array of hashes, you can write the following.

```<code>keys_to_aggregate = [:price1, :price2]

bookings.each_with_object({}) { |g,h| h.update(g[:booking_ref]=>g) { |_,o,n|
  keys_to_aggregate.reduce(o) { |f,k| f.merge(k=>o[k] + n[k]) } } }.values
  #=> [{:booking_ref=>"w578383", :foo=>"bar", :price1=>1100, :price2=>70},
  #    {:booking_ref=>"r123523", :foo=>"bar", :price1=>699, :price2=>4}]
</code>```

Note that before Hash#values at the end of the expression is evaluated we have the following.

```<code>bookings.each_with_object({}) { |g,h| h.update(g[:booking_ref]=>g) { |_,o,n|
  keys_to_aggregate.reduce(o) { |f,k| f.merge(k=>o[k] + n[k]) } } }
  #=> {"w578383"=>{:booking_ref=>"w578383", :foo=>"bar", :price1=>1100, :price2=>70},
  #    "r123523"=>{:booking_ref=>"r123523", :foo=>"bar", :price1=>699, :price2=>4}}
</code>```

This uses the form of Hash#update that employs a block to determine the values of keys that are present in both hashes being merged. See the doc for details, particularly the definitions of the value-determining block's three variables (k, o and n). (I've substituted _ for k [the key] to signify that it is not used in the block calculation.)

Body:
You have an array of objects which contain a key-value reference.

[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I am thinking:

objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}

Does that work and if so how do I then return them back out of the group_by state?

Body:
Whenever you can use Enumerable#group_by you can use some form of Hash#merge or Hash#update (aka merge!), and vice-versa. Others have used group_by, so here's a hash-merge answer.

Letting the variable bookings equal your array of hashes, you can write the following.

keys_to_aggregate = [:price1, :price2]

bookings.each_with_object({}) { |g,h| h.update(g[:booking_ref]=>g) { |_,o,n|
  keys_to_aggregate.reduce(o) { |f,k| f.merge(k=>o[k] + n[k]) } } }.values
  #=> [{:booking_ref=>"w578383", :foo=>"bar", :price1=>1100, :price2=>70},
  #    {:booking_ref=>"r123523", :foo=>"bar", :price1=>699, :price2=>4}]

Note that before Hash#values at the end of the expression is evaluated we have the following.

bookings.each_with_object({}) { |g,h| h.update(g[:booking_ref]=>g) { |_,o,n|
  keys_to_aggregate.reduce(o) { |f,k| f.merge(k=>o[k] + n[k]) } } }
  #=> {"w578383"=>{:booking_ref=>"w578383", :foo=>"bar", :price1=>1100, :price2=>70},
  #    "r123523"=>{:booking_ref=>"r123523", :foo=>"bar", :price1=>699, :price2=>4}}

This uses the form of Hash#update that employs a block to determine the values of keys that are present in both hashes being merged. See the doc for details, particularly the definitions of the value-determining block's three variables (k, o and n). (I've substituted _ for k [the key] to signify that it is not used in the block calculation.)


问:
How to Call Ajax from HTML/JS to start PHP Function?
I'm working on a code that will show an alert when form is submitted and then redirect back to home page. If an empty form is submitted, I want to show an error alert. I realize that I cannot call PHP from onclick, and that I need to instead call a JS function that will start my PHP function. Can someone tell me if my PHP code is on the right track, and how to initialize the AJAX function? Trying to do this WITHOUT JQuery. Thanks!

html

```<code><form method="POST" action="contact.php">

<label for='message'>Leave a Message:</label> <br><br>
   <textarea rows="15" cols="45" name="message" id="message" ></textarea>
<br><br>
  <input type="submit" name='submit' value="send!" onclick="startajax()"/>

</form>
</code>```

and php

```<code><?PHP

$subject="New Message!";
$message=$_POST ["message"];

function leavemessage () {

if(!empty($_POST['message'])) {

echo '<script type="text/javascript">
function error(){
alert("Error!");
window.location.replace=(contact.html);}
</script>';

}

else

{

{mail ($email, $subject, $message, "From:".$from);}

echo '<script type="text/javascript">
function confirmation(){
alert("Message Sent!");
window.location.replace (index.html);}
</script>';

}

}

?>
</code>```

答:
You can do this with jquery ajax to complete your request like this:

HTML:

```<code><form method="POST" id="contact-form" onsubmit="return startajax()" >

<label for='message'>Leave a Message:</label> <br><br>
   <textarea rows="15" cols="45" name="message" id="message" ></textarea>
<br><br>
  <input type="submit" name='submit' value="send!"/>

</form>
</code>```

PHP:

```<code><?PHP

$subject="New Message!";
$message=$_POST ["message"];
if(!empty($message)) {
   //your email code here
   exit(json_encode(array('error' => 0, 'errorMessage' => '')));
} else {
   exit(json_encode(array('error' => 1, 'errorMessage' => 'Message is required')));

}

}

?>
</code>```

Jquery:

```<code><script>
    var startajax = function(){
        var url = 'contact.php';
        $.ajax({
            url : url,
            type : "POST",
            dataType : "JSON",
            data : $('#contact-form').serialize(),
            success : function(response) {
                if (response.error == 0) { // success
                    $('#contact-form')[0].reset();
                    alert('SUCCESS MESSAGE');
                } else { // error
                    alert(response.errorMessage);//form is invalid
                }
            }
        })
        return false;
    }

</script>
</code>```

Just make sure you have jquery library included to your page.

As per request, Without jQuery code below:

HTML:

```<code><form method="POST" id="contact-form" action="contact.php" >

<label for='message'>Leave a Message:</label> <br><br>
   <textarea rows="15" cols="45" name="message" id="message" ></textarea>
   <?php if (isset($_GET['error'])) { ?>
    <p style="color:red;">Message is required</p>
   <?php } ?>
<br><br>
  <input type="submit" name='submit' value="send!"/>

</form>
</code>```

PHP:

```<code><?PHP

    if (isset($_POST) && !empty($_POST)) {
        $subject="New Message!";
        $message=$_POST ["message"];
        if(!empty($message)) {
           //your email code here
           echo '<script>window.location.href="index.html"</script>';
        } else {

           echo '<script>window.location.href="index.html?error=1"</script>';
        }

        }
    }

    ?>
</code>```

Body:
I'm working on a code that will show an alert when form is submitted and then redirect back to home page. If an empty form is submitted, I want to show an error alert. I realize that I cannot call PHP from onclick, and that I need to instead call a JS function that will start my PHP function. Can someone tell me if my PHP code is on the right track, and how to initialize the AJAX function? Trying to do this WITHOUT JQuery. Thanks!

html

<form method="POST" action="contact.php">

Leave a Message:

   <textarea rows="15" cols="45" name="message" id="message" ></textarea>

  <input type="submit" name='submit' value="send!" onclick="startajax()"/>

</form>

and php

<?PHP

$subject="New Message!";
$message=$_POST ["message"];

function leavemessage () {

if(!empty($_POST['message'])) {

echo '';

}

else

{

{mail ($email, $subject, $message, "From:".$from);}

echo '';

}

}

?>

Body:
You can do this with jquery ajax to complete your request like this:

HTML:

<form method="POST" id="contact-form" onsubmit="return startajax()" >

<label for='message'>Leave a Message:</label> <br><br>
   <textarea rows="15" cols="45" name="message" id="message" ></textarea>
<br><br>
  <input type="submit" name='submit' value="send!"/>

</form>

PHP:

<?PHP

$subject="New Message!";
$message=$_POST ["message"];
if(!empty($message)) {
   //your email code here
   exit(json_encode(array('error' => 0, 'errorMessage' => '')));
} else {
   exit(json_encode(array('error' => 1, 'errorMessage' => 'Message is required')));

}

}

?>

Jquery:

<script>
    var startajax = function(){
        var url = 'contact.php';
        $.ajax({
            url : url,
            type : "POST",
            dataType : "JSON",
            data : $('#contact-form').serialize(),
            success : function(response) {
                if (response.error == 0) { // success
                    $('#contact-form')[0].reset();
                    alert('SUCCESS MESSAGE');
                } else { // error
                    alert(response.errorMessage);//form is invalid
                }
            }
        })
        return false;
    }

</script>

Just make sure you have jquery library included to your page.

As per request, Without jQuery code below:

HTML:

<form method="POST" id="contact-form" action="contact.php" >

<label for='message'>Leave a Message:</label> <br><br>
   <textarea rows="15" cols="45" name="message" id="message" ></textarea>
   <?php if (isset($_GET['error'])) { ?>
    <p style="color:red;">Message is required</p>
   <?php } ?>
<br><br>
  <input type="submit" name='submit' value="send!"/>

</form>

PHP:

<?PHP

    if (isset($_POST) && !empty($_POST)) {
        $subject="New Message!";
        $message=$_POST ["message"];
        if(!empty($message)) {
           //your email code here
           echo '<script>window.location.href="index.html"</script>';
        } else {

           echo '<script>window.location.href="index.html?error=1"</script>';
        }

        }
    }

    ?>


问:
Can C++ compilers cache the result of constexpr functions?
Disclaimer: This question is a bit complicated because it's several questions in one, but they're all related to the same sort of concept/issue.

Premise:
consexpr functions may only consist of a single return statement.

They can call other functions and use conditionals, but theoretically they should demonstrate functional purity, and thus the results should be cachable (by the compiler, at compile time) in some sort of map so that the compiler doesn't have to constantly re-evaluate the same function.

Question(s):
Is this assumption correct or is there something I haven't considered that makes it impossible to cache the result of a constexpr function?
If no, does this mean that constexpr functions have to be calculated every time they're used?

What about templates? Are constexpr values on templates cachable or do they also have to be recalculated each time?

答:
I don't believe constexpr functions are required to be pure - at least, not for all possible arguments. Consider:

```<code>#include <iostream>
#include <stdlib.h>

constexpr int f(int n) { return n == 0 ? 42 : rand(); }

template <int n> void g() {}

int main()
{
    g<f(0)>();  // OK
//    g<f(1)>();  // error
    std::cout << f(0) << ' ' << f(1) << ' ' << f(2);
}
</code>```

Output: 42 1804289383 846930886. Demo

Body:
I don't believe constexpr functions are required to be pure - at least, not for all possible arguments. Consider:

#include <iostream>
#include <stdlib.h>

constexpr int f(int n) { return n == 0 ? 42 : rand(); }

template <int n> void g() {}

int main()
{
    g<f(0)>();  // OK
//    g<f(1)>();  // error
    std::cout << f(0) << ' ' << f(1) << ' ' << f(2);
}

Output: 42 1804289383 846930886. Demo


问:
Cordova build returns missing plugin.xml
When i build my cordova project i get an warning message as:

Missing file:
  /home/vijay/workspace/Repos_temp/QuickTraq_Android/plugins/nl.x-services.plugins.toast/plugin.xml

Missing file:
  /home/vijay/workspace/Repos_temp/QuickTraq_Android/plugins/cordova-plugin-device-rotation-vector/plugin.xml

This happens when i add an plugin or remove an plugin also .

This happens just as a warning when i add a plugin or build the project but when i remove the plugin error occurs as

Error: ENOENT, no such file or directory
  '/home/vijay/workspace/Repos_temp/QuickTraq_Android/plugins/com.grumpysailor.cordova-plugin-device-rotation-vector/plugin.xml'
      at Object.fs.openSync (fs.js:439:18)
      at Object.fs.readFileSync (fs.js:290:15)
      at Object.module.exports.parseElementtreeSync (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/util/xml-helpers.js:121:27)
      at /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/util/dependencies.js:56:35
      at Array.forEach (native)
      at Object.module.exports.package.generateDependencyInfo (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/util/dependencies.js:53:45)
      at runUninstallPlatform (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/uninstall.js:218:53)
      at Function.module.exports.uninstallPlatform (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/uninstall.js:81:12)
      at /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/plugin.js:205:58
      at _fulfilled (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:787:54)

and my plugin remove failed .. Is there an way to resolve this ??

答:
Close all Windows that may touch upon the install.  Then try to install again.

W10:... I had an open Command Prompt open to an Android build output folder.  The install was unable to delete a file, which failed the install, until after I closed the Command Prompt window.


问:
Execute Python threads in small groups
I am trying to insert some number(100) of data sets into SQL server using python. I am using multi-threading to create 100 threads in a loop. All of them are starting at the same time and this is bogging down the database. I want to group my threads into set of 5 and once that group is done, I would like to start the next group of threads and so on. As I am new to python and multi-threading, any help would be highly appreciated.Please find my code below.</p>

```<code>for row in datasets:
        argument1=row[0]
        argument2=row[1]
        jobs=[]
        t = Thread(target=insertDataIntoSQLServer, args=(argument1,argument2,))
        jobs.append(t)
        t.start()
for t in jobs:
    t.join()
</code>```

答:
First note that your code doesn't work as you intended:  it sets jobs to an empty list every time through the loop, so after the loop is over you only join() the last thread created.

So repair that, by moving jobs=[] out of the loop.  After that, you can get exactly what you asked for by adding this after t.start():

```<code>if len(jobs) == 5:
    for t in jobs:
        t.join()
    jobs = []
</code>```

I'd personally use some kind of pool (as other answers suggest), but it's easy to directly get what you had in mind.

Title: Execute Python threads in small groups

Body:
I am trying to insert some number(100) of data sets into SQL server using python. I am using multi-threading to create 100 threads in a loop. All of them are starting at the same time and this is bogging down the database. I want to group my threads into set of 5 and once that group is done, I would like to start the next group of threads and so on. As I am new to python and multi-threading, any help would be highly appreciated.Please find my code below.

for row in datasets:
        argument1=row[0]
        argument2=row[1]
        jobs=[]
        t = Thread(target=insertDataIntoSQLServer, args=(argument1,argument2,))
        jobs.append(t)
        t.start()
for t in jobs:
    t.join()

Body:
First note that your code doesn't work as you intended:  it sets jobs to an empty list every time through the loop, so after the loop is over you only join() the last thread created.

So repair that, by moving jobs=[] out of the loop.  After that, you can get exactly what you asked for by adding this after t.start():

if len(jobs) == 5:
    for t in jobs:
        t.join()
    jobs = []

I'd personally use some kind of pool (as other answers suggest), but it's easy to directly get what you had in mind.


问:
Matlab Clamped Spline
I need to solve the question on the photo with the help of matlab What am I doing wrong? Are there some who can help? Very important to me.

```<code>clc;
clear;
format compact;
T=[0 3 5 8 13]
V=[0 225 383 623 993]
A=[75 77 80 74 72]
v_5=interp1(T,V,5);
a_5=interp1(T,A,5);
t_5=interp1(T,A,5);
x=0:3:13;
y=interp1(T,A,x,'spline');
plot(T,V,'o',x,y),title('speed vs distance ')
</code>```

答:
This is obviously a homework and it is not how things work in SO. You should first take a look at this link before asking such questions. However, I will give you a hint (first part of the question) and I guess you will be fine working the whole thing out by yourself.

You need to use regression to be able to estimate some values between the given observations though interpolation.
The function interp1 returns interpolated values of a 1-D function at specific query points using linear interpolation.

```<code> vq = interp1(x,v,xq)
</code>```

Vector x contains the sample points (Time in your case), and v contains the corresponding values, v(x) (distance or speed in your case). Vector xq contains the coordinates of the query points.

So you can find the position and speed of the car at t=10 as follows:

```<code>Time = [0 3 5 8 13];
Distance =[0 225 383 623 993];
Speed = [75 77 80 74 72];
t_10 = 10;                              % the query point
d_10 = interp1(Time,Distance,t_10)      % find the distance at t=10
v_10 = interp1(Time,Speed,t_10)         % find the speed at t=10
</code>```

It would result:

```<code>d_10 =

   771

v_10 =

   73.2000
</code>```

and you can confirm this on a plot as well:

Edit:

For a cubic spline you need to replace the interp1d with spline. Check the documentation here.

Title: Matlab Clamped Spline

Body:
I need to solve the question on the photo with the help of matlab What am I doing wrong? Are there some who can help? Very important to me.

clc;
clear;
format compact;
T=[0 3 5 8 13]
V=[0 225 383 623 993]
A=[75 77 80 74 72]
v_5=interp1(T,V,5);
a_5=interp1(T,A,5);
t_5=interp1(T,A,5);
x=0:3:13;
y=interp1(T,A,x,'spline');
plot(T,V,'o',x,y),title('speed vs distance ')

Body:
This is obviously a homework and it is not how things work in SO. You should first take a look at this link before asking such questions. However, I will give you a hint (first part of the question) and I guess you will be fine working the whole thing out by yourself.

You need to use regression to be able to estimate some values between the given observations though interpolation.
The function interp1 returns interpolated values of a 1-D function at specific query points using linear interpolation.

 vq = interp1(x,v,xq)

Vector x contains the sample points (Time in your case), and v contains the corresponding values, v(x) (distance or speed in your case). Vector xq contains the coordinates of the query points.

So you can find the position and speed of the car at t=10 as follows:

Time = [0 3 5 8 13];
Distance =[0 225 383 623 993];
Speed = [75 77 80 74 72];
t_10 = 10;                              % the query point
d_10 = interp1(Time,Distance,t_10)      % find the distance at t=10
v_10 = interp1(Time,Speed,t_10)         % find the speed at t=10

It would result:

d_10 =

   771

v_10 =

   73.2000

and you can confirm this on a plot as well:

Edit:

For a cubic spline you need to replace the interp1d with spline. Check the documentation here.


问:
How to create Entity dynamically in Objective-C?
I'm building an iPad application where I need user to create entity dynamically. I'm already having 3 entities which program uses.

Could you help me with code how to do it?

I want to understand the whole structure according to my understanding I have to create new managedObjectModel, add new entities and than merge it with existing one, is it correct?

答:
That's correct -- you'd create an array of NSEntityDescription objects, then call setEntities: on the new managed object model.  Then, finally, you'd merge that model with your built-in model.

But note that you can't change a model once it has been used to create a managed object context (or used for storage).  You'll need to create new storage and context after the model is changed.