Author Archives: Jarek Kubos

DisplayLink drivers on Ubuntu 17.10

Update: Driver version 1.4 works on 17.10 without hacks mentioned below. 

(there is whole journey of me and DisplayLink, NVidia, Intel and Dell troublemakers – see here and here and here)

After last updates I ended up with unbelievably annoying flickering, and sometimes completely missing, cursor on main display.

Desperate people do desperate actions. So I have tried to upgrade to Ubuntu 17.10 with kernel 4.13. Attempt to install “DisplayLink USB Graphics Software for Ubuntu 1.3.54” failed with following issue:

/var/lib/dkms/evdi/1.3.54/build/evdi_gem.c: In function ‘evdi_prime_create’:
/var/lib/dkms/evdi/1.3.54/build/evdi_gem.c:276:15: error: implicit declaration of function ‘drm_malloc_ab’; did you mean ‘dma_alloc_wc’? [-Werror=implicit-function-declaration]
 obj->pages = drm_malloc_ab(npages, sizeof(struct page *));
 ^~~~~~~~~~~~~
 dma_alloc_wc

I have asked on forum when 17.10 will be supported. Meanwhile there is workaround:

  1. Download 1.3.54 driver from http://www.displaylink.com/downloads/ubuntu
  2. Run installer with parameter keep ./displaylink-driver-1.3.54.run –keep
  3. It fails, but in current directory there is folder displaylink-driver-1.3.54
  4. There is file evdi-1.3.54-src.tar.gz, move it somewhere into temp directory
  5. Unpack using tar -zxvf evdi-1.3.54-src.tar.gz
  6. Replace evdi_gem.c by this file from this commit
  7. Pack it again using tar cvzf evdi-1.3.54-src.tar.gz *
  8. Replace original file in folder displaylink-driver-1.3.54
  9. Install driver using ./displaylink-driver-1.3.54/displaylink-installer.sh install
  10. Reboot computer, device should be recognized
  11. But Gnome with Wayland will switch off because recognizes unsupported device. (when will be supported Wayland is a big question)
  12. So first other shell is selected – Plasma in my case. Unfortunatelly most of packages is missing so nasty error appears.
  13. Log out, and on login screen below credentials select cog and there Unity
  14. Then it works except screen connected on DisplayLink shows only cursor
  15. Apply workaround 2 from here, reboot computer
  16. Voila!

20170922_084749

Advertisements

i-tec USB 3.0 Dual Docking Station & Ubuntu 16.04.3 or newer kernels

[There is updated article for Ubuntu 17.10]

There are older articles (first, second) about my issues with graphic on my hardware (Dell Inspiron 15 7559 and i-tec USB 3.0 Dual Docking Station).

Recently I have updated to Ubuntu 16.04.3 (kernel 4.10) so which configuration works now?

It is still necessary to block nvidia and nouveau modules in blacklist.conf. Package bbswitch-dkms is no longer required. Then monitor connected through i-tec docking station is visible in display settings. But when desktop is extended to it then is keeps to be blank. For my setup works first workaround mentioned in DisplayLink knowledge base.

Then everything works fine…..except of annoying flickering of cursor!!! There are some workarounds but unfortunately none works for me 😦

I wish one day problems with graphic cards disappear on Linux. I remember trying Linux for the first time.  There was CD attached to paper magazine. It was around year 2000. Guess why I was not able to use it?! Graphic card issues! Since then I had issue with EVERY graphic card I have used. Intel, ATI, NVidia.

vscub

React.js and MobX: Escape the Redux trap

I have seen React in action for the first time in relatively complex legacy application. There were some attempts to develop new functions using React and, of course, Redux. Because everyone is using that combination. It is the clear, cool way. Hm…

notsure

I fell in love with React quickly but with Redux it was not so hot. Alex Dixon wrote great article about his problems with Redux and functional programming in JavaScript. TLDR:

  • You never know whether you have plain JS object or Immutable.js object under your hands.
  • If you are not using Immutable.js then you still should know whether object you have can be mutated or not.
  • In every file you have to manually import libraries like Immutable or Lodash.

I had those issues plus:

  • It was real pain to describe complex change you would like to perform on immutable state within store. Like add 6th item into array, remove 3 different keys from map, etc.
  • For doing even simple things you have to modify code in multiple files. One often do a hack instead of nice solution.
  • Problems with using multiple stores. I still had feeling that I should not store state of form in global store. Local data should be local, right?
  • Same store is used during navigation without page reload. It is hard to clean everything properly.
  • React-Redux library is doing incredible magic I was never able fully understand.
  • Using Promises just made thing worse.
  • I still had feeling that if I have to reorganize store structure I will got mad.

Then, out of blue sky, I have found MobX. And I realized that I found great React’s partner.

thinking

I can have multiple stores – one that holds application state (selected language, global formatting settings), second that holds form state and handles communication with server, third for caching currency conversions, etc. This stores are available through React context – therefore their presence is checked by React using contextTypes definition. You can freely move components in hierarchy as long as you assure that proper stores are in context.

I still have certain level of immutability because MobX checks that no change is done during processing previous change.

