问:
Java 8 Interface vs Abstract Class
I went through this question:
Interface with default methods vs Abstract class in Java 8

The following part is not clear to me:

The constraint on the default method is that it can be implemented
  only in the terms of calls to other interface methods, with no
  reference to a particular implementation's state. So the main use case
  is higher-level and convenience methods.

I tried creating objects of a concrete class (implementation) inside default method and invoked its instance method, it is working fine. i.e, I don't need to use Interface type as reference to the object.

Then what is meant by the quoted paragraph.

答:
Problem is that default methods can only "see" what is declared in the interface itself - not in the implementation class. Any state fields that are declared in the class that implements this interface are simply not accessible. But they can access static final fields of the interface:

```<code>interface test {
    static final int x = 3;

    public default void changeIt() {
        System.out.println(x); // this would work
        ++x; // this will fail
    }
}
</code>```

Title: Java 8 Interface vs Abstract Class

Body:
Problem is that default methods can only "see" what is declared in the interface itself - not in the implementation class. Any state fields that are declared in the class that implements this interface are simply not accessible. But they can access static final fields of the interface:

interface test {
    static final int x = 3;

    public default void changeIt() {
        System.out.println(x); // this would work
        ++x; // this will fail
    }
}


来源: stackexchange

问:
What does the WordPress "_e()" function do?
I have these all over my theme, and when if I delete them, there nothing happens to the theme. What does it do? Should I leave them in or are they unnecessary? I want to optimize my site to load faster, so this is why I'm asking.</p>

答:
Those are WordPress library function used on localization in Wordpress themes. Its recommended to use escapes function as much as possible in theme and plugins for safety.

__() = Return the translated string

  _e() = echo the translated string

  esc_html__() = Escapes & return the translation string use in HTML output

  esc_html_e() = Escapes & echo the translation string use in HTML output

  esc_attr__() = Escapes & return the translation string use in an attribute

  esc_attr_e() = Escapes & echo the translation string use in an attribute

  _n() = Retrieve the plural or single form based on the amount.

  _x() = Retrieve translated string with gettext context

  _ex() = echo translated string with gettext context

  esc_attr_x() = Escapes & return translated string with gettext context use in an attribute

  esc_html_x() = Escapes & return translated string with gettext context use in HTML output

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
C++ multiple interfaces inheritance and static_cast
In the following code:

Live

```<code>#include <iostream>
#include <thread>
#include <mutex>
#include <functional>

struct IView {
    virtual void setOnClick() = 0;
};
struct ITextView : IView {
    virtual void setText() = 0;
};
struct IButton : ITextView {
    virtual void setRadius() = 0;
};

struct View : IView {
    int i = 1;
    virtual void setOnClick() override {
        std::cout << "setting OnClick! i: " << i << std::endl;
    };
};

/// Works as is
/// But if make "TextView : View, ITextView" - have segfault on the run
struct TextView : ITextView, View {
    int j = 2;
    virtual void setText() override {
        std::cout << "setting text! i: " << i << " j: " << j << std::endl;
    };

    // forward IView
    virtual void setOnClick() override {
        View::setOnClick();
    }
};

int main() {
    TextView tv;

    void* ptr = &tv;    // I need to pass raw pointer, and then restore "interface" from it

    ITextView* itv = static_cast<ITextView*>(ptr);  // I don't need safety checks here
    itv->setOnClick();
    itv->setText();

    return 0;
}
</code>```

If I change TextViews inheritance order I'll have segfault on itv->setText(); call.

Why is it important? Can I use static_cast here, or I have UB here? As I understand dynamic_cast only required with virtual inheritance, and this, as I can tell, not that case.

答:
As it stands, you convert implicitly from TextView* to void*, then explicitly from void* to ITextView*. These conversions do not perform any pointer adjustment when casting from/to void*, so you end up with a pointer of type ITextView* which actually points to a TextView (not to its ITextView subobject!): undefined behaviour ensues.

The solution is to take care of always using the exact same type on both "sides" of the void*:

```<code>TextView tv;

void* ptr = static_cast<ITextView*>(&tv); // Adjust, then convert to void*

ITextView* itv = static_cast<ITextView*>(ptr);
</code>```

Body:
In the following code:

Live

#include <iostream>
#include <thread>
#include <mutex>
#include <functional>

struct IView {
    virtual void setOnClick() = 0;
};
struct ITextView : IView {
    virtual void setText() = 0;
};
struct IButton : ITextView {
    virtual void setRadius() = 0;
};

struct View : IView {
    int i = 1;
    virtual void setOnClick() override {
        std::cout << "setting OnClick! i: " << i << std::endl;
    };
};

/// Works as is
/// But if make "TextView : View, ITextView" - have segfault on the run
struct TextView : ITextView, View {
    int j = 2;
    virtual void setText() override {
        std::cout << "setting text! i: " << i << " j: " << j << std::endl;
    };

    // forward IView
    virtual void setOnClick() override {
        View::setOnClick();
    }
};

int main() {
    TextView tv;

    void* ptr = &tv;    // I need to pass raw pointer, and then restore "interface" from it

    ITextView* itv = static_cast<ITextView*>(ptr);  // I don't need safety checks here
    itv->setOnClick();
    itv->setText();

    return 0;
}

If I change TextViews inheritance order I'll have segfault on itv->setText(); call.

Why is it important? Can I use static_cast here, or I have UB here? As I understand dynamic_cast only required with virtual inheritance, and this, as I can tell, not that case.

Body:
As it stands, you convert implicitly from TextView* to void*, then explicitly from void* to ITextView*. These conversions do not perform any pointer adjustment when casting from/to void*, so you end up with a pointer of type ITextView* which actually points to a TextView (not to its ITextView subobject!): undefined behaviour ensues.

The solution is to take care of always using the exact same type on both "sides" of the void*:

TextView tv;

void* ptr = static_cast<ITextView*>(&tv); // Adjust, then convert to void*

ITextView* itv = static_cast<ITextView*>(ptr);


问:
Extract values only from an array to encode them in JSON using PHP
This has probably been asked many times but I can't find a solution for my case.

This is my array :

```<code>$request=Array (
        [0] => Array ( [staName] => Auditorium Stravinsky 2m2c )
        [1] => Array ( [staName] => Geneva Arena )
        [2] => Array ( [staName] => Les Docks )
        [3] => Array ( [staName] => Kheops )
    )
</code>```

And i need an output as follows as JSON:

```<code>"Auditorium Stravinsky 2m2c ","Geneva Arena","Les Docks","Kheops"
</code>```

My current code is as follows:

```<code>    foreach($request as $value)
    {
        $names[]=$value;
    }

    $jsonValue = json_encode(array_values($names));

    print_r($jsonValue);
</code>```

And my current output is as follows in JSON format:

```<code>[{"staName":"Auditorium Stravinsky 2m2c "},{"staName":"Geneva Arena"},{"staName":"Les Docks"},{"staName":"Kheops"}]
</code>```

How can i stop "staName " from being outputed?

Many thanks in advance and please be considerate of my post as this is only the second one I make on this site.

答:
```<code><?php

$request=Array (
        0 => Array ( 'staName' => 'Auditorium Stravinsky 2m2c' ) ,
        1 => Array ( 'staName' => 'Geneva Arena' ) ,
        2 => Array ( 'staName' => 'Les Docks' ) ,
        3 => Array ( 'staName' => 'Kheops' )
    );

$newArray=array();
for($i=0;$i<count($request);$i++){
    $newArray[$i]=$request[$i]['staName'];
}

$newArray=json_encode($newArray,true);
print_r($newArray);
</code>```

And the output is a merged json:

```<code>["Auditorium Stravinsky 2m2c","Geneva Arena","Les Docks","Kheops"]
</code>```

Body:
This has probably been asked many times but I can't find a solution for my case.

This is my array :

$request=Array (
        [0] => Array ( [staName] => Auditorium Stravinsky 2m2c )
        [1] => Array ( [staName] => Geneva Arena )
        [2] => Array ( [staName] => Les Docks )
        [3] => Array ( [staName] => Kheops )
    )

And i need an output as follows as JSON:

"Auditorium Stravinsky 2m2c ","Geneva Arena","Les Docks","Kheops"

My current code is as follows:

    foreach($request as $value)
    {
        $names[]=$value;
    }

    $jsonValue = json_encode(array_values($names));

    print_r($jsonValue);

And my current output is as follows in JSON format:

[{"staName":"Auditorium Stravinsky 2m2c "},{"staName":"Geneva Arena"},{"staName":"Les Docks"},{"staName":"Kheops"}]

How can i stop "staName " from being outputed?

Many thanks in advance and please be considerate of my post as this is only the second one I make on this site.

Body:
<?php

$request=Array (
        0 => Array ( 'staName' => 'Auditorium Stravinsky 2m2c' ) ,
        1 => Array ( 'staName' => 'Geneva Arena' ) ,
        2 => Array ( 'staName' => 'Les Docks' ) ,
        3 => Array ( 'staName' => 'Kheops' )
    );

$newArray=array();
for($i=0;$i<count($request);$i++){
    $newArray[$i]=$request[$i]['staName'];
}

$newArray=json_encode($newArray,true);
print_r($newArray);

And the output is a merged json:

["Auditorium Stravinsky 2m2c","Geneva Arena","Les Docks","Kheops"]


问:
Unable to send mail via php mail()
I am unable to send an email via php's mail function.

This is the error I receive.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in D:\inetpub\vhosts\southernbatteries.com\httpdocs\includes\utils.php on line 6
Array ( [0] => [1] => Could not send mail, please try later... )

What exactly does this mean ? Does it mean there is not mail server installed on my webserver ? Is it possible to use a different mail server. E.g Gmails mail server to send the mail ?

答:
You should run your own mailserver on your server. Most likely it's not started or not installed.

As I can see your are running it on windows it's most likely the later. You could try using your providers mail server. Or googles. But you need most likely a username and password for that.

ContentLicense: CC BY-SA 2.5

Title: Unable to send mail via php mail()


问:
NSFont(name:size:) not working for all fonts
I am trying to set the font and font size for an NSTextField.

