2020-03-15

Polymer 3 dom-bind event handling

Original intent

is to update the text when component.selection is changed
index-0.html
<textarea style="width: 100%;height: 9em" id="configtext"></textarea>
<button onclick=" navigator.clipboard.writeText(configtext.value) ">&boxbox; Copy</button>

<webcomponents-element visible="true" id="webcomponentsElement" ></webcomponents-element>
<script>
    window.addEventListener("load",()=>{
        webcomponentsElement.addEventListener("selection-changed",(ev)=>{
            configtext.value=webcomponentsElement.selection.replace( /,/g , ",\n");
        });
    });
</script>

using dom-bind

The change handler is still initialized in SCRIPT code:
index-1.html
<dom-bind id="configurator">
    <template>

        <textarea style="width: 100%;height: 9em" id="configtext"></textarea>
        <button onclick=" navigator.clipboard.writeText(configtext.value) ">&boxbox; Copy</button>

        <webcomponents-element visible="true" id="webcomponentsElement"
                               on-selection-changed="onSelectionChanged"
        ></webcomponents-element>
    </template>
</dom-bind>
<script>
    configurator.onSelectionChanged = function (e) {
        configtext.value = webcomponentsElement.selection.replace(/,/g, ",\n");
    };
</script>

Final version - The power of declarative programming!

No JavaScript, binding only via sel variable scoped in binding context of dom-bind.
index.html
<dom-bind>
    <template>
        <textarea style="width: 100%;height: 9em" id="configtext" value="{{sel::change}}"></textarea>
        <button onclick=" navigator.clipboard.writeText(configtext.value) ">&boxbox; Copy</button>

        <webcomponents-element visible="true" id="webcomponentsElement" selection="{{sel}}"></webcomponents-element>
    </template>
</dom-bind>

2020-03-08

Java Lambda vs method performance is 2x slower

Going over algorithms exercises I found that inline functions with access to outer scope variables make code way cleaner.  In Java 8+ I know two ways of doing so:

  1. wrap an outer scope variables in object and define a method
  2. use Lambda functions
Surprisingly 1st method became almost 2x more performant:
member
    final public class
BinaryGap
{
    public BinaryGap( long value ){ val = value; }

        public final static int
    maxGapCount( final long value )
    {
        final BinaryGap vo = new BinaryGap(value);
        vo.skipBits(0 );

        for( int max0 = 0; vo.val !=0 ; )
        {
            vo.skipBits(1 );
            int z = vo.skipBits(0 );
            if( z == 0 )
                return max0;
            if( z > max0 )
                max0 = z;
        }
        return 0;
    }
    long val;

    final int skipBits( final int bit0 )
    {   int ret = 0;
        do
        {   if( val == 0 || (val&1) != bit0  )
                return ret;
            val = val >> 1;
            ret++;
        }while( val != 0 );
        return ret;
    }
}
Lambda
        public final static int
    maxGapCountLambda(  long value )
    {   class Wrap{ long v; }
        final Wrap w = new Wrap(); w.v = value;
        IntSupplier skip0 = ()->
        {   int count=0;
            long L = w.v;
            for( ; L!=0 && (L&1) == 0; count++ ) // skip 0
                L = L>>1;
            w.v = L;
            return count;
        };
        IntSupplier skip1 = ()->
        {   long L = w.v;
            while( L!=0 && (L&1) == 1 ) // skip 1
                L = L>>1;
            w.v = L;
            return 0;
        };

        skip0.getAsInt();
        int maxCount =0;
        while( w.v != 0 )
        {
            skip1.getAsInt();
            int count =skip0.getAsInt();
            if( count > maxCount )
                maxCount = count;
        }
        return maxCount;
    }

Tests

Test Duration Result
maxGapCount 0s passed
maxGapCountInlineLoad 0.126s
Of course inline is fastest, but not as much readable.
passed
maxGapCountLambdaLoad 0.226s passed
maxGapCountLoad 0.141s passed
skipBits 0s passed
Full sources
BinaryGap.java
package codily.lesson1;