Adding functionality is deadly simple. You have two classes – component and store.

Because store is single purpose and is object of class, it is quite easy to determine what you can do with it. If there is method, try to call it. Compare that with searching for proper Redux action.

Despite I have never use truly functional programming language I highly utilize lambda expressions (Ruby, Java 8, JavaScript), enjoy passing function as parameter and since then my usage of class inheritance dropped by 90% 🙂 In Java I employ Immutables, Jooq and high percentage of methods I write are static ones. So I consider myself open minded in functional programming area. That hopefully gives me some credit to have strong feeling that combination of React and Redux is simply wrong. MobX and React, on the other hand, are just great combination. At least for me 😉

 

 

 

 

Lambda: simplify method calls

There is important part of good programmers skills – ability to detect duplicity. Over years I have developed it for various situations. But recently I have added new situation – duplicity in calling methods with many parameters. And especially with many parameters in local scope. Take a look on following example:

package test;

import java.awt.Graphics;

public class NaiveRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		int calculatedA = paramA+42;
		
		if (paramA<100) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, -1.0);
		} else if (paramA<10) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, -0.2);
		} else if (paramA==0) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.0);
		} else if (paramA>100) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 1.0);
		} else if (paramA>10) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.2);
		} else {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

Obviously, there is huge duplicity in renderSubpart calls. Calculation of some parameters is repeated many times. Let’s improve it:

package test;

import java.awt.Graphics;

public class BetterRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		int calculatedA = paramA+42;
		
		boolean newParamB = !paramB;
		double newParamC = paramC*22.3;
		String newParamD = paramD+" oh";
		
		if (paramA<100) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, -1.0);
		} else if (paramA<10) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, -0.2);
		} else if (paramA==0) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.0);
		} else if (paramA>100) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 1.0);
		} else if (paramA>10) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.2);
		} else {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

Hm. So we have bloated scope by three new local variables. And we have to name it. Plus there is still problem with many similar calls to the renderSubpart. But only one parameter varies. Let’s improve that:

package test;

import java.awt.Graphics;

public class EvenBetterRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		double calculatedB;
		
		if (paramA<100) {
			calculatedB = -1.0;
		} else if (paramA<10) {
			calculatedB = -0.2;
		} else if (paramA==0) {
			calculatedB = 0.0;
		} else if (paramA>100) {
			calculatedB = 1.0;
		} else if (paramA>10) {
			calculatedB = 0.2;
		} else {
			calculatedB = 0.0;
		}
		
		renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", paramA+42, calculatedB);
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

So now we reduced number of added local variables to one. Great, but I don’t like decoupling of condition and method call. Block of condition just set calculatedB which is later used for calling renderSubpart. Can’t we improve that?

I realized that I can wrap parameters into local lambda function like this:

package test;

import java.awt.Graphics;
import java.util.function.Consumer;

public class LambdaRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		Consumer<Double> renderSubpartLambda = (calculatedB)->renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", paramA+42, calculatedB);
		
		if (paramA<100) {
			renderSubpartLambda.accept(-1.0);
		} else if (paramA<10) {
			renderSubpartLambda.accept(-0.2);
		} else if (paramA==0) {
			renderSubpartLambda.accept(0.0);
		} else if (paramA>100) {
			renderSubpartLambda.accept(1.0);
		} else if (paramA>10) {
			renderSubpartLambda.accept(0.2);
		} else {
			renderSubpartLambda.accept(0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

So I have defined renderSubpartLambda that receives single varying parameter and fill all other parameters that shares value over all calls. This is possible because Lambda function, unlike methods, have access to the local scope (parameters, local variables). Lambda is then executed from exact position withing condition blocks with only with single important parameter.

This technique is usable in all situations where it would be hard to define helper method because number of passed parameters would be too high. Btw. this solution is language independent – I have used it in JavaScript too.

jOOQ & Immutables & Jackson: Great together

I really like Java. But only the plain one. I hate all the enterprise frameworks like Spring, Java EE or Hibernate. I consider them enormous and verbose. It my eyes usage of them leads to corporate applications:

  • Application so complex that it is hard to avoid duplicity in code because everone is afraid to change anything.
  • Applications that does not adapt to company needs so company needs to adapt to applications.
  • Applications that is not possible to maintain and improve any more.

Feels like hell for me 🙂 I prefer small, single purpose libraries. For that reason is Navigo3 using multiple libraries for data.

For building access classes to the database we are using jOOQ. You just point it to database and it will generate code for handling it. We are doing that during every Gradle build. If you then use generated code for data access it is automatically verified by compiler. Compiler will complain if anything is wrong – data type was changed, column removed, etc. Because objects read from database can be basically plain POJOs, they may be directly serialized into JSON and used in REST API. I don’t need to say how easy is to find references to certain object, for example column when compared to SQL strings in code…mainly for fields like ‘createdAt’ which is in all tables.

For effortless data structures (POJOs) we are using Immutables. It is matter of seconds to prepare data class with all necessary access methods or builder. No need to write any getter/setter anymore! This is handy mainly for programmers who like functional programming principles. Data are data and they are shaped by functions. Also since I am using Immutables I use static methods much more than before. The reason is that can create methods that returns complex output easily. Formerly I preferred to keep much richer internal state of objects and methods on that object were modifying it instead returning value. This leads to much easier refactoring – static method is so much easier to move that instance method!

For JSON (de)serialization we are using Jackson. Both jOOQ and Immutables have embedded great support for it. It is even possible to serialize combination of both.

Consider this example: I have REST API method that should return information about person – GET /person-info/12345. But not only that, I would like to return also information about company assigned to person – for example to avoid second request during rendering person detail in React.js.

So task is to compose DbPerson and DbCompany classes (generated by jOOQ) into single class that can be (de)serialized. Easy done as nested interface of REST handler:

class Handler {
	@Value.Immutable
	@JsonSerialize(as = ImmutablePersonAndCompany.class)
	@JsonDeserialize(as = ImmutablePersonAndCompany.class)
	public interface PersonAndCompany {
		DbPerson getPerson();
		DbCompany getCompany();
	}

	...
}

So you get generated ImmutablePersonAndCompanyBuilder, fill it with both objects loaded by jOOQ and serialize it using Jackson. Task accomplished.

Using this technique it is easy to add fields into data. For example adding information about address can be done by adding single line.

We also utilize POJO nature of this libraries for documentation. It is quite easy to traverse definition of such classes using reflection and automatically generate documentation from it. Such documentation is always up-to-date without any manual actions.

meta.png

React.js components with embedded styles

You have probably already seen global CSS files with thousands of lines that may influence anything. Change is too dangerous so you just add new rules. To the point everything must be rewritten.

I love React’s ability to build reusable components. Write once, put anywhere you like. This rule does not apply just for JavaScript, it may apply for CSS too. Did you know that you can use css loader to autoprefix rules from CSS/SASS/LESS file? So every require of such file prepares class names that does not clash with anything else (like style__item___3dKqL).

That way you can prepare components that contains embedded styles that applies only for them. No complex CSS selectors are required – just use plain names:

embedcss

At the same time you can import application wide constants using SASS so you do not lose ability to set colors, sizes, … in single place.

Usage in code is simple:

code

(btw. to avoid join operation you can use classnames lib)

Right now I use following:

postcss.config.js

module.exports = {};

package.json

const path = require('path')
const webpack = require('webpack')

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'web-ui-bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true   //!!!!!! This enables modules
                            localIdentName: '[name]_[local]__[hash:base64:15]'
                        }
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                        }
                    },
                    {
                        loader: 'sass-loader'
                    }
                ],
            },
            { 
                test: /\.js$/,
                use: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        contentBase: './',
        hot: true
    },
    plugins: [
     new webpack.HotModuleReplacementPlugin()
    ]
};