For some fonts, this works as expected, but for other fonts, only the font is set, and the size is ignored (it is set to some small, default size).

The stringValue of the NSTextField is a string of Chinese characters, e.g. 花.

```<code>class ViewController: NSViewController {
    @IBOutlet weak var displayLabel: NSTextField!
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.displayLabel.font = NSFont(name: "Heiti TC Medium", size: CGFloat(128.0))
        ...
    }
    ....
}
</code>```

For the font "Heiti TC Medium", I can set the size, but for "BiauKai Ordinary", I just get the small, default size.

In the macOS Font Book app, I can set the size for both fonts, and that works as expected, so it should not be an issue with the font itself.

Update:

As it turns out, with the small font size, it's hard to see if the font actually changes. I think maybe I made a mistake in thinking they did.

The only safe way of dealing with the fonts, because you apparently don't get an error if the system can't identify the font, is to query the system for the font name, as pointed out in the link by Guy Kogus below.

答:
Getting the exact font name can be a pain sometimes. What I often do to debug this is put a breakpoint somewhere and see what fonts are available through the debugger, by calling:

```<code>(lldb) po UIFont.familyNames
</code>```

and then once you find the correct family, BiauKai (or whatever it's called in that last) get the exact names by calling

```<code>(lldb) po UIFont.fontNames(forFamilyName: "BiauKai")
</code>```

Body:
I am trying to set the font and font size for an NSTextField.

For some fonts, this works as expected, but for other fonts, only the font is set, and the size is ignored (it is set to some small, default size).

The stringValue of the NSTextField is a string of Chinese characters, e.g. 花.

class ViewController: NSViewController {
    @IBOutlet weak var displayLabel: NSTextField!
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.displayLabel.font = NSFont(name: "Heiti TC Medium", size: CGFloat(128.0))
        ...
    }
    ....
}

For the font "Heiti TC Medium", I can set the size, but for "BiauKai Ordinary", I just get the small, default size.

In the macOS Font Book app, I can set the size for both fonts, and that works as expected, so it should not be an issue with the font itself.

Update:

As it turns out, with the small font size, it's hard to see if the font actually changes. I think maybe I made a mistake in thinking they did.

The only safe way of dealing with the fonts, because you apparently don't get an error if the system can't identify the font, is to query the system for the font name, as pointed out in the link by Guy Kogus below.

Body:
Getting the exact font name can be a pain sometimes. What I often do to debug this is put a breakpoint somewhere and see what fonts are available through the debugger, by calling:

(lldb) po UIFont.familyNames

and then once you find the correct family, BiauKai (or whatever it's called in that last) get the exact names by calling

(lldb) po UIFont.fontNames(forFamilyName: "BiauKai")


问:
Type mismatch, expected ListBuffer[Any], actual ListBuffer[CustomClass]
I don't understand the title error knowing that for this function :

```<code>def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}
</code>```

called with these parameters :

```<code>myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)
</code>```

Am i obliged to call function like this :

```<code>myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)
</code>```

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

答:
If CustomObject and CustomClass are actually supposed to be the same (or CustomObject is a subtype of CustomClass), you may want to change the function to be generic:

```<code>def myFunction[A](objectList: ListBuffer[A], object: A) = ...
</code>```

Otherwise, the issue is that myFunction can put anything into a ListBuffer[Any], but if you pass a ListBuffer[CustomClass], you can only put values of type CustomClass into it. This explains why ListBuffer is invariant.

If myFunction isn't going to put anything into the Buffer, you can just use Seq (or even more general types), which is covariant. You will be able to pass a ListBuffer there because it extends Seq. Generally, it's a good policy to give the most general possible type to method arguments.

Body:
I don't understand the title error knowing that for this function :

def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}

called with these parameters :

myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)

Am i obliged to call function like this :

myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

Body:
If CustomObject and CustomClass are actually supposed to be the same (or CustomObject is a subtype of CustomClass), you may want to change the function to be generic:

def myFunction[A](objectList: ListBuffer[A], object: A) = ...

Otherwise, the issue is that myFunction can put anything into a ListBuffer[Any], but if you pass a ListBuffer[CustomClass], you can only put values of type CustomClass into it. This explains why ListBuffer is invariant.

If myFunction isn't going to put anything into the Buffer, you can just use Seq (or even more general types), which is covariant. You will be able to pass a ListBuffer there because it extends Seq. Generally, it's a good policy to give the most general possible type to method arguments.


问:
I have 2 tables ( unit , user ) each user can have many units, I am trying to return each user with it all units as json , using laravel
I am trying to do this:

```<code>$unitsPayments = Unit::leftJoin('uf_user', 'uf_unit.owner', '=', 'uf_user.id')
->select('uf_unit.code','uf_user.display_name','uf_unit.neighborhood',
         'uf_unit.id AS unit_id','uf_unit.owner AS unit_owner')->get();
</code>```

but it return the data separated like this.
I need to have first user and all it unit inside it

so at the end I will only have 2 nodes for users and each node will have 2 unit nodes

This is current JSON:

```<code>[
    {
        "code": "121",
        "display_name": "zal",
        "neighborhood": "wan",
        "unit_id": 49,
        "unit_owner": 17
    },
    {
        "code": "47",
        "display_name": "Ahmad",
        "neighborhood": "aim",
        "unit_id": 63,
        "unit_owner": 2
    },
    {
        "code": "21",
        "display_name": "Ahmad",
        "neighborhood": "wan",
        "unit_id": 64,
        "unit_owner": 2
    },
    {
        "code": "102",
        "display_name": "zal",
        "neighborhood": "war",
        "unit_id": 65,
        "unit_owner": 17
    }
]
</code>```

and this is how I need the data to look like:

```<code>[{
        "display_name": "zal",
        "unit_owner": 17,
        "units": {
            "code": "102",
            "neighborhood": "war",
            "unit_id": 65
        } {
            "code": "121",
            "neighborhood": "wan",
            "unit_id": 49
        }
    },
    {
        "display_name": "Ahmad",
        "unit_owner": 2,
        "units": {
            "code": "47",
            "neighborhood": "aim",
            "unit_id": 63,
        } {
            "code": "21",
            "neighborhood": "wan",
            "unit_id": 64,
        }
    }
]
</code>```

答:
You really should set up proper relationships using Eloquent: https://laravel.com/docs/5.5/eloquent-relationships

Your code will look like this:

```<code>$unitsPayments = User::with('units')->get();
</code>```

And in User class:

```<code>class User extends Model {
  public function units(){
    return $this->hasMany(Unit::class, 'owner');
  }
}
</code>```

Body:
I am trying to do this:

$unitsPayments = Unit::leftJoin('uf_user', 'uf_unit.owner', '=', 'uf_user.id')
->select('uf_unit.code','uf_user.display_name','uf_unit.neighborhood',
         'uf_unit.id AS unit_id','uf_unit.owner AS unit_owner')->get();

but it return the data separated like this.
I need to have first user and all it unit inside it

so at the end I will only have 2 nodes for users and each node will have 2 unit nodes

This is current JSON:

[
    {
        "code": "121",
        "display_name": "zal",
        "neighborhood": "wan",
        "unit_id": 49,
        "unit_owner": 17
    },
    {
        "code": "47",
        "display_name": "Ahmad",
        "neighborhood": "aim",
        "unit_id": 63,
        "unit_owner": 2
    },
    {
        "code": "21",
        "display_name": "Ahmad",
        "neighborhood": "wan",
        "unit_id": 64,
        "unit_owner": 2
    },
    {
        "code": "102",
        "display_name": "zal",
        "neighborhood": "war",
        "unit_id": 65,
        "unit_owner": 17
    }
]

and this is how I need the data to look like:

[{
        "display_name": "zal",
        "unit_owner": 17,
        "units": {
            "code": "102",
            "neighborhood": "war",
            "unit_id": 65
        } {
            "code": "121",
            "neighborhood": "wan",
            "unit_id": 49
        }
    },
    {
        "display_name": "Ahmad",
        "unit_owner": 2,
        "units": {
            "code": "47",
            "neighborhood": "aim",
            "unit_id": 63,
        } {
            "code": "21",
            "neighborhood": "wan",
            "unit_id": 64,
        }
    }
]

Body:
You really should set up proper relationships using Eloquent: https://laravel.com/docs/5.5/eloquent-relationships

Your code will look like this:

$unitsPayments = User::with('units')->get();

And in User class:

class User extends Model {
  public function units(){
    return $this->hasMany(Unit::class, 'owner');
  }
}


答:
If you want to use built-in mail(), you will need to talk to the server administrator. It is possible to use an external SMTP server on Windows, but it has to be specified in the php.ini settings, and PHP's built-in functions don't support SMTP authentication.

The usual way is to either use a local mail server that in turn can talk to a "real" SMTP server with authentication, or use a mailing package like SwiftMailer that can connect to a 3rd party SMTP server like GMail directly.

Title: Unable to send mail via php mail()

Body:
I am unable to send an email via php's mail function.

This is the error I receive.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in D:\inetpub\vhosts\southernbatteries.com\httpdocs\includes\utils.php on line 6
Array ( [0] => [1] => Could not send mail, please try later... )

What exactly does this mean ? Does it mean there is not mail server installed on my webserver ? Is it possible to use a different mail server. E.g Gmails mail server to send the mail ?


问:
WordPress Plugin Custom Fields not showing form
Ok, so I couldn't find a plugin to do what I wanted, so I set out to create my own.  I've done PHP coding before, though it's been some time.  Grabbed a bunch of code of the internet to modify and do what I want, threw it all together in a single class.

The goal at the moment is to have a new post type, with custom fields, and be able to edit those fields in the admin site.  What I have instead is a new post type, with a bunch of boxes with the right label, but no form being shown.

This may just be needing a second set of eyes on it, but I don't see what's wrong here.  The add_meta_box calls seem to be working, they're just not echoing anything in their callback functions.  What am I missing?  Any help is greatly appreciated.

If needed, whole repo is https://github.com/steev42/WrestleEFedManager; relevant file is copied below.

```<code><?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'Wrestleefedmanager_Federation' ) ) :
class Wrestleefedmanager_Federation {

    /**
     * Constructor
     */
    public function __construct() {
        // Hooking up our function to theme setup
        add_action( 'init',             array( $this, 'create_federation_post_type' ) );
        add_action( 'add_meta_boxes',   array( $this, 'initialize_federation_post_type') );
        add_action( 'save_post',        array( $this, 'save_fed') );
    }

    // Our custom post type function
    function create_federation_post_type() {

     $fedlabels = array(
        'name'                => _x( 'Federations', 'Post Type General Name'),
        'singular_name'       => _x( 'Federation', 'Post Type Singular Name'),
        'menu_name'           => __( 'Federations'),
        'parent_item_colon'   => __( 'Parent Fed'),
        'all_items'           => __( 'All Feds'),
        'view_item'           => __( 'View Fed'),
        'add_new_item'        => __( 'Add New Fed'),
        'add_new'             => __( 'Add New'),
        'edit_item'           => __( 'Edit Fed'),
        'update_item'         => __( 'Update Fed'),
        'search_items'        => __( 'Search Feds'),
        'not_found'           => __( 'Not Found'),
        'not_found_in_trash'  => __( 'Not found in Trash'),
    );

    $fedargs = array(
        'label'               => __( 'feds' ),
        'description'         => __( 'Federations' ),
        'labels'              => $fedlabels,
        // Features this CPT supports in Post Editor
        'supports'            => array( 'title', 'editor', 'author', ),
        // You can associate this CPT with a taxonomy or custom taxonomy.
        //'taxonomies'          => array( 'genres' ),
        /* A hierarchical CPT is like Pages and can have
        * Parent and child items. A non-hierarchical CPT
        * is like Posts.
        */
        'hierarchical'        => true,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
    );

        register_post_type( 'feds', $fedargs);
    }

    function initialize_federation_post_type() {
        /*
        add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null,
                      string $context = 'advanced', string $priority = 'default', array $callback_args = null )*/
        add_meta_box("abbreviation", "Abbreviation", "fed_abbr", "feds", "normal", "low");
        add_meta_box("founded", "Founded", "fed_founded", "feds", "side", "low");
        add_meta_box("closed", "Closed", "fed_closed", "feds", "side", "low");
        add_meta_box("parentfed", "Parent Federation", "fed_parent", "feds", "normal", "low");
        add_meta_box("logo", "Logo", "fed_logo", "feds", "normal", "low");
        add_meta_box("owner", "Owner", "fed_owner", "feds", "side", "low");
    }

    function fed_abbr(){
        global $post;
        $custom = get_post_custom($post->ID);
        $abbr = $custom["abbreviation"][0];
        ?>
        <label>Abbr:</label>
        <input name="fed_abbreviation" type="text" value="<?php echo $abbr; ?>" />
        <?php
        }

    function fed_founded(){
        global $post;
        $custom = get_post_custom($post->ID);
        $founded = $custom["founded"][0];
        ?>
        <label>Founded:</label>
        <input name="fed_founddate" value="<?php echo $founded; ?>" />
        <?php
    }

    function fed_closed(){
        global $post;
        $custom = get_post_custom($post->ID);
        $closed = $custom["closed"][0];
        ?>
        <label>Closed:</label>
        <input name="fed_closedate" value="<?php echo $closed; ?>" />
        <?php
    }

    function fed_parent(){
    }

    function fed_logo(){
    }

    function fed_owner(){
        global $post;
        $custom = get_post_custom($post->ID);
        $owner = $custom["owner"][0];
        ?>
        <label>Owner:</label>
        <input name="fed_owner" value="<?php echo $owner; ?>" />
        <?php
    }

    function save_fed(){
        global $post;

        update_post_meta($post->ID, "abbreviation", $_POST["fed_abbreviation"]);
        update_post_meta($post->ID, "founded", $_POST["fed_founddate"]);
        update_post_meta($post->ID, "closed", $_POST["fed_closedate"]);
        update_post_meta($post->ID, "owner", $_POST["fed_owner"]);
    }

}
endif;
</code>```

答:
Ok, so with a bit of trial and error and scouring the googles, I was able to make this work.

First off, because this in a class, the callbacks in the add_meta_box need the array ($this, <cb>) format rather than just the original string.

Secondly, instead of using the add_meta_boxes action callback, the args for register_post_type have their own option, which I used thusly: 'register_meta_box_cb' => array( $this, 'initialize_federation_post_type')

So, after getting that to work, and adding in a bit of code to get the fields to display in view mode, the file looks like this:

```<code><?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'Wrestleefedmanager_Federation' ) ) :
class Wrestleefedmanager_Federation {

    /**
     * Constructor
     */
    public function __construct() {
        // Hooking up our function to theme setup
        add_action( 'init',             array( $this, 'create_federation_post_type' ) );
        //add_action( 'add_meta_boxes',     array( $this, 'initialize_federation_post_type') );
        add_action( 'save_post',        array( $this, 'save_fed') );

        add_filter ('template_include', array($this, 'display_federation_template' ) );
    }

    // Our custom post type function
    function create_federation_post_type() {

     $fedlabels = array(
        'name'                => _x( 'Federations', 'Post Type General Name'),
        'singular_name'       => _x( 'Federation', 'Post Type Singular Name'),
        'menu_name'           => __( 'Federations'),
        'parent_item_colon'   => __( 'Parent Fed'),
        'all_items'           => __( 'All Feds'),
        'view_item'           => __( 'View Fed'),
        'add_new_item'        => __( 'Add New Fed'),
        'add_new'             => __( 'Add New'),
        'edit_item'           => __( 'Edit Fed'),
        'update_item'         => __( 'Update Fed'),
        'search_items'        => __( 'Search Feds'),
        'not_found'           => __( 'Not Found'),
        'not_found_in_trash'  => __( 'Not found in Trash'),
    );

    $fedargs = array(
        'label'               => __( 'Federations' ),
        'description'         => __( 'Wrestling Companies' ),
        'labels'              => $fedlabels,
        // Features this CPT supports in Post Editor
        'supports'            => array( 'title', 'editor', 'author', ),
        // You can associate this CPT with a taxonomy or custom taxonomy.
        //'taxonomies'          => array( 'genres' ),
        /* A hierarchical CPT is like Pages and can have
        * Parent and child items. A non-hierarchical CPT
        * is like Posts.
        */
        'hierarchical'        => true,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 17,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
        'register_meta_box_cb' => array( $this, 'initialize_federation_post_type'),
    );

        register_post_type( 'feds', $fedargs);
    }

    function initialize_federation_post_type() {
        /*
        add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null,
                      string $context = 'advanced', string $priority = 'default', array $callback_args = null )*/
        add_meta_box("abbreviation", "Abbreviation", array( $this, 'fed_abbr'), "feds", "normal", "low");
        add_meta_box("founded", "Founded", array( $this, 'fed_founded'), "feds", "side", "low");
        add_meta_box("closed", "Closed", array( $this, 'fed_closed'), "feds", "side", "low");
        add_meta_box("parentfed", "Parent Federation", array( $this, 'fed_parent'), "feds", "normal", "low");
        add_meta_box("logo", "Logo", array( $this, 'fed_logo'), "feds", "normal", "low");
        add_meta_box("owner", "Owner", array( $this, 'fed_owner'), "feds", "side", "low");
    }

    function fed_abbr(){
        global $post;
        $custom = get_post_custom($post->ID);
        $abbr = $custom["abbreviation"][0];
        ?>
        <label>Abbr:</label>
        <input name="fed_abbreviation" type="text" value="<?php echo $abbr; ?>" />
        <?php
        }

    function fed_founded(){
        global $post;
        $custom = get_post_custom($post->ID);
        $founded = $custom["founded"][0];
        ?>
        <label>Founded:</label>
        <input name="fed_founddate" value="<?php echo $founded; ?>" />
        <?php
    }

    function fed_closed(){
        global $post;
        $custom = get_post_custom($post->ID);
        $closed = $custom["closed"][0];
        ?>
        <label>Closed:</label>
        <input name="fed_closedate" value="<?php echo $closed; ?>" />
        <?php
    }

    function fed_parent(){
    }

    function fed_logo(){
    }

    function fed_owner(){
        global $post;
        $custom = get_post_custom($post->ID);
        $owner = $custom["owner"][0];
        ?>
        <label>Owner:</label>
        <input name="fed_owner" value="<?php echo $owner; ?>" />
        <?php
    }

    function save_fed(){
        global $post;

        update_post_meta($post->ID, "abbreviation", $_POST["fed_abbreviation"]);
        update_post_meta($post->ID, "founded", $_POST["fed_founddate"]);
        update_post_meta($post->ID, "closed", $_POST["fed_closedate"]);
        update_post_meta($post->ID, "owner", $_POST["fed_owner"]);
    }

    function display_federation_template ($template_path) {
        if ( get_post_type() == 'feds' ) {
        if ( is_single() ) {
            // checks if the file exists in the theme first,
            // otherwise serve the file from the plugin
            if ( $theme_file = locate_template( array ( 'single-feds.php' ) ) ) {
                $template_path = $theme_file;
            } else {
                $template_path = plugin_dir_path( __FILE__ ) . '/single-feds.php';
            }
        }
    }
    return $template_path;
    }

}
endif;
</code>```

Body:
Ok, so I couldn't find a plugin to do what I wanted, so I set out to create my own.  I've done PHP coding before, though it's been some time.  Grabbed a bunch of code of the internet to modify and do what I want, threw it all together in a single class.

The goal at the moment is to have a new post type, with custom fields, and be able to edit those fields in the admin site.  What I have instead is a new post type, with a bunch of boxes with the right label, but no form being shown.

This may just be needing a second set of eyes on it, but I don't see what's wrong here.  The add_meta_box calls seem to be working, they're just not echoing anything in their callback functions.  What am I missing?  Any help is greatly appreciated.

If needed, whole repo is https://github.com/steev42/WrestleEFedManager; relevant file is copied below.

<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'Wrestleefedmanager_Federation' ) ) :
class Wrestleefedmanager_Federation {

    /**
     * Constructor
     */
    public function __construct() {
        // Hooking up our function to theme setup
        add_action( 'init',             array( $this, 'create_federation_post_type' ) );
        add_action( 'add_meta_boxes',   array( $this, 'initialize_federation_post_type') );
        add_action( 'save_post',        array( $this, 'save_fed') );
    }

    // Our custom post type function
    function create_federation_post_type() {

     $fedlabels = array(
        'name'                => _x( 'Federations', 'Post Type General Name'),
        'singular_name'       => _x( 'Federation', 'Post Type Singular Name'),
        'menu_name'           => __( 'Federations'),
        'parent_item_colon'   => __( 'Parent Fed'),
        'all_items'           => __( 'All Feds'),
        'view_item'           => __( 'View Fed'),
        'add_new_item'        => __( 'Add New Fed'),
        'add_new'             => __( 'Add New'),
        'edit_item'           => __( 'Edit Fed'),
        'update_item'         => __( 'Update Fed'),
        'search_items'        => __( 'Search Feds'),
        'not_found'           => __( 'Not Found'),
        'not_found_in_trash'  => __( 'Not found in Trash'),
    );

    $fedargs = array(
        'label'               => __( 'feds' ),
        'description'         => __( 'Federations' ),
        'labels'              => $fedlabels,
        // Features this CPT supports in Post Editor
        'supports'            => array( 'title', 'editor', 'author', ),
        // You can associate this CPT with a taxonomy or custom taxonomy.
        //'taxonomies'          => array( 'genres' ),
        /* A hierarchical CPT is like Pages and can have
        * Parent and child items. A non-hierarchical CPT
        * is like Posts.
        */
        'hierarchical'        => true,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
    );

        register_post_type( 'feds', $fedargs);
    }

    function initialize_federation_post_type() {
        /*
        add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null,
                      string $context = 'advanced', string $priority = 'default', array $callback_args = null )*/
        add_meta_box("abbreviation", "Abbreviation", "fed_abbr", "feds", "normal", "low");
        add_meta_box("founded", "Founded", "fed_founded", "feds", "side", "low");
        add_meta_box("closed", "Closed", "fed_closed", "feds", "side", "low");
        add_meta_box("parentfed", "Parent Federation", "fed_parent", "feds", "normal", "low");
        add_meta_box("logo", "Logo", "fed_logo", "feds", "normal", "low");
        add_meta_box("owner", "Owner", "fed_owner", "feds", "side", "low");
    }

    function fed_abbr(){
        global $post;
        $custom = get_post_custom($post->ID);
        $abbr = $custom["abbreviation"][0];
        ?>
        Abbr:
        <input name="fed_abbreviation" type="text" value="<?php echo $abbr; ?>" />
        <?php
        }

    function fed_founded(){
        global $post;
        $custom = get_post_custom($post->ID);
        $founded = $custom["founded"][0];
        ?>
        Founded:
        <input name="fed_founddate" value="<?php echo $founded; ?>" />
        <?php
    }

    function fed_closed(){
        global $post;
        $custom = get_post_custom($post->ID);
        $closed = $custom["closed"][0];
        ?>
        Closed:
        <input name="fed_closedate" value="<?php echo $closed; ?>" />
        <?php
    }

    function fed_parent(){
    }

    function fed_logo(){
    }

    function fed_owner(){
        global $post;
        $custom = get_post_custom($post->ID);
        $owner = $custom["owner"][0];
        ?>
        Owner:
        <input name="fed_owner" value="<?php echo $owner; ?>" />
        <?php
    }

    function save_fed(){
        global $post;

        update_post_meta($post->ID, "abbreviation", $_POST["fed_abbreviation"]);
        update_post_meta($post->ID, "founded", $_POST["fed_founddate"]);
        update_post_meta($post->ID, "closed", $_POST["fed_closedate"]);
        update_post_meta($post->ID, "owner", $_POST["fed_owner"]);
    }

}
endif;

Body:
Ok, so with a bit of trial and error and scouring the googles, I was able to make this work.

First off, because this in a class, the callbacks in the add_meta_box need the array ($this, <cb>) format rather than just the original string.

Secondly, instead of using the add_meta_boxes action callback, the args for register_post_type have their own option, which I used thusly: 'register_meta_box_cb' => array( $this, 'initialize_federation_post_type')

So, after getting that to work, and adding in a bit of code to get the fields to display in view mode, the file looks like this:

<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'Wrestleefedmanager_Federation' ) ) :
class Wrestleefedmanager_Federation {

    /**
     * Constructor
     */
    public function __construct() {
        // Hooking up our function to theme setup
        add_action( 'init',             array( $this, 'create_federation_post_type' ) );
        //add_action( 'add_meta_boxes',     array( $this, 'initialize_federation_post_type') );
        add_action( 'save_post',        array( $this, 'save_fed') );

        add_filter ('template_include', array($this, 'display_federation_template' ) );
    }

    // Our custom post type function
    function create_federation_post_type() {

     $fedlabels = array(
        'name'                => _x( 'Federations', 'Post Type General Name'),
        'singular_name'       => _x( 'Federation', 'Post Type Singular Name'),
        'menu_name'           => __( 'Federations'),
        'parent_item_colon'   => __( 'Parent Fed'),
        'all_items'           => __( 'All Feds'),
        'view_item'           => __( 'View Fed'),
        'add_new_item'        => __( 'Add New Fed'),
        'add_new'             => __( 'Add New'),
        'edit_item'           => __( 'Edit Fed'),
        'update_item'         => __( 'Update Fed'),
        'search_items'        => __( 'Search Feds'),
        'not_found'           => __( 'Not Found'),
        'not_found_in_trash'  => __( 'Not found in Trash'),
    );

    $fedargs = array(
        'label'               => __( 'Federations' ),
        'description'         => __( 'Wrestling Companies' ),
        'labels'              => $fedlabels,
        // Features this CPT supports in Post Editor
        'supports'            => array( 'title', 'editor', 'author', ),
        // You can associate this CPT with a taxonomy or custom taxonomy.
        //'taxonomies'          => array( 'genres' ),
        /* A hierarchical CPT is like Pages and can have
        * Parent and child items. A non-hierarchical CPT
        * is like Posts.
        */
        'hierarchical'        => true,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 17,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
        'register_meta_box_cb' => array( $this, 'initialize_federation_post_type'),
    );

        register_post_type( 'feds', $fedargs);
    }

    function initialize_federation_post_type() {
        /*
        add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null,
                      string $context = 'advanced', string $priority = 'default', array $callback_args = null )*/
        add_meta_box("abbreviation", "Abbreviation", array( $this, 'fed_abbr'), "feds", "normal", "low");
        add_meta_box("founded", "Founded", array( $this, 'fed_founded'), "feds", "side", "low");
        add_meta_box("closed", "Closed", array( $this, 'fed_closed'), "feds", "side", "low");
        add_meta_box("parentfed", "Parent Federation", array( $this, 'fed_parent'), "feds", "normal", "low");
        add_meta_box("logo", "Logo", array( $this, 'fed_logo'), "feds", "normal", "low");
        add_meta_box("owner", "Owner", array( $this, 'fed_owner'), "feds", "side", "low");
    }

    function fed_abbr(){
        global $post;
        $custom = get_post_custom($post->ID);
        $abbr = $custom["abbreviation"][0];
        ?>
        <label>Abbr:</label>
        <input name="fed_abbreviation" type="text" value="<?php echo $abbr; ?>" />
        <?php
        }

    function fed_founded(){
        global $post;
        $custom = get_post_custom($post->ID);
        $founded = $custom["founded"][0];
        ?>
        <label>Founded:</label>
        <input name="fed_founddate" value="<?php echo $founded; ?>" />
        <?php
    }

    function fed_closed(){
        global $post;
        $custom = get_post_custom($post->ID);
        $closed = $custom["closed"][0];
        ?>
        <label>Closed:</label>
        <input name="fed_closedate" value="<?php echo $closed; ?>" />
        <?php
    }

    function fed_parent(){
    }

    function fed_logo(){
    }

    function fed_owner(){
        global $post;
        $custom = get_post_custom($post->ID);
        $owner = $custom["owner"][0];
        ?>
        <label>Owner:</label>
        <input name="fed_owner" value="<?php echo $owner; ?>" />
        <?php
    }

    function save_fed(){
        global $post;

        update_post_meta($post->ID, "abbreviation", $_POST["fed_abbreviation"]);
        update_post_meta($post->ID, "founded", $_POST["fed_founddate"]);
        update_post_meta($post->ID, "closed", $_POST["fed_closedate"]);
        update_post_meta($post->ID, "owner", $_POST["fed_owner"]);
    }

    function display_federation_template ($template_path) {
        if ( get_post_type() == 'feds' ) {
        if ( is_single() ) {
            // checks if the file exists in the theme first,
            // otherwise serve the file from the plugin
            if ( $theme_file = locate_template( array ( 'single-feds.php' ) ) ) {
                $template_path = $theme_file;
            } else {
                $template_path = plugin_dir_path( __FILE__ ) . '/single-feds.php';
            }
        }
    }
    return $template_path;
    }

}
endif;


问:
Parsing XML data in PHP array
I have this format of xml which is created automatically and was wondering how to iterate through it and save data into mysql

```<code><sales>

  <site_id="000001" sale_id="80" end_date="20170826" end_time="112420" />

  <site_id="000002" sale_id="81" end_date="20170828" end_time="101001" />

  <site_id="000003" sale_id="82" end_date="20170828" end_time="101001" />

</sales>
</code>```

I am okay with inserting into database, however it is the iteration and capturing in a variable that I am kind of stuck with

答:
If you can't edit the source you can use regex:

```<code><?php
$xml = <<<XML
<sales>

  <site_id="000001" sale_id="80" end_date="20170826" end_time="112420" />

  <site_id="000002" sale_id="81" end_date="20170828" end_time="101001" />

  <site_id="000003" sale_id="82" end_date="20170828" end_time="101001" />

</sales>
XML;

$lines = preg_split("/\n/", $xml);

$results = array();
foreach($lines as $line)
{
    $line = trim($line);
    if(preg_match("/^<[^$]+\ \/>$/", $line))
    {
        preg_match_all("/([^=<\s]+)=\"([^\"]+)\"/", $line, $m);
        $result = array();
        foreach($m as $n)
        {
            $count = count($n);
            for($i=0;$i<$count;$i++)
                $result[$m[1][$i]] = $m[2][$i];
        }
        $results[] = $result;
    }
}

print_r($results);
</code>```

PD: KILL THE XML SOURCE DEVELOPER

Title: Parsing XML data in PHP array

Body:
I have this format of xml which is created automatically and was wondering how to iterate through it and save data into mysql

<sales>

  <site_id="000001" sale_id="80" end_date="20170826" end_time="112420" />

  <site_id="000002" sale_id="81" end_date="20170828" end_time="101001" />

  <site_id="000003" sale_id="82" end_date="20170828" end_time="101001" />

</sales>

I am okay with inserting into database, however it is the iteration and capturing in a variable that I am kind of stuck with

Body:
If you can't edit the source you can use regex:

<?php
$xml = <<<XML
<sales>

  <site_id="000001" sale_id="80" end_date="20170826" end_time="112420" />

  <site_id="000002" sale_id="81" end_date="20170828" end_time="101001" />

  <site_id="000003" sale_id="82" end_date="20170828" end_time="101001" />

</sales>
XML;

$lines = preg_split("/\n/", $xml);

$results = array();
foreach($lines as $line)
{
    $line = trim($line);
    if(preg_match("/^<[^$]+\ \/>$/", $line))
    {
        preg_match_all("/([^=<\s]+)=\"([^\"]+)\"/", $line, $m);
        $result = array();
        foreach($m as $n)
        {
            $count = count($n);
            for($i=0;$i<$count;$i++)
                $result[$m[1][$i]] = $m[2][$i];
        }
        $results[] = $result;
    }
}

print_r($results);

PD: KILL THE XML SOURCE DEVELOPER


问:
Backup repository size is much bigger than indices size
I have an Elasticsearch backup per hour, after about 370 times of backup (about 15 days) , my backup repository is more than 15G !!! But the total indices size is just about 500M !! Elasticsearch is incremental backup, but 15G VS 500M , the difference is so huge ! I wonder whether it is normal with so big different size between indices and backup repository ?

Is it caused by my frequent backup (hourly) ? I use the hourly backup in cluster 1 and hourly restore in cluster 2 to keep two ES clusters data same real time .

I am using Elasticsearch backup API to backup

setting repo:
curl -XPUT "http://IP:9200/_snapshot/backup" -d "{\"type\": \"fs\",\"settings\": {\"compress\" : true,\"location\": \"backup\"}}"

backup :
CURTIME=date +"%Y-%m-%d %H:%M:%S"
BKTIME=${CURTIME//[- :]/}
curl -XPUT "http://IP:9200/snapshot/backup/snapshot$BKTIME?wait_for_completion=true"

My Elasticsearch settings : 2 nodes , 12 shard/node , 2 indices , fs type of backup to store snapshots to NAS

in Elasticsearch data directory , the indices size :

node1 indices size :
[root@esnode1 indices]$ du -sh

307M .

node2 indices size
[root@esnode2 indices]$ du -sh

238M .

[root@esnode1 indices]$ du -lh

8.0K    ./index1/10/translog
8.0K    ./index1/10/_state
2.9M    ./index1/10/index
2.9M    ./index1/10
12K     ./index1/5/translog
8.0K    ./index1/5/_state
1.5M    ./index1/5/index
1.5M    ./index1/5
8.0K    ./index1/4/translog
8.0K    ./index1/4/_state
2.9M    ./index1/4/index
2.9M    ./index1/4
8.0K    ./index1/_state
8.0K    ./index1/7/translog
8.0K    ./index1/7/_state
2.9M    ./index1/7/index
2.9M    ./index1/7
8.0K    ./index1/1/translog
8.0K    ./index1/1/_state
2.9M    ./index1/1/index
2.9M    ./index1/1
8.0K    ./index1/2/translog
8.0K    ./index1/2/_state
2.9M    ./index1/2/index
2.9M    ./index1/2
8.0K    ./index1/6/translog
8.0K    ./index1/6/_state
3.0M    ./index1/6/index
3.0M    ./index1/6
8.0K    ./index1/0/translog
8.0K    ./index1/0/_state
1.5M    ./index1/0/index
1.5M    ./index1/0
8.0K    ./index1/8/translog
8.0K    ./index1/8/_state
1.5M    ./index1/8/index
1.5M    ./index1/8
8.0K    ./index1/11/translog
8.0K    ./index1/11/_state
2.9M    ./index1/11/index
2.9M    ./index1/11
12K     ./index1/9/translog
8.0K    ./index1/9/_state
3.0M    ./index1/9/index
3.0M    ./index1/9
8.0K    ./index1/3/translog
8.0K    ./index1/3/_state
3.0M    ./index1/3/index
3.0M    ./index1/3
31M     ./index1
16K     ./index2/10/translog
8.0K    ./index2/10/_state
16M     ./index2/10/index
16M     ./index2/10
36K     ./index2/5/translog
8.0K    ./index2/5/_state
43M     ./index2/5/index
43M     ./index2/5
20K     ./index2/4/translog
8.0K    ./index2/4/_state
17M     ./index2/4/index
18M     ./index2/4
8.0K    ./index2/_state
40K     ./index2/7/translog
8.0K    ./index2/7/_state
32M     ./index2/7/index
32M     ./index2/7
68K     ./index2/1/translog
8.0K    ./index2/1/_state
21M     ./index2/1/index
21M     ./index2/1
64K     ./index2/2/translog
8.0K    ./index2/2/_state
19M     ./index2/2/index
19M     ./index2/2
116K    ./index2/6/translog
8.0K    ./index2/6/_state
22M     ./index2/6/index
22M     ./index2/6
24K     ./index2/0/translog
8.0K    ./index2/0/_state
17M     ./index2/0/index
17M     ./index2/0
128K    ./index2/8/translog
8.0K    ./index2/8/_state
34M     ./index2/8/index
34M     ./index2/8
72K     ./index2/11/translog
8.0K    ./index2/11/_state
20M     ./index2/11/index
20M     ./index2/11
88K     ./index2/9/translog
8.0K    ./index2/9/_state
22M     ./index2/9/index
22M     ./index2/9
76K     ./index2/3/translog
8.0K    ./index2/3/_state
16M     ./index2/3/index
16M     ./index2/3
277M    ./index2
307M    .

in backup repository , the size :
[root@esnode1 backup]$ du -lh

114M ./backup/indices/index1/0

112M ./backup/indices/index1/5

114M ./backup/indices/index1/11

114M ./backup/indices/index1/10

111M ./backup/indices/index1/8

116M ./backup/indices/index1/4

120M ./backup/indices/index1/9

118M ./backup/indices/index1/3

114M ./backup/indices/index1/2

115M ./backup/indices/index1/7

115M ./backup/indices/index1/1

112M ./backup/indices/index1/6

1.4G ./backup/indices/index1

747M ./backup/indices/index2/0

1.6G ./backup/indices/index2/5

887M ./backup/indices/index2/11

743M ./backup/indices/index2/10

2.1G ./backup/indices/index2/8

801M ./backup/indices/index2/4

1.3G ./backup/indices/index2/9

878M ./backup/indices/index2/3

951M ./backup/indices/index2/2

1.2G ./backup/indices/index2/7

953M ./backup/indices/index2/1

943M ./backup/indices/index2/6

13G ./backup/indices/index2

15G ./backup/indices

15G ./backup

1.1M ./backuplogs

15G .

======
https://www.elastic.co/blog/introducing-snapshot-restore
Both backup and restore operations are incremental, which means that only files that changed since the last snapshot will be copied into the repository or restored into an index. Incremental snapshots allow performing the snapshot operation as frequently as needed without too much disk space overhead. Users can now easily create a snapshot before upgrade or a risky change in the cluster and quickly rollback to the previous index state if things go wrong. The snapshot/restore mechanism can be also used to synchronize data between a “hot” cluster and a remote, “cold” backup cluster in a different geographic region for fast disaster recovery.

From the above , my case is really an issue , Can anyone help me ? Thanks in advance !

答:
Snapshot and restore works at the segment level it is very important information that isn't mentioned in Elastic "Snapshot And Restore" documentation.
I reported this to Elastic and asked if they can update the documentation.</p>


问:
Validating Bootstrap date-time picker in Laravel request
I am using Bootstrap datetime picker and I am trying to validate the date in my controller but it always gives me an error saying the format is not right!.

However I can create a new Carbon date object from the request data just fine but I cannot validate the request object using the same format.

This throws an error saying the from does not match format d M Y - H:i

```<code>$request->validate([
            'from' => 'date_format:"d M Y - H:i"|required|before:till',
            'till' => 'date_format:"d M Y - H:i"|required|after:from'
    ]);
</code>```

But this code works, if I use the data without any validation.

```<code>$ride->from = Carbon::createFromFormat('d M Y - H:i', $request->from)->toDateTimeString();
$ride->till = Carbon::createFromFormat('d M Y - H:i', $request->till)->toDateTimeString();
</code>```

Note:
The bootstrap dateTimePicker has format: "dd MM yyyy - hh:ii" but I understand javascript format differs from php format.

What is going wrong here?

Edit: These are the input dates obtained from dumping the request object.

```<code>  "from" => "16 November 2017 - 14:10"
  "till" => "06 November 2017 - 12:00"
</code>```

答:
To be honest you don't need to watch the date formats. Totally unnecessary. I suggest you do something like this:

```<code>$fromDate = Carbon::parse($request->get('from'));
$toDate = Carbon::parse($request->get('to'));
</code>```

Now the above will allow you to compare the dates for conditions such as:

Check whether you have passed a valid date.

Start date should not be greater than to date.

To Date should not be less than start date.

Then you can do something like:

```<code>if (($startDate === false) || ($toDate === false)) {
    // return error
}

// Check start date is greater than to date
if ($startDate->gt($toDate)) {
}

// Check to date is not less than to date
if ($toDate->lt($toDate)) {
}
</code>```

As long as you are passing date in a correct format, this should be enough. No need for you to do validation on date format.

Body:
I am using Bootstrap datetime picker and I am trying to validate the date in my controller but it always gives me an error saying the format is not right!.

However I can create a new Carbon date object from the request data just fine but I cannot validate the request object using the same format.

This throws an error saying the from does not match format d M Y - H:i

$request->validate([
            'from' => 'date_format:"d M Y - H:i"|required|before:till',
            'till' => 'date_format:"d M Y - H:i"|required|after:from'
    ]);

But this code works, if I use the data without any validation.

$ride->from = Carbon::createFromFormat('d M Y - H:i', $request->from)->toDateTimeString();
$ride->till = Carbon::createFromFormat('d M Y - H:i', $request->till)->toDateTimeString();

Note:
The bootstrap dateTimePicker has format: "dd MM yyyy - hh:ii" but I understand javascript format differs from php format.

What is going wrong here?

Edit: These are the input dates obtained from dumping the request object.

  "from" => "16 November 2017 - 14:10"
  "till" => "06 November 2017 - 12:00"

Body:
To be honest you don't need to watch the date formats. Totally unnecessary. I suggest you do something like this:

$fromDate = Carbon::parse($request->get('from'));
$toDate = Carbon::parse($request->get('to'));

Now the above will allow you to compare the dates for conditions such as:

Check whether you have passed a valid date.

Start date should not be greater than to date.

To Date should not be less than start date.

Then you can do something like:

if (($startDate === false) || ($toDate === false)) {
    // return error
}

// Check start date is greater than to date
if ($startDate->gt($toDate)) {
}

// Check to date is not less than to date
if ($toDate->lt($toDate)) {
}

As long as you are passing date in a correct format, this should be enough. No need for you to do validation on date format.


问:
AndroidPlot: XYPlot How to make Bars with rounded corners
I am working with AndroidPlot since about one year to display different Diagrams in my app.
Now I am working with BarCharts, the charts are finished but how can I make corners rounded?

I found some results for lines:
How to make line with rounded (smooth) corners with AndroidPlot

I tried already:

```<code>BarFormatter formatter1,formatter2, formatter3;
formatter1.getBorderPaint().setStrokeJoin(Paint.Join.ROUND);
formatter1.getFillPaint().setStrokeJoin(Paint.Join.ROUND);
</code>```

doesn't seems to have any impact.

then I tried:

```<code>XYPlot plot; //Initialized with UI-Diagrammm above
...
plot.setBorderStyle(XYPlot.BorderStyle.ROUNDED,5f,5f);
</code>```

Does anyone had the problem already and got an answer how to do this.

Thanks for Help,

Franzi

答:
Bars are rendered by Androidplot's BarRenderer class which uses the Canvas.drawRect(...) method to draw individual bars.  In order to get rounded edges it would either need to call Canvas.drawRoundRect or possibly even better, draw each bar as a path using Path.lineTo(...) and Path.arcTo(...) methods so that only the top of the bars are rounded.  This functionality unfortunately does not exist yet but you could open a feature request if you want.

Or you could implement it yourself by creating a custom renderer that extends  BarRenderer and overriding drawBar(...). Documentation available here

Body:
I am working with AndroidPlot since about one year to display different Diagrams in my app.
Now I am working with BarCharts, the charts are finished but how can I make corners rounded?

I found some results for lines:
How to make line with rounded (smooth) corners with AndroidPlot

I tried already:

BarFormatter formatter1,formatter2, formatter3;
formatter1.getBorderPaint().setStrokeJoin(Paint.Join.ROUND);
formatter1.getFillPaint().setStrokeJoin(Paint.Join.ROUND);

doesn't seems to have any impact.

then I tried:

XYPlot plot; //Initialized with UI-Diagrammm above
...
plot.setBorderStyle(XYPlot.BorderStyle.ROUNDED,5f,5f);

Does anyone had the problem already and got an answer how to do this.

Thanks for Help,

Franzi


问:
how can i show an irrational number to 100 decimal places in python?
I am trying to find the square root of 2 to 100 decimal places, but it only shows to like 10 by default, how can I change this?</p>

Body:
decimal module comes in handy.

>>> from decimal import *
>>> getcontext().prec = 100
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')


问:
Can't subscribe to server-sent event using Jersey and Tomcat 7
I am deploying Server-Sent-Event resource with jersey 2.41 / Java 7 / tomcat 7.

I am getting error as

Dec 16, 2013 4:04:40 AM org.apache.catalina.core.StandardWrapperValve
  invoke SEVERE: Servlet.service() for servlet [ServletAdaptor] in
  context with path [/trackapp] threw exception
  [java.lang.UnsupportedOperationException: Asynchronous processing not
  supported on Servlet 2.x container.] with root cause
  java.lang.UnsupportedOperationException: Asynchronous processing not
  supported on Servlet 2.x container.   at
  org.glassfish.jersey.servlet.WebComponent$3.suspend(WebComponent.java:123)
    at
  org.glassfish.jersey.servlet.internal.ResponseWriter.suspend(ResponseWriter.java:109)
    at
  org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:619)
    at
  org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:381)
    at
  org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:371)
    at
  org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:262)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)     at
  org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)  at
  org.glassfish.jersey.internal.Errors.process(Errors.java:315)     at
  org.glassfish.jersey.internal.Errors.process(Errors.java:297)     at
  org.glassfish.jersey.internal.Errors.process(Errors.java:267)     at
  org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
    at
  org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
    at
  org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:983)
    at
  org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:361)
    at
  org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at
  org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at
  org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at
  org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at
  org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
    at
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at
  org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

my Resource

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String broadcastMessage(String message) {
    OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
    OutboundEvent event = eventBuilder.name("message")
        .mediaType(MediaType.TEXT_PLAIN_TYPE)
        .data(String.class, message)
        .build();

    broadcaster.broadcast(event);
    System.out.println("broadcasting listen [" +message+ "]");

    return "Message was '" + message + "' broadcast.";
}

@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
@Path("/listen")
public EventOutput listenToBroadcast() {
    System.out.println("will listen");
    final EventOutput eventOutput = new EventOutput();
    this.broadcaster.add(eventOutput);
    return eventOutput;
}
```

<p>web.xml</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="false">
    <servlet>
        <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>
            org.glassfish.jersey.servlet.ServletContainer
        </servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>net.jigarshah.mse.tracker</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

</web-app>
</code>```

client JS

test

```

答:
I had the same trouble, my issue was that I used the wrong jersey servlet implementation. Add to replace

```<code><dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet-core</artifactId>
</dependency>
</code>```

by (note the missing -core)

```<code><dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet</artifactId>
</dependency>
</code>```

Body:
I am deploying Server-Sent-Event resource with jersey 2.41 / Java 7 / tomcat 7.

I am getting error as

Dec 16, 2013 4:04:40 AM org.apache.catalina.core.StandardWrapperValve
  invoke SEVERE: Servlet.service() for servlet [ServletAdaptor] in
  context with path [/trackapp] threw exception
  [java.lang.UnsupportedOperationException: Asynchronous processing not
  supported on Servlet 2.x container.] with root cause
  java.lang.UnsupportedOperationException: Asynchronous processing not
  supported on Servlet 2.x container.   at
  org.glassfish.jersey.servlet.WebComponent$3.suspend(WebComponent.java:123)
    at
  org.glassfish.jersey.servlet.internal.ResponseWriter.suspend(ResponseWriter.java:109)
    at
  org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:619)
    at
  org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:381)
    at
  org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:371)
    at
  org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:262)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)     at
  org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)  at
  org.glassfish.jersey.internal.Errors.process(Errors.java:315)     at
  org.glassfish.jersey.internal.Errors.process(Errors.java:297)     at
  org.glassfish.jersey.internal.Errors.process(Errors.java:267)     at
  org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
    at
  org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
    at
  org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:983)
    at
  org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:361)
    at
  org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at
  org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at
  org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at
  org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at
  org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
    at
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at
  org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

my Resource

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String broadcastMessage(String message) {
    OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
    OutboundEvent event = eventBuilder.name("message")
        .mediaType(MediaType.TEXT_PLAIN_TYPE)
        .data(String.class, message)
        .build();

    broadcaster.broadcast(event);
    System.out.println("broadcasting listen [" +message+ "]");

    return "Message was '" + message + "' broadcast.";
}

@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
@Path("/listen")
public EventOutput listenToBroadcast() {
    System.out.println("will listen");
    final EventOutput eventOutput = new EventOutput();
    this.broadcaster.add(eventOutput);
    return eventOutput;
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="false">
    <servlet>
        <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>
            org.glassfish.jersey.servlet.ServletContainer
        </servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>net.jigarshah.mse.tracker</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

</web-app>

client JS

test

Body:
I had the same trouble, my issue was that I used the wrong jersey servlet implementation. Add to replace

<dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet-core</artifactId>
</dependency>

by (note the missing -core)

<dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet</artifactId>
</dependency>


问:
House price prediction using Neural Network- network not learning
I am using pybrain to predict house prices in the house price dataset. I downloaded the dataset from below link:
https://www.kaggle.com/apratim87/housingdata/data

I picked 6 columns to predict the price
    'bedrooms','bathrooms','sqft_living','sqft_lot','floors','zipcode'

I took a neural network with 6 input units,1 hidden layer with 3 neurons and 1 unit in the output.

I have normalized the data. Code is as below:

```<code> house_df = pd.read_csv("kc_house_data.csv")
 print(house_df.head())
df = house_df.dropna(axis=0)
df = df[(df != 0).all(1)]
df.reset_index(drop=True,inplace=True)
X_org=house_df[['bedrooms','bathrooms','sqft_living','sqft_lot','floors','zipcode']]
y_org=house_df[['price']]

scaler = Normalizer().fit(X_org)
X = scaler.transform(X_org)
target_scaler = preprocessing.MinMaxScaler()
y=target_scaler.fit_transform(y_org)

ds=SupervisedDataSet(X.shape[1],y.shape[1])
for i in range(len(X)):
    ds.addSample(X.iloc[i,:].values,y.iloc[i,:].values)

train,rest=ds.splitWithProportion(0.60)
test,validation=rest.splitWithProportion(0.50)

print('Training Set Size='+str(len(train)))
print('Test Set Size='+str(len(test)))
print('Validation Set Size='+str(len(validation)))

#creating a neural network
def buildNN(invar,hidden,out):
    net=buildNetwork(invar,hidden,out,hiddenclass=SigmoidLayer,outclass=SoftmaxLayer)
    trainer=BackpropTrainer(net,dataset=train,momentum=0.1,verbose=True,weightdecay=0.01)
    trn_err,val_err=trainer.trainUntilConvergence(dataset=train,maxEpochs=50)

    #trainer.trainOnDataset(trndata,500)
    tst,=plt.plot(trn_err,'b',label='Test Error')
    vali,=plt.plot(val_err,'r',label='Validation Error')
    plt.legend(handles=[tst, vali])
    plt.ylabel('Error')
    plt.xlabel('Number of Epochs')
    plt.show()
     #testing it on test data
     out=net.activateOnDataset(test).argmax(axis=1)
    test_error=percentError(out,test['price'])
    #on validation data
    out=net.activateOnDataset(validation).argmax(axis=1)
    vali_error=percentError(out,validation['price'])
    return  test_error,vali_error

print('Neaural network with 6 input, 3 hidden units, 1 output')
nn3_testerr,nn3_valierr=buildNN(6,3,1)
</code>```

I get constant error and my program is not learning. Can you please suggest what might be the issue?

Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278

答:
there are lots of ways to improve NN performance

1) tweak the geometry (add layers, change layer size)

2) change the activation function

3) change step size/momentum

4) play around with data preprocessing

you should try all of these, and various combinations of all of these.  From a quick glance, a single layer, with only three neurons won't be very rugged, so start there.

Can you get this network to converge on a simple example like xor?

Body:
I am using pybrain to predict house prices in the house price dataset. I downloaded the dataset from below link:
https://www.kaggle.com/apratim87/housingdata/data

I picked 6 columns to predict the price
    'bedrooms','bathrooms','sqft_living','sqft_lot','floors','zipcode'

I took a neural network with 6 input units,1 hidden layer with 3 neurons and 1 unit in the output.

I have normalized the data. Code is as below:

 house_df = pd.read_csv("kc_house_data.csv")
 print(house_df.head())
df = house_df.dropna(axis=0)
df = df[(df != 0).all(1)]
df.reset_index(drop=True,inplace=True)
X_org=house_df[['bedrooms','bathrooms','sqft_living','sqft_lot','floors','zipcode']]
y_org=house_df[['price']]

scaler = Normalizer().fit(X_org)
X = scaler.transform(X_org)
target_scaler = preprocessing.MinMaxScaler()
y=target_scaler.fit_transform(y_org)

ds=SupervisedDataSet(X.shape[1],y.shape[1])
for i in range(len(X)):
    ds.addSample(X.iloc[i,:].values,y.iloc[i,:].values)

train,rest=ds.splitWithProportion(0.60)
test,validation=rest.splitWithProportion(0.50)

print('Training Set Size='+str(len(train)))
print('Test Set Size='+str(len(test)))
print('Validation Set Size='+str(len(validation)))

#creating a neural network
def buildNN(invar,hidden,out):
    net=buildNetwork(invar,hidden,out,hiddenclass=SigmoidLayer,outclass=SoftmaxLayer)
    trainer=BackpropTrainer(net,dataset=train,momentum=0.1,verbose=True,weightdecay=0.01)
    trn_err,val_err=trainer.trainUntilConvergence(dataset=train,maxEpochs=50)

    #trainer.trainOnDataset(trndata,500)
    tst,=plt.plot(trn_err,'b',label='Test Error')
    vali,=plt.plot(val_err,'r',label='Validation Error')
    plt.legend(handles=[tst, vali])
    plt.ylabel('Error')
    plt.xlabel('Number of Epochs')
    plt.show()
     #testing it on test data
     out=net.activateOnDataset(test).argmax(axis=1)
    test_error=percentError(out,test['price'])
    #on validation data
    out=net.activateOnDataset(validation).argmax(axis=1)
    vali_error=percentError(out,validation['price'])
    return  test_error,vali_error

print('Neaural network with 6 input, 3 hidden units, 1 output')
nn3_testerr,nn3_valierr=buildNN(6,3,1)

I get constant error and my program is not learning. Can you please suggest what might be the issue?

Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278
Total error:  0.441892335278


问:
How to use icon in mahapps hamburger menu XAML
How do I use Entypo icon in mahapps hamburger menu?
I've tried many ways but nothing works. Below is my xaml code:</p>

```<code><controls:HamburgerMenu.ItemsSource>
   <controls:HamburgerMenuItemCollection>
      <controls:HamburgerMenuIconItem Icon="{iconPacks:PackIconEntypo Kind=Users}" Label="Accounts">
         <controls:HamburgerMenuIconItem.Tag>
             <views:AccountsView/>
         </controls:HamburgerMenuIconItem.Tag>
      </controls:HamburgerMenuIconItem>
   </controls:HamburgerMenuItemCollection>
</controls:HamburgerMenu.ItemsSource>
</code>```

答:
You need to define a datatemplate :

```<code><DataTemplate x:Key="MenuItemTemplate" DataType="{x:Type controls:HamburgerMenuIconItem}">
   <Grid Height="64">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="64" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
   <Grid Grid.Column="0">
        <Viewbox ToolTip="{Binding Label}" Width="32" Height="32" >
            <Viewbox.Child>
                <ContentControl Content="{Binding Path=Icon}"></ContentControl>
             </Viewbox.Child>
        </Viewbox>
    </Grid>
    <TextBlock Grid.Column="1"
               VerticalAlignment="Center"
               FontSize="16"
               Foreground="White"
               Text="{Binding Label}" />
        </Grid>
</DataTemplate>
</code>```

Then apply this datatemplate setting this property in your HamburgerMenu

```<code>ItemTemplate="{StaticResource MenuItemTemplate}"
</code>```

Please mind that the widths and heights defined in the datatemplate can be modified to fit your menù size. You can define your own datatemplate, but you need to tell your application where how to display the Icon

Body:
How do I use Entypo icon in mahapps hamburger menu?
I've tried many ways but nothing works. Below is my xaml code:

<controls:HamburgerMenu.ItemsSource>
   <controls:HamburgerMenuItemCollection>
      <controls:HamburgerMenuIconItem Icon="{iconPacks:PackIconEntypo Kind=Users}" Label="Accounts">
         <controls:HamburgerMenuIconItem.Tag>
             <views:AccountsView/>
         </controls:HamburgerMenuIconItem.Tag>
      </controls:HamburgerMenuIconItem>
   </controls:HamburgerMenuItemCollection>
</controls:HamburgerMenu.ItemsSource>

Body:
You need to define a datatemplate :

<DataTemplate x:Key="MenuItemTemplate" DataType="{x:Type controls:HamburgerMenuIconItem}">
   <Grid Height="64">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="64" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
   <Grid Grid.Column="0">
        <Viewbox ToolTip="{Binding Label}" Width="32" Height="32" >
            <Viewbox.Child>
                <ContentControl Content="{Binding Path=Icon}"></ContentControl>
             </Viewbox.Child>
        </Viewbox>
    </Grid>
    <TextBlock Grid.Column="1"
               VerticalAlignment="Center"
               FontSize="16"
               Foreground="White"
               Text="{Binding Label}" />
        </Grid>
</DataTemplate>

Then apply this datatemplate setting this property in your HamburgerMenu

ItemTemplate="{StaticResource MenuItemTemplate}"

Please mind that the widths and heights defined in the datatemplate can be modified to fit your menù size. You can define your own datatemplate, but you need to tell your application where how to display the Icon


问:
Check if two items are equal
I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.

Is there a good method or query to check if the UserId == ThreadId?

My current code:

```<code>public void deleteThread() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_THREAD, null, null);
    db.close();

    Log.d(TAG, "Deleted all Thread info from sqlite");
}
</code>```

答:
Something like this;

```<code>public void deleteThread(String threadName) {
    SQLiteDatabase db = this.getWritableDatabase();
    try {
        db.delete(MYDATABASE_TABLE, "name = ?", new String[]{threadName});
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.close();
    }
}
</code>```

Something long these lines, querying database to find the specific row that has  column which matches the parameter.

For example to delete a row which the name column is "Hello World";

```<code>deleteThread("Hello World");
</code>```

Title: Check if two items are equal

Body:
I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.

Is there a good method or query to check if the UserId == ThreadId?

My current code:

public void deleteThread() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_THREAD, null, null);
    db.close();

    Log.d(TAG, "Deleted all Thread info from sqlite");
}

Body:
Something like this;

public void deleteThread(String threadName) {
    SQLiteDatabase db = this.getWritableDatabase();
    try {
        db.delete(MYDATABASE_TABLE, "name = ?", new String[]{threadName});
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.close();
    }
}

Something long these lines, querying database to find the specific row that has  column which matches the parameter.

For example to delete a row which the name column is "Hello World";

deleteThread("Hello World");


问:
Internet Explorer box model - what is offset?
I am trying to adapt a site to support IE 7. I have a few elements, however, which are being offset to the right by 69px. I am testing in IE9, set to render the page as if it were IE7. When I turn on developer mode and inspect the element I notice that surrounding the "margin" there is a parameter called "offset".

I've never heard of this before and Googling has not helped me out much - I only managed to find something about float-offset, which was not the same, but I assume it was there to eliminate some of the issues of quirks mode? How can I eliminate this offset-parameter?

Obviously I have a IE-7 specific stylesheet set up and you can test the problem yourself by going to my testing environment on this link:

http://suitable.amok-adhoc.com/2012/

Solved:

Found a solution - it was pretty simple. Just had to explicitly declare the position  like this (although it was inherited from the parent element in all other browsers IE added a margin and called it "offset", which is overridden by doing this):

```<code>p {
    left:0px;
}
</code>```

答:
You can try to use:
position: -ms-device-fixed;
this trick helps me.

Body:
I am trying to adapt a site to support IE 7. I have a few elements, however, which are being offset to the right by 69px. I am testing in IE9, set to render the page as if it were IE7. When I turn on developer mode and inspect the element I notice that surrounding the "margin" there is a parameter called "offset".

I've never heard of this before and Googling has not helped me out much - I only managed to find something about float-offset, which was not the same, but I assume it was there to eliminate some of the issues of quirks mode? How can I eliminate this offset-parameter?

Obviously I have a IE-7 specific stylesheet set up and you can test the problem yourself by going to my testing environment on this link:

http://suitable.amok-adhoc.com/2012/

Solved:

Found a solution - it was pretty simple. Just had to explicitly declare the position  like this (although it was inherited from the parent element in all other browsers IE added a margin and called it "offset", which is overridden by doing this):

p {
    left:0px;
}


问:
What exactly is Common Language Runtime
What exactly is  Common Language Runtime in Dot Net. Is it an exe or dll. Can I see common  language runtime in task manager. Where is it located.</p>

答:
You should first look up in google before posting here.. But here it goes:

What is it?

The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier.

Where is it located?.

C:\Windows\Microsoft.NET\Framework\v2.0.50727

Of course the last part depends on your version.

Title: What exactly is Common Language Runtime


问:
javascript element of array stays unchangeable, even after change value
My problem is this:

Suppose this class, it's an example of my true code:

class TileMap {
    constructor ( w, h ) {
        this.tiles = [];

        // init the matrix
        for (var i = 0; i < h; i++) {
            var a = [];
            for (var j = 0; j < w; j++) {
                a.push(0);
            }
            this.tiles[i] = a;
        }
    }

    setTile (x, y, tile) {
        this.tiles[y][x] = tile;
    }

    doSomething () {
        this.setTile(0, 0, 1);
        this.setTile(0, 1, 2);
    }
}

// What's happening is when I use like this:
var player = {};
player.map = new TileMap(32, 90, 90);

player.map.doSomething();
console.log("before Tile[0][0] = " + player.map.tiles[0][0]);

player.map.setTile(0, 0, 3);
console.log("after Tile[0][0] = " + player.map.tiles[0][0]);```
</div>
</div>
</p>

<p>Shows me the follow output:</p>

```before Tile[0][0] = 1
after Tile[0][0] = 1
```

The matrix are modified but turn back to before values.
What should I do? (NOTE I'm not familiar with javascript but with language like C++)

答:
I do not understand what is wrong. I added to your code the player object.

class TileMap{
  constructor ( w, h ){
    this.tiles = [];
    //init the matrix
    for (var i = 0; i < h; i++)
    {
      var a = [];
      for (var j = 0; j < w; j++)
        a.push(0);
      this.tiles[i] = a;
    }
  }

  setTile (x, y, tile){
    this.tiles[y][x] = tile;
  }

  doSomething (){
    this.setTile(0,0, 1);
    this.setTile(0,1, 2);
  }
}

//What's happening is when I use like this:
var player = {};
player.map = new TileMap(32,90,90);
player.map.doSomething();
console.log("before Tile[0][0] = "+player.map.tiles[0][0]);
player.map.setTile(0,0, 3);
console.log("after Tile[0][0] = "+player.map.tiles[0][0]);```

Body:
My problem is this:

Suppose this class, it's an example of my true code:

class TileMap {
    constructor ( w, h ) {
        this.tiles = [];

        // init the matrix
        for (var i = 0; i < h; i++) {
            var a = [];
            for (var j = 0; j < w; j++) {
                a.push(0);
            }
            this.tiles[i] = a;
        }
    }

    setTile (x, y, tile) {
        this.tiles[y][x] = tile;
    }

    doSomething () {
        this.setTile(0, 0, 1);
        this.setTile(0, 1, 2);
    }
}

// What's happening is when I use like this:
var player = {};
player.map = new TileMap(32, 90, 90);

player.map.doSomething();
console.log("before Tile[0][0] = " + player.map.tiles[0][0]);

player.map.setTile(0, 0, 3);
console.log("after Tile[0][0] = " + player.map.tiles[0][0]);

Shows me the follow output:

before Tile[0][0] = 1
after Tile[0][0] = 1

The matrix are modified but turn back to before values.
What should I do? (NOTE I'm not familiar with javascript but with language like C++)


问:
Read file line by line and do regex validation
What is the proper way for validating weather the imported text file matches with this block of text, line by line by Regex

Title: Effort required for coding

YLabel: Effort

XLabel: Lines

XStart: 0

XInterval: 2500

0, 100, 200, 400, 700, 1024

for example: I tried with this regex syntax to check the first line i.e (Title: Effort required for coding) but the expression is not correct

```<code> public Boolean fileValidation(String input){
    boolean bool = input.matches("^Title(?=.*:) [a-zA-Z]");

     if(bool){
         JOptionPane.showMessageDialog(this, "Valid File", "Valid", JOptionPane.INFORMATION_MESSAGE);
     }else{
         JOptionPane.showMessageDialog(this, "Invalid File", "Invalid", JOptionPane.ERROR_MESSAGE);
     }
     return bool;

}
</code>```

This is my code for reading selected text file line by line

```<code>try {
        Scanner scan = new Scanner(file);

        String info = "";

        while(scan.hasNext()){

            info += scan.nextLine() + "\n";
            readtxt.setText(info);
            fileValidation(info);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

答:
```<code>String s = "Title: Effort required for coding";

System.out.println(s.matches("^Title(?=.*:): [a-zA-Z ]+"));
</code>```

Blank and + for the rest of the string were missing.

Body:
What is the proper way for validating weather the imported text file matches with this block of text, line by line by Regex

Title: Effort required for coding

YLabel: Effort

XLabel: Lines

XStart: 0

XInterval: 2500

0, 100, 200, 400, 700, 1024

for example: I tried with this regex syntax to check the first line i.e (Title: Effort required for coding) but the expression is not correct

 public Boolean fileValidation(String input){
    boolean bool = input.matches("^Title(?=.*:) [a-zA-Z]");

     if(bool){
         JOptionPane.showMessageDialog(this, "Valid File", "Valid", JOptionPane.INFORMATION_MESSAGE);
     }else{
         JOptionPane.showMessageDialog(this, "Invalid File", "Invalid", JOptionPane.ERROR_MESSAGE);
     }
     return bool;

}

This is my code for reading selected text file line by line

try {
        Scanner scan = new Scanner(file);

        String info = "";

        while(scan.hasNext()){

            info += scan.nextLine() + "\n";
            readtxt.setText(info);
            fileValidation(info);

        }

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

Body:
String s = "Title: Effort required for coding";

System.out.println(s.matches("^Title(?=.*:): [a-zA-Z ]+"));

Blank and + for the rest of the string were missing.


问:
tried to get a user from facebook with http.get
i tried to get a user from facebook with the method "getUser" but i still get the error "property _backend is missing in typeof Http".
What is the reason ?

Here my code :

```<code>export class User {
    http:Http;
    constructor() {
      this.http = Http;
    }

    public createUser(user,token) {
        firebase.database().ref("Users/"+user.uid).set({
            name : user.displayname,
            token : token
        });
    }

    public removeUser(user) {

    }

    public getUserToken(id) {
        return firebase.database().ref("Users/"+id).child("token");
    }

    public getUser(token) {
        //let http : Http;
        return this.http.get("https://graph.facebook.com/me?access_token="+token+"&fields=id,name,picture")
        .subscribe(data => data.json());
    }
}
</code>```

i tried to make an instance from User and to call getUser here:

```<code>  export class HomePage {

  constructor(public navCtrl: NavController,http : Http,public nav :
  Nav,public loadingCtrl : LoadingController) {

  let me = this;
  let token;
  let user;
  let facebookUser;
  let userClass = new User();

  firebase.auth().getRedirectResult().then(function(result){
      me.presentLoadingCustom();

      user = result.user.providerData[0];
      token = result.credential.accessToken;
      facebookUser = userClass.getUser(token);

      userClass.createUser(user,token);
      nav.setRoot(IndexPage,{user : facebookUser});

  });
</code>```

}

答:
It seems that you don't have injected http provider in your constructor.

```<code>import { Http } from '@angular/http';
export class User{

constructor(private http: Http){

}

public getUser(token){

    //let http : Http;

    return this.http.get("https://graph.facebook.com/me?access_token="+token+"&fields=id,name,picture")
        .subscribe(data => data.json());
}
}
</code>```

Also, you may be need to import HttpModule in app.module.ts if not already done like this :

```<code>...
import { HttpModule } from '@angular/http';

@NgModule({
    imports:      [HttpModule],
    ....
})
</code>```

Body:
i tried to get a user from facebook with the method "getUser" but i still get the error "property _backend is missing in typeof Http".
What is the reason ?

Here my code :

export class User {
    http:Http;
    constructor() {
      this.http = Http;
    }

    public createUser(user,token) {
        firebase.database().ref("Users/"+user.uid).set({
            name : user.displayname,
            token : token
        });
    }

    public removeUser(user) {

    }

    public getUserToken(id) {
        return firebase.database().ref("Users/"+id).child("token");
    }

    public getUser(token) {
        //let http : Http;
        return this.http.get("https://graph.facebook.com/me?access_token="+token+"&fields=id,name,picture")
        .subscribe(data => data.json());
    }
}

i tried to make an instance from User and to call getUser here:

  export class HomePage {

  constructor(public navCtrl: NavController,http : Http,public nav :
  Nav,public loadingCtrl : LoadingController) {

  let me = this;
  let token;
  let user;
  let facebookUser;
  let userClass = new User();

  firebase.auth().getRedirectResult().then(function(result){
      me.presentLoadingCustom();

      user = result.user.providerData[0];
      token = result.credential.accessToken;
      facebookUser = userClass.getUser(token);

      userClass.createUser(user,token);
      nav.setRoot(IndexPage,{user : facebookUser});

  });

}

Body:
It seems that you don't have injected http provider in your constructor.

import { Http } from '@angular/http';
export class User{

constructor(private http: Http){

}

public getUser(token){

    //let http : Http;

    return this.http.get("https://graph.facebook.com/me?access_token="+token+"&fields=id,name,picture")
        .subscribe(data => data.json());
}
}

Also, you may be need to import HttpModule in app.module.ts if not already done like this :

...
import { HttpModule } from '@angular/http';

@NgModule({
    imports:      [HttpModule],
    ....
})