import java.util.function.IntSupplier;
import java.util.function.LongPredicate;
import java.util.function.LongToIntFunction;

/**
 * https://app.codility.com/programmers/lessons/1-iterations/binary_gap/
 */
    final public class
BinaryGap
{
    long val;
    public BinaryGap( long value ){ val = value; }

        public final static int
    maxGapCount( final long value )
    {
        final BinaryGap vo = new BinaryGap(value);
        vo.skipBits(0 );

        for( int max0 = 0; vo.val !=0 ; )
        {
            vo.skipBits(1 );
            int z = vo.skipBits(0 );
            if( z == 0 )
                return max0;
            if( z > max0 )
                max0 = z;
        }
        return 0;
    }
        public final static int
    maxGapCountInline(  long value )
    {
        while( value!=0 && (value&1) == 0 ) // skip 0
            value = value>>1;
        int maxCount =0;

        while( value !=0 )
        {
            while( value!=0 && (value&1) == 1 ) // skip 1
                value = value>>1;

            int count =0;
            while( value!=0 && (value&1) == 0 ) // skip 0
            {   count ++;
                value = value >> 1;
            }
            if( count > maxCount )
                maxCount = count;
        }
        return maxCount;
    }
        public final static int
    maxGapCountLambda(  long value )
    {   class Wrap{ long v; }
        final Wrap w = new Wrap(); w.v = value;
        IntSupplier skip0 = ()->
        {   int count=0;
            long L = w.v;
            for( ; L!=0 && (L&1) == 0; count++ ) // skip 0
                L = L>>1;
            w.v = L;
            return count;
        };
        IntSupplier skip1 = ()->
        {   long L = w.v;
            while( L!=0 && (L&1) == 1 ) // skip 1
                L = L>>1;
            w.v = L;
            return 0;
        };

        skip0.getAsInt();
        int maxCount =0;
        while( w.v != 0 )
        {
            skip1.getAsInt();
            int count =skip0.getAsInt();
            if( count > maxCount )
                maxCount = count;
        }
        return maxCount;
    }


        final int
    skipBits( final int bit0 )
    {   int ret = 0;
        do
        {   if( val == 0 || (val&1) != bit0  )
                return ret;
            val = val >> 1;
            ret++;
        }while( val != 0 );
        return ret;
    }
}
BinaryGapTest.java
package codily.lesson1;

import org.junit.Test;
import static org.junit.Assert.*;

    public class