webpack.config.js

{ 
    "name": "web-ui",
    "description": "",
    "version": "0.0.1",
    "dependencies": {
        "react": "15.6.1",
        "react-dom": "15.6.1"
    },
    "devDependencies": {
        "webpack": "3.5.2",
        "babel-core": "6.25.0",
        "babel-loader": "7.1.1",
        "babel-preset-es2015": "6.24.1",
        "babel-preset-react": "6.24.1",
        "webpack-dev-server": "2.7.1",
        "style-loader": "0.18.2",
        "css-loader": "0.28.4",
        "postcss-loader": "2.0.6",
        "sass-loader": "6.0.6",
        "node-sass": "4.5.3"
    },
    "scripts": {
        "build": "webpack",
        "devel": "webpack-dev-server --hot"
    },
    "browserslist": ["defaults", "not ie < 11"]
}

React.js: Build your components catalog

When you design large information system UI it is important to stay uniform. Nobody likes when pages varies in appearance or behavior. Typically it is necessary to write UI/UX design manual that describes allowed tools and techniques.

I was thinking about ways how to prepare list of UI components. So we can pick component when creating new functionality and avoid writing new. I was considering Confluence but it would need extra effort to keep list of components up to date.

Then I got it: We can employ React’s ability to prepare reusable components and easily compose catalog. Here is our:

catalogue

Catalog is embedded in application but visible only to developers. Every component is shown in typical situation (to have concise list) and it may be expanded (Date component above) to be seen in various configurations – error state, different input values, empty, …

We are using physics particles categories for components and each category has own section:

  • Quarks – simplest components that only use passed properties (Button, FormattedInput, …)
  • Atoms – components that call server API or are attached to forms or application state (ContextMenu, CurrencyInput)
  • Molecules – larger function blocks that contains application logic (UserForm, TasksList)
  • Pages – ok, this is not physics category 😉

Each level uses components from upper levels. And each level is harder to instantiate outside its real usage. According to my experience it is quite feasible to have Quarks and Atoms in catalog. I believe that MobX is helping here but I have no long term experience with Redux. Molecules depends too much on API and application data so it would be hard to mock it.

You can also think about catalog as mild form of test. You are testing that:

  1. You can reuse component, there are no hidden dependencies
  2. There is no clash among components when used together
  3. All components basically works