Categories
discuss

Class Binding ternary operator

I have some rather cumbersome logic I would like to apply to an element class.

:class="{sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'}"

The above doesn’t work, while the following does:

:class="{'is-outlined': sportTypes.sports.indexOf(sport) > -1}"

I get the following error

template syntax error - invalid expression:

Any ideas what’s wrong with the first part?

Answer

You have unnecessary braces. The latter expression is an object whereas the first is simply a ternary expression that returns a string.

:class="sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'"
Categories
discuss

How to create String Format template to generate Json for Eclipse autogenerated toString

Eclipse gave option to auto generate the toString method for every class.

Further leverage this facility, I am creating String Format Template to give as Json format when eclipse generate toString Method.

I used following String Format Template:

 { ${member.name()}:"${member.value}", ${otherMembers}}

now i generated toString method as following POJO but When i run this program i got result as and not a VALID JSON.

{ name:"null", reportees:"[1, 2, 3]", department:"[retail, banking, finance]", owns:"null", supplimentary:"null}

Code

public class TestPojo {
  private String name;
  private List<String> reportees;
  private String[] department;
  private Machine owns;
  private List<Machine> supplimentary;

public static void main(String arg[]) {
    TestPojo aTestPojo = new TestPojo();
    aTestPojo.department = new String[] { "retail", "banking", "finance" };
    aTestPojo.reportees = new ArrayList<String>() {

        {
            add("1");
            add("2");
            add("3");
        }
    };
    System.out.print(aTestPojo);
}

public static class Machine {

    private String machineName;
    private String duties;

    public String getMachineName() {
        return machineName;
    }

    public void setMachineName(String machineName) {
        this.machineName = machineName;
    }

    public String getDuties() {
        return duties;
    }

    public void setDuties(String duties) {
        this.duties = duties;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("{ machineName:"").append(machineName).append("", duties:"").append(duties).append("}");
        return builder.toString();
    }

}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("{ name:"").append(name).append("", reportees:"").append(reportees).append("", department:"").append(Arrays.toString(department)).append("", owns:"").append(owns).append("", supplimentary:"").append(supplimentary).append("}");
    return builder.toString();
}

}

Answer

With the help of @dvlcube idea. I built a “Eclipse Custom toString() builder” to generate toString method code to return a JSON formatted string of current object.