BinaryGapTest
{
    public final long [] exp =  { 00, 00, 00, 00, 00, 00, 01, 02, 03, 30 };
    public final long [] inp =  { 0b0000_0000_0000_0000_0000_0000_0000_0000L
                                , 0b1111_1111_1111_1111_1111_1111_1111_1111L
                                , 0b0000_0000_0000_0000_0000_0000_0000_0001L
                                , 0b0000_0000_0000_0000_0000_0000_0000_0011L
                                , 0b0000_0000_0000_0000_0000_0000_0000_0010L
                                , 0b0000_0000_0000_0000_0000_0000_0000_0100L
                                , 0b0000_0000_0000_0000_0000_0000_0000_0101L
                                , 0b0000_0000_0000_0000_0000_0000_0000_1001L
                                , 0b0000_0000_0000_0000_0000_0000_1000_1001L
                                , 0b1000_0000_0000_0000_0000_0000_0000_0001L
                                };
    long [] act= new long[inp.length];

        @Test public void
    maxGapCount()
    {
        assertEquals(00, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_0000_0000L ) );
        assertEquals(00, BinaryGap.maxGapCount( 0b1111_1111_1111_1111_1111_1111_1111_1111L ) );
        assertEquals(00, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_0000_0001L ) );
        assertEquals(00, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_0000_0011L ) );
        assertEquals(00, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_0000_0010L ) );
        assertEquals(00, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_0000_0100L ) );

        assertEquals(01, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_0000_0101L ) );
        assertEquals(02, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_0000_1001L ) );
        assertEquals(03, BinaryGap.maxGapCount( 0b0000_0000_0000_0000_0000_0000_1000_1001L ) );
        assertEquals(30, BinaryGap.maxGapCount( 0b1000_0000_0000_0000_0000_0000_0000_0001L ) );
    }
    final int REPEAT_COUNT = 1000_000;

    @Test public void
    maxGapCountLoad()
    {
        for( int k=0; k < REPEAT_COUNT; k++ ) // timer count
            for( int i=0; i<exp.length; i++ )
                act[i] = BinaryGap.maxGapCount( inp[i] );
        assertArrayEquals( act, exp );
    }
        @Test public void
    maxGapCountInlineLoad()
    {
        for( int k=0; k < REPEAT_COUNT; k++ ) // timer count
            for( int i=0; i<exp.length; i++ )
                act[i] = BinaryGap.maxGapCountInline( inp[i] );
        assertArrayEquals( act, exp );
    }
        @Test public void
    maxGapCountLambdaLoad()
    {
        for( int k=0; k < REPEAT_COUNT; k++ ) // timer count
            for( int i=0; i<exp.length; i++ )
                act[i] = BinaryGap.maxGapCountLambda( inp[i] );
        assertArrayEquals( act, exp );
    }

        @Test public void
    skipBits()
    {
        BinaryGap bg = new BinaryGap( 0L );
        assertEquals( "zero", bg.skipBits(0), 0 );
        assertEquals( "zero", bg.skipBits(0), 0 );
        assertEquals( "zero", bg.skipBits(1), 0 );

        bg = new BinaryGap( 0b1111_1111_1111_1111_1111_1111_1111_1111L );
        assertEquals( "zero", bg.skipBits(0), 0 );
        assertEquals( "zero", bg.skipBits(1), 32 );
        assertEquals( "zero", bg.skipBits(1), 0 );
        assertEquals( "zero", bg.skipBits(0), 0 );
    }
}

2020-02-20

polymer bi-directional databind within dom-repeat

Two-way databinding in dom-repeat could be based on extending the item model with component-specific field ( where it is a good habit to use component-specific prefix).

In sample the fieldset is shown only upon checkbox selection.

<ul>
    <template is="dom-repeat" items="[[forms]]">
        <paper-checkbox label="Enable [[item.name]]" checked="{{item.fieldset_enabled}}"></paper-checkbox>
        <template is="dom-if" if="[[item.fieldset_enabled]]">
            <fieldset><legend> '[[item.name]]' section </legend>
                ...
            </fieldset>
        </template>
    </template>
</ul>

2019-06-04

Liferay polymer integration

This is a guideline for Polymer 3 PWA integration as microapplication into Liferay Portlet. The npm module code is a part of portlet and deployed within its JAR. Sample has been build with Vaadin template.

Methods described in this article is applicable to any framework from Angular to Ionic. I am focusing on Polymer 3 as most compatible and smallest base. Other frameworks need extra level of compatibility coding in order to be Liferay (or any CMS) friendly.

Problem

Modern JS frameworks in Liferay 7.1 CMS are the pain to deal with.

The internal CDN publishing of NPM modules have promised to be an great helper. The build tool uses the package.json and node_modules content to publish module and dependencies version into Liferay URL. This way same package version could be shared among applications.

This brilliant idea had not been implemented sufficiently to be suitable for high-level frameworks like PolymerJS(native web components) or Quasar( VueJs ). Such libraries use dependencies in es6 source format which meant to be compiled and bundled depend of target platform into es5 or es6 bundles. Liferay JS toolkit unfortunately treats all dependencies as pre-build to es5 AMD format. Kicking off most of modern JS libs which use ES6 'import' capabilities. Bug.

Solution

Is to use selected platform bundled build capabilities. I would suggest to use legacy (es5/AMD) and modern(ES6) browsers build profiles, both as bundles with dynamic code load. This way in majority of browsers only minimal set of  JS will be used during page load still keeping page responsive to user actions when on-demand code is loaded.

