magento 1.9 – Fatal error: Call to a member function setData() on boolean in core/Mage/Adminhtml/Block/Widget/Form/Container.php on line 144

Good evening guys!

I am almost giving up on this error that i am getting with a new module.

Fatal error: Call to a member function setData() on boolean in /var/www/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php on line 144

These line refers to this part:

public function getFormHtml()
{
    $this->getChild('form')->setData('action', $this->getSaveUrl());
    return $this->getChildHtml('form');
}

I have the following structure:

Company_Module_Block_Adminhtml_Campaign_Edit_Tabs > Company_Module_Block_Adminhtml_Campaign_Edit_Tab_Form > Company_Module_Block_Adminhtml_Campaign_Edit_Form

Ok i have Xdebug running on this project and everything is being called except this one :

Company_Module_Block_Adminhtml_Campaign_Edit_Form

My Edit.php is everything ok too:

    parent::__construct();
    $this->_blockGroup = 'company_module';
    $this->_controller = 'adminhtml_module';

I’ve being trying to resolve this error for days, searched every place but still with no answer 🙁

typescript – Lodash Apply class instance function if instance is not null

Let’s assume we have the following example:

class Person {
  name: string;
  firstname: string;

  getFullName(separator: string) {
    return name + separator + fisrt
  }
}

const person = ..

const fullName = _.ifNotNull(person, value => value.getFullName('-'))

Is there an equivalent to ifNotNull function in lodash which apply a function from object parameter.

c++ – how many parameters can be in a function overloading?

template<typename _CharT, typename _Traits>
    basic_istream<_CharT, _Traits>&
    operator>>(basic_istream<_CharT, _Traits>& __in, _CharT* __s);

This is a function overloading for operator >>. My question is why this function overloading could have two parameters?
usually, we write:

mystringStream >> myChar;

But this function has another variable __in. How could I understand this?

Thanks!

php – How to hook into a public static function from a custom plugin

This function exists in woocommerce plugin includes. I want to be able to hook into it, I think is the term after a form on a checkout page has been submitted to a third party api, I want to take that payload result and update_order_review I don’t mind having a flow where, I check the balance of the gift card, and then you hit apply to run this function but how would I hook into from my custom plugin I have built. I am able to get the Ajax Part to work, but am stuck on how to hook into the update order review part.