Follow the github for this solution Click [Eclipse toString_Builder for JSON](https://github.com/djaganathan/EclipseToStringBuilderForJson/blob/master/src/main/java/com/github/djaganathan/opensource/eclipse/util/JsonToStringBuilder.java,”Custom Eclipse toString() Builder”)

Sample Testing Code

import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.time.StopWatch;
import org.elasticsearch.common.collect.Lists;

public class TestPojo {

    private String name;
    private List<String> reportees;
    private String[] department;
    private Machine owns;
    private List<Machine> supplimentary;
    private int i = 10;
    private Map<String, Machine> machineList = Maps.newConcurrentMap();

    public static void main(String arg[]) {
        TestPojo aTestPojo = new TestPojo();
        aTestPojo.department = new String[] { "retail", "banking", "finance"};
        aTestPojo.reportees = new ArrayList<String>() {
            {
                add("1");
                add("2");
                add("3");
            }
        };

        Machine aMachine = new Machine("Train", "travel");
        Machine aMachine1 = new Machine("Lorry", "Carrier");
        aTestPojo.supplimentary = Lists.newArrayList(aMachine, aMachine1);
        aTestPojo.machineList.put("Train", aMachine);
        aTestPojo.machineList.put("Lorry", aMachine1);

        System.out.print(aTestPojo);
    }

    public static class Machine {
          private String machineName;
          private String duties;

        public Machine(String machineName, String duties) {
            super();
            this.machineName = machineName;
            this.duties = duties;
        }
        public String getMachineName() {
          return machineName;
        }
        public void setMachineName(String machineName) {
          this.machineName = machineName;
        }

      public String getDuties() {
          return duties;
      }

      public void setDuties(String duties) {
          this.duties = duties;
      }

    @Override
    public String toString() {
        JsonToStringBuilder builder = new JsonToStringBuilder(this);
        builder.append("machineName", machineName);
        builder.append("duties", duties);
        return builder.build();
    }
}

@Override
public String toString() {
    JsonToStringBuilder builder = new JsonToStringBuilder(this);
    builder.append("name", name);
    builder.append("reportees", reportees);
    builder.append("department", department);
    builder.append("owns", owns);
    builder.append("supplimentary", supplimentary);
    builder.append("i", i);
    builder.append("machineList", machineList);
    String value = builder.build();
    return value;
    }
}

While running this program i got the following JSON output

{"name": null,"reportees": ["1","2","3"],"department": ["retail","banking","finance"],"owns": null,"supplimentary": [{"machineName": "Train","duties": "travel"},{"machineName": "Lorry","duties": "Carrier"}],"i": 10,"machineList": {"Lorry": {"machineName": "Lorry","duties": "Carrier"},"Train": {"machineName": "Train","duties": "travel"}}}
Categories
discuss

Materialize modal not working

I wrote a simple code for materialize modal.
HTML code:

<a class="waves-effect waves-light btn view" data-target="modal1">View Scores</a>
<!-- Modal Structure -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <h4>Modal Header</h4>
    <p>A bunch of text</p>
  </div>
  <div class="modal-footer">
    <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Agree</a>
  </div>
</div>  

JS code:

$(document).ready(function() {
  // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
  /*$('.view').click(function (){
    $('#modal1').modal('open'); 
    alert('edskjcxnm');
  });*/
  /*$('.view').leanModal();*/
  $('#modal1').modal('open');
});  

JSFiddle link: https://jsfiddle.net/7f6hmgcf/
Why isn’t it working?

Answer

Initialize all modals first. $('.modal').modal();

Complete code will look like this

(function ($) {
    $(function () {

        //initialize all modals           
        $('.modal').modal();

        //now you can open modal from code
        $('#modal1').modal('open');

        //or by click on trigger
        $('.trigger-modal').modal();

    }); // end of document ready
})(jQuery); // end of jQuery name space
Categories
discuss

Decorator Pattern : Why do we need an abstract decorator?

I am having difficulty understanding the following implementation advice from Erich Gamma's book Design Patterns regarding Decorator pattern.

Omitting the abstract Decorator class There’s no need to define an abstract Decorator class when you only need to add one responsibility.

I don’t see why abstract Decorator class is required at all? Why can’t all decorators simply implement/inherit directly IComponent/Component?

Answer

I don’t see why abstract Decorator class is required at all? Why can’t all decorators simply implement/inherit directly IComponent/Component?

The purpose of the abstract class in the Decorator pattern is to eliminate code duplication. The crux of the Decorator pattern is to allow you to wrap an existing Component with new responsibilities. This wrapping is done by creating a new class that IS-A component and HAS-A component :

public class Decorator implements Component { 
    private Component component;

    public Decorator(Component component) { this.component = component; }
}

Imagine that you introduce two more decorators. You would now have to implement similar code in both your new decorators. The abstract decorator can help you solve exactly this problem. By moving the above code to an abstract class, all your concrete decorators can inherit from it and avoid the need to re-implement the decorator skeleton manually.

I understand that the Decorator in the above example doesn’t do much; however, imagine a situation where you want to disallow further decoration based on some condition. For example, don’t allow any more toppings on a Pizza if the cost will exceed 15$. The abstract decorator can take care of this by calling the getCost function on the component in the constructor. This will result in a call to all the getCost function of all the decorators and give you a final cost. If getCost()>15, the application can inform the user that the cost cannot exceed 15$. Such code reuse is the real motivation behind the abstract decorator class.

Categories
discuss

Change page URL sent to Universal Google Analytics when using Google Tag Manager

How can I change the page URL that is sent to Universal Google Analytics when using Google Tag Manager? Without Google Tag Manager it’s really simple. You just have to add ga('set', 'page', '/my/custom/url'); before ga('send', 'pageview');.

Your Google Analytics script needs to be like this:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-XXXXXXXX-X', 'auto');
      ga('set', 'page', '/my/custom/url'); /* Set my custom URL */
      ga('send', 'pageview');

</script>

How can I do something similar using Google Tag Manager?

Answer

Changing the “dp” value can be accomplished in GTM by setting the desired value in the page field, under “Fields to set”:

enter image description here

Edit: For dynamic page values, you could define them in the dataLayer (make sure it’s defined BEFORE your GTM container snippet so that the pageview tag sees it):

dataLayer = [{
   'newPage': '/your/page/here'
}];

and define a Data Layer type variable that captures the newPage value, which you use as the value of the page field.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..