The reference implementation also gives extra perks like

  • debug mode support to use unbundled JS sources on page load
  • build profile enforcing via URL parameter
  • JS project integrated and deployed withing portlet JAR.

Design notes

  • Portlet have to be published in fixed osgi path.
    I.e. for CSS /o/my-custom-portlet/my-custom.css deployment path defined by bnd.bnd is:
        Web-ContextPath: /my-custom-portlet
  • Legacy and es6 builds have to set own root path in index.html by build.sh
  • Browser compatibility recognition done on server side by BrowserSnifferUtil and uses the build profile matching browser.
    esm-bundled, es5-bundled profiles are made for modern and legacy browsers respectively.
  • Server-side inclusion of build/${profile}/index.html is done by jsp:include
  • the top-level component included by view.jsp after as tag with data passed as html element parameters. In sample the URL for ajax call is passed from jsp to portlet.
  • <script type="module"... > during navigation into page with PolymerPortlet is ignored by Liferay SPA implementation. view.jsp has a workaround by re-injecting script tag into page. Processed script tags are marked by `injected` property.
  • es5-unbundled generates document.write("<!--") which clears the page. Fix is removing code from generated index.html

Sample Code


Happy coding!

2019-05-13

@xmlaspect/reactive-xml - reasons of creation

For ApiFusion the import documentation from sources into MediaWiki pages become a sequence for processing various data from different sources, mostly data and html web services. This mix when implemented with classic asynchronous patterns like callbacks, Promise call chain, or `async` JS keyword become a spaghetti code mess hard to code and maintain.

An another use case inspired reacive-xml creation is a web crawling for data mining. In my case finding who will share the floor on various dance competitions.

More on apifusion.com/@xmlaspect/reactive-xml 
Open source work in progress, meanwhile xml4jQuery gives similar solution.

2018-08-12

EPA-Translation as Community-Driven Localisation for Web Apps



Just redefined description for epa-translation:

the community driven translations of web application will extend the application audience beyond the initially targeted countries and lingual dialects.


Why I have started a new project? Ideas are cheap, "every day a dozen" appear and are back logged forever. But this time it became another project to worry about. Worthy of the effort, ApiFusion.com and EPA-WG are actively in progress. 

First, a bit of history. When a new more or less valuable idea appears, it is usually written out and sometimes shared with friends who could have potential interest. Usually that is where its life ends. But this time, Hogne Titlestad from FriendUp invited me to discuss it in their IM group. Apparently the work on translation is in progress there. 

To make it visual for discussion, I thought 3 hours would be sufficient for proof of concept. That is when the project started. And as usual the appetite came during the meal, making me feed-frenzy towards the unusual challenges.

The challenge factor is crucial for hobby style projects. Otherwise, why bother, right?  However, it is not just the challenge swung me to work on proj. The EPA-WG needs a few clear microapplication samples, better in web 3.0 context( cross- service vendors UI and integration ). So far epa-translation seems to be complex enough in functionality and simple enough to understand. 

There is final reason to get it done: epa-translation fits into concept of community-driven content and knowledge/culture evolution which drives modern civilization to progress, where only collective intelligence could counter-balance AI. ( I do recognize other options such as AI and human fusion, but that is a bit in the future. Rather, community initiatives are acting now.)

epa-translation is a part of EPA-WG (Embeddable Progressive Application Working Group) initiative. #OpenSource hosted on GitHub.


PS. This project's challenges came from various sides:
* how to make the translation process seamless?
* how to embed microapplication into host app context?
* How to split several flows ( view, edit, sync to cloud) into independent microapplications?
* What radically new pattern microapplication gives and does it give significant advantages?
Some in HTML5 
* How to identify the text chunks in page, select and substitute?
* What local storage to use - localStorage vs IndexedDB? There is large matrix of pros and cons on each side.

Cloud layer
* Should it be server-less based?
* Should the platform be open?
* Could distributed DB be used? BlockChain vs CDN.

I am pretty sure the list of challenges will grow.

2018-01-24

Things to try


  • Chimay beer in Belgium