/**
     * AJAX update order review on checkout.
     */
    public static function update_order_review() {
        check_ajax_referer( 'update-order-review', 'security' );

        wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );

        if ( WC()->cart->is_empty() && ! is_customize_preview() && apply_filters( 'woocommerce_checkout_update_order_review_expired', true ) ) {
            self::update_order_review_expired();
        }

        do_action( 'woocommerce_checkout_update_order_review', isset( $_POST('post_data') ) ? wp_unslash( $_POST('post_data') ) : '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

        $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
        $posted_shipping_methods = isset( $_POST('shipping_method') ) ? wc_clean( wp_unslash( $_POST('shipping_method') ) ) : array();

        if ( is_array( $posted_shipping_methods ) ) {
            foreach ( $posted_shipping_methods as $i => $value ) {
                $chosen_shipping_methods( $i ) = $value;
            }
        }

        WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
        WC()->session->set( 'chosen_payment_method', empty( $_POST('payment_method') ) ? '' : wc_clean( wp_unslash( $_POST('payment_method') ) ) );
        WC()->customer->set_props(
            array(
                'billing_country'   => isset( $_POST('country') ) ? wc_clean( wp_unslash( $_POST('country') ) ) : null,
                'billing_state'     => isset( $_POST('state') ) ? wc_clean( wp_unslash( $_POST('state') ) ) : null,
                'billing_postcode'  => isset( $_POST('postcode') ) ? wc_clean( wp_unslash( $_POST('postcode') ) ) : null,
                'billing_city'      => isset( $_POST('city') ) ? wc_clean( wp_unslash( $_POST('city') ) ) : null,
                'billing_address_1' => isset( $_POST('address') ) ? wc_clean( wp_unslash( $_POST('address') ) ) : null,
                'billing_address_2' => isset( $_POST('address_2') ) ? wc_clean( wp_unslash( $_POST('address_2') ) ) : null,
            )
        );

        if ( wc_ship_to_billing_address_only() ) {
            WC()->customer->set_props(
                array(
                    'shipping_country'   => isset( $_POST('country') ) ? wc_clean( wp_unslash( $_POST('country') ) ) : null,
                    'shipping_state'     => isset( $_POST('state') ) ? wc_clean( wp_unslash( $_POST('state') ) ) : null,
                    'shipping_postcode'  => isset( $_POST('postcode') ) ? wc_clean( wp_unslash( $_POST('postcode') ) ) : null,
                    'shipping_city'      => isset( $_POST('city') ) ? wc_clean( wp_unslash( $_POST('city') ) ) : null,
                    'shipping_address_1' => isset( $_POST('address') ) ? wc_clean( wp_unslash( $_POST('address') ) ) : null,
                    'shipping_address_2' => isset( $_POST('address_2') ) ? wc_clean( wp_unslash( $_POST('address_2') ) ) : null,
                )
            );
        } else {
            WC()->customer->set_props(
                array(
                    'shipping_country'   => isset( $_POST('s_country') ) ? wc_clean( wp_unslash( $_POST('s_country') ) ) : null,
                    'shipping_state'     => isset( $_POST('s_state') ) ? wc_clean( wp_unslash( $_POST('s_state') ) ) : null,
                    'shipping_postcode'  => isset( $_POST('s_postcode') ) ? wc_clean( wp_unslash( $_POST('s_postcode') ) ) : null,
                    'shipping_city'      => isset( $_POST('s_city') ) ? wc_clean( wp_unslash( $_POST('s_city') ) ) : null,
                    'shipping_address_1' => isset( $_POST('s_address') ) ? wc_clean( wp_unslash( $_POST('s_address') ) ) : null,
                    'shipping_address_2' => isset( $_POST('s_address_2') ) ? wc_clean( wp_unslash( $_POST('s_address_2') ) ) : null,
                )
            );
        }

        if ( isset( $_POST('has_full_address') ) && wc_string_to_bool( wc_clean( wp_unslash( $_POST('has_full_address') ) ) ) ) {
            WC()->customer->set_calculated_shipping( true );
        } else {
            WC()->customer->set_calculated_shipping( false );
        }

        WC()->customer->save();

        // Calculate shipping before totals. This will ensure any shipping methods that affect things like taxes are chosen prior to final totals being calculated. Ref: #22708.
        WC()->cart->calculate_shipping();
        WC()->cart->calculate_totals(); // I WOULD LIKE TO CHANGE HOOK IN HERE AFTER MY AJAX 
                                        // REQUEST FROM MY BUTTON OR EVENTUALLY CUSTOM FORM

        // Get order review fragment.
        ob_start();
        woocommerce_order_review();
        $woocommerce_order_review = ob_get_clean();

        // Get checkout payment fragment.
        ob_start();
        woocommerce_checkout_payment();
        $woocommerce_checkout_payment = ob_get_clean();

        // Get messages if reload checkout is not true.
        $reload_checkout = isset( WC()->session->reload_checkout ) ? true : false;
        if ( ! $reload_checkout ) {
            $messages = wc_print_notices( true );
        } else {
            $messages = '';
        }

        unset( WC()->session->refresh_totals, WC()->session->reload_checkout );

        wp_send_json(
            array(
                'result'    => empty( $messages ) ? 'success' : 'failure',
                'messages'  => $messages,
                'reload'    => $reload_checkout,
                'fragments' => apply_filters(
                    'woocommerce_update_order_review_fragments',
                    array(
                        '.woocommerce-checkout-review-order-table' => $woocommerce_order_review,
                        '.woocommerce-checkout-payment' => $woocommerce_checkout_payment,
                    )
                ),
            )
        );
    }

This is my ajax and php so far

php

<?php


add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() {
   wp_register_script( "gift_card_redeem", WP_PLUGIN_URL.'/givex-integrate/gift_card_redeem.js', array('jquery') );
   wp_localize_script( 'gift_card_redeem', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'gift_card_redeem' );

}

add_action("wp_ajax_gift_card_redeem", "gift_card_redeem");


function gift_card_redeem(){
  
  if(!empty($_SERVER('HTTP_X_REQUESTED_WITH')) && strtolower($_SERVER('HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest') {
    error_log("test !empty");

    $result('type') = "success";
    $result = json_encode($result);
    echo $result;
  }
  else {
    error_log("test else");
      header("Location: ".$_SERVER("HTTP_REFERER"));
  }

  die();
}

js

jQuery(document).ready(function () {
  jQuery(".redeem_gift_card").click(function (e) {
    e.preventDefault();

    jQuery.ajax({
      type: "post",
      dataType: "json",
      url: myAjax.ajaxurl,
      data: { action: "gift_card_redeem" },
      success: function (response) {
        if (response.type == "success") {
          jQuery("#test").html(response.type);
        } else {
          alert("something broke");
        }
      },
    });
  });
});

data – function over list mathematica

I work on problem that need to define function with two list of data as follow

a = {0.1, 0.233, 0.65, 1.56};
b = {0.99, 0.8, 0.9, 1.9};

ELCDM1(z_?NumericQ, om_?NumericQ) := 1/Sqrt(om*(1 + z)^3 + 1 - om);

angdist(zmin_?NumberQ, zmax_?NumberQ, om_?NumberQ) := (3*10^5)/(

   1 + zmax) NIntegrate(ELCDM1(z, om), {z, zmin, zmax});

“a” is list of lower bound of integrate and b is upper bound. The true outcome for my function “angdis” is
{100707., 71762., 25625.6, 13508.}. For me I should put first list “a” to my function and at the end of my program put list “b” so as I did as follow the outcome is different with {100707., 71762., 25625.6, 13508.}.

angdist3(x_, 
   om_) := (3*10^5)/(1 + #) NIntegrate(ELCDM1(z, om), {z, x, #}) & /@ 
   b;

angdist4(om_) := angdist3(#, om)((#)) & /@ a;

angdist4(.3)

here is the outcome :

{{100707., 92199.9, 97142.2, 111441.}((
  0.1)), {82220.6, 71762., 77779.9, 98755.}((
  0.233)), {32424.9, 16710.2, 25625.6, 64584.9}((
  0.65)), {-42008.8, -65580.4, -52333.9, 13508.}((1.56))}

Any suggestions would be greatly appreciated.

fa.functional analysis – “Trade-off” between bound on the function and on the spectrum for functional calculus in spectral theory

Let $A$ be a self-adjoint (unbounded) operator on a separable Hilbert space $H$.
From the following form of spectral theorem, we may define a functional calculus by $f(A)=Q^{-1} M_{fcirc alpha} Q$. (See below for $Q,alpha$.)

There exists an at most countable collection of finite Borel measures $(mu_k)$ on $mathbb R$ and a isometric linear map $Q:L^2(X,mu) to H$, where $(X,mu)=bigsqcup_{k}(mathbb R , mu_k)$ is the disjoint union of copies of $mathbb R$, such that
$$
Q^{-1}AQ=M_alpha, text{Domain}(A)=D(A)=QD(M_alpha),
$$

where $alpha:X to mathbb R$ is given by $alpha(x)=x$ on each copy of $mathbb R$ and $M_alpha$ is the multiplication operator corresponding to $alpha$ on $L^2(X,mu)$.

This is a version of spectral theorem found in Spectral Theory –
Basic Concepts and Applications
by David Borthwick. It is also proven in the book that this functional calculus is well-defined for all bounded borel functions $mathbb R to mathbb C$ (Theorem 5.9). However, this does not include many functions. For example, polynomial functions, like $f(x)=x$, are unbounded.

On the other hand, it is very easy to see that functional calculus for polynomials can easily be defined in this way, if $A$ is a bounded operator, because it has a bounded spectrum.

It appears that, to make the functional calculus work, we have to place a limit on either the “size” of spectrum of $A$ or the “growth rate” of $f$?

Can the above statement be made more precise? Are there any nice descriptions of this “trade-off”?

go – Testing a template function in GoLang using mocking – making it DRY & easy to follow

I’m wondering how to organise test functions using mocks for GoLang drier & easier to follow.

Function

I have a template function that is very similar to ACF’s getField:

  • It take’s in a string (field name) & the post ID.
  • It checks if the ID exists and the obtains the post by ID (the f.store.Posts belongs to the fields struct)
  • If the post doesn’t exist or if the fields could not be unmarshalled it will return an empty string.
func (f *fields) getField(field string, id ...int) interface{} {

    fields := f.fields
    if len(id) > 0 {
        post, err := f.store.Posts.GetById(id(0))
        if err != nil {
            return ""
        }
        var m map(string)interface{}
        if err := json.Unmarshal(*post.Fields, &m); err != nil {
            return ""
        }
        fields = m
    }

    val, found := fields(field)
    if !found {
        return ""
    }

    return val
}

Testing

From the function, presumably I need to test if, The post exists, the json could be unmarshalle or if the field exists.
I have started to use github.com/golang/mock/gomock but am finding it confusing!
In each of the test functions below I create a new controller and mockPost, add assigning the fields Post to it.


func TestGetField(t *testing.T) {
    f, err := helper(`{"text": "content"}`)
    if err != nil {
        t.Error(err)
    }

    if field := f.getField("text"); field == "" {
        t.Errorf(test.Format("content", nil))
    }

    if field := f.getField("wrongval"); field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := ()byte(`{"posttext": "postcontent"}`)
    mockPost := domain.Post{
        Id:     2,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    f.store.Posts = posts
    posts.EXPECT().GetById(2).Return(mockPost, nil)

    field := f.getField("posttext", 2)
    if field != "postcontent" {
        t.Errorf(test.Format("postcontent", field))
    }
}

func TestGetField_No_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    posts := mocks.NewMockPostsRepository(controller)
    var mockErr = fmt.Errorf("No post")
    posts.EXPECT().GetById(gomock.Any()).Return(domain.Post{}, mockErr)
    f.store.Posts = posts

    field := f.getField("text", 1)

    if field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Invalid_JSON(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := ()byte(`"text "content"`)
    mockPost := domain.Post{
        Id:     1,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    posts.EXPECT().GetById(1).Return(mockPost, nil)
    f.store.Posts = posts

    field := f.getField("text", 1)
    if field != "" {
        t.Errorf(test.Format("", field))
    }
}


func TestHasField(t *testing.T) {
    f, err := helper(`{"text": "content"}`)
    if err != nil {
        t.Error(err)
    }

    if has := f.hasField("text"); !has {
        t.Errorf(test.Format(true, has))
    }

    if has := f.hasField("wrongval"); has {
        t.Errorf(test.Format(true, has))
    }
}

Feedback

  • Without using the mock package, how would you approach this?
  • Are there any areas for improvement with the current codebase?
  • Is there away to consolidate any of the testing methods? It seems quite long winded for such a short function

terms – Disable custom taxonomy by name in function

I need delete some custom taxonomy with function. Users creates new taxonomies, but when user create any disabled taxonomy (for example named “custom_taxonomy1”) so WP remove it with function (so blacklist for specific taxonomy name).

How can I delete with something like this:

If post type "custom_post_type" – do remove taxonomy with name array "custom_taxonomy1", "custom_taxonomy2"...

or with wp_remove_object_term() function

or I find this, but how achieve it:

function wpse_296972_pre_delete_term( $term_id, $taxonomy_name ) {
    if ( $taxonomy_name === 'organization' ) {
        $objects = get_objects_in_term( $term_id, $taxonomy );

        // delete here .
    }
}
add_action( 'pre_delete_term', 'wpse_296972_pre_delete_term' );

hands free – Voice activated / HF inputs: how can you escape special function phrases?

For example, say I have a sentence that I want to end with a period then have returned to a new line, but the contents of that sentence itself include period and new line as literals. Is it possible to use voice-only commands to write such a message?

javascript – Naming a data-attribute to be used for calling a function on click

I apologize beforehand if this question does not follow the rules, or seems a bit silly. I really could not find any other place to put this. I will delete it if the case is the former.

Anyway, I want to name a data-attribute that performs an action when the element it is attached to is clicked. Seems simple enough, but I have had a difficult time coming up with a nice name that makes sense in context. For a bit of background, frameworks like Bootstrap use the term data-toggle="...". This is often not the right description, for example, when the action is not a toggle, but a simple function execution. Let’s use an example: a button that calls an input’s stepUp() function (reference) when clicked. I have the following options:

<button type="button" data-toggle="step-up" data-target="my-input">&plus</button>
<button type="button" data-trigger="step-up" data-target="my-input">&plus</button>
<button type="button" data-execute="step-up" data-target="my-input">&plus</button>
<button type="button" data-callback="step-up" data-target="my-input">&plus</button>
<button type="button" data-click="step-up" data-target="my-input">&plus</button>

I would like to know which term makes the most sense in this context, and if you have any other suggestions, I am open to options. Thank you.