Archives 2005 - 2019    Search

Testing for an empty array in javascript

published Oct 01, 2015 12:34   by admin ( last modified Oct 01, 2015 12:34 )

Do:

if (myEmptyArray.length === 0) {} // true

Do not do:

if (myEmptyArray === []) {} // false

nor:

if (myEmptyArray == []) {} // false

nor:

if (!myEmptyArray) {}  // false

Random text string in Javascript

published Sep 28, 2015 09:40   by admin ( last modified Sep 28, 2015 09:43 )

This worked fine:

 

for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)

 

Which reminded me of this uuid one:

"00000000-0000-4000-8000-000000000000".replace(/0/g,function(){return(0|Math.random()*16).toString(16)})

Instructions for use of the TempScan GT-302A Thermometer

published Sep 19, 2015 06:50   by admin ( last modified Sep 19, 2015 06:59 )

Instructions for use of the TempScan GT-302A Thermometer

(Unofficial instructions, use at your own risk)

I just figured out how to use mine again, lost the instructions a decade ago or so. Here goes:

Switching it on
Switch it on by pressing the on/MEM button. This will set the device in memory recall mode, indicated by the “M” symbol to the left in the display. The SCAN button will cycle between the 10 most recent temperature takings, taking #1 being the most recent.

Go to temperature taking mode
Press the on button again to put the device in stand-by mode for temperature monitoring. Over a bit less than 10 seconds, a progress report will appear near the top of the display showing 3 progressively thicker bars and finally a pictogram of an ear, accompanied by a beep.

Take the temperature
When the ear pictogram has appeared, the device is ready for temperature monitoring. Position the tip of the device in ear (with appropriate protection) and depress the SCAN button. Release the SCAN button when the device has beeped. The temperature may now be read from the display and will be stored in memory as reading #1.

Switching off the device
Depress the on/MEM button and wait for the device to switch off the display. Release button.

-----

Shorter version:

Switch it on by pressing the on/MEM button. Press “on” again & wait 10 secs for small ear to appear in display. Take the temp by pressing SCAN until beep.


Avoiding grey-screen in tightvnc under Ubuntu 14.04

published Sep 14, 2015 12:55   by admin ( last modified Sep 14, 2015 12:55 )

This is on the right path although windows are not controllable for me:

#!/bin/sh

def

export XKL_XMODMAP_DISABLE=1

unset SESSION_MANAGER

unset DBUS_SESSION_BUS_ADDRESS


gnome-panel &

gnome-settings-daemon &

metacity &

nautilus &

gnome-terminal &

This and similar just greyscreened:

#!/bin/sh
 
xrdb $HOME/.Xresources
xsetroot -solid grey
export XKL_XMODMAP_DISABLE=1
echo starting gnome
gnome-session --session=ubuntu-2d &

 

#!/bin/sh
 
xrdb $HOME/.Xresources
xsetroot -solid grey
export XKL_XMODMAP_DISABLE=1
echo starting gnome
gnome-session

Read more: Link - Ubuntu VNC Grey Screen | onkea eLearning


Nouveau stopped my Acer V5-537G from crashing

published Sep 14, 2015 12:30   by admin ( last modified Sep 14, 2015 12:53 )

Switching from Ubuntu 32-bit to 64-bit (14.04 and 15.04) I got problems with my Acer V5-537G freezing irrevocably, and only a hard restart would get it back to life again.

However by selecting the open source Nouveau driver for my Nvidia Geforce GT750M graphics card, the deep-freezes stopped. Now there are just temporary freeze-ups.

 

BinaryDriverHowto/Nvidia - Community Help Wiki


ECMAScript 6 tutorial shows similarities to python

published Sep 09, 2015 11:09   by admin ( last modified Sep 09, 2015 11:09 )

Use ECMAScript 6 Today - Tuts+ Code Article is a tutorial that is readable, about ECMAScript (Javascript) 6. It is from 2013 so more features may be available directly in the browsers and in Node.js as of today.

As a python developer, the things that stand out as similar to python in ECMAScript 6 are:

  • for x of - Seems to do what pythons for x in does. Javascript has for x in since long but it returns more primitive things.
  • Maps - allows any object and not only strings to be the key, as in python dictionaries.
  • rest and spread - Seems to be like splat (star) in python, that is * although python also has ** for dictionaries (a.ka. maps in ECMAScript 6) which ECMAScript 6 does not have,
  • Default function parameters -seems to work as in python
  • Destructuring - Works as in python, but better. In python you can only return tuples, but in ECMAScript 6 you can also unpack things from objects
  • Array comprehensions - Just like list comprehensions in python, but using of instead of in syntax-wise as noted above.


 

In this article, we'll explore ten new features, with a significant focus on tools, browsers and transpilers.


Read more: Link - Use ECMAScript 6 Today - Tuts+ Code Article



Fast mass inserts into PostgreSQL

published Sep 04, 2015 03:32   by admin ( last modified Sep 04, 2015 03:32 )

The fastest way seems to be with a special tool:

pg_bulkload

Other than that, one can use COPY which is almost as fast and it means you have a data file that postgres can suck in: PostgreSQL: Documentation: 9.4: Populating a Database

This guy has tested it all and concludes that if for whatever reason you cannot use COPY you can make multirow INSERTS: select * from depesz; » Blog Archive » how to insert data to database – as fast as possible

Here is an example of how a multirow insert looks like in PostgreSQL

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');

 

There is an alternative to using COPY, which is the multirow values syntax that Postgres supports. From the documentation:


Read more: Link - postgresql - Whats the fastest way to do a bulk insert into Postgres? - Stack Overflow


Python dictionaries are pretty fast

published Sep 04, 2015 01:50   by admin ( last modified Sep 04, 2015 01:50 )

Yesterday I found myself looking at Google dense hash maps in C++. Googling around about them, I found a page from incise.org benchmarking different hashes in C++.

The author, on a lark he writes, decided to include dictionaries from Python and the corresponding data structure from Ruby. It turns out that python dictionaries aren't slow at all. Here two diagrams from the post:

 

They are fast, but take up a fair bit of memory. More diagrams and te text in the original post:

 

 

 

I've put together a set of benchmarks of what I consider to be the most prominent C and C++ hash table implementations. I've made the code available at Github. If you have any critiques or corrections, please post a comment below, email me, or fork the code and send me a pull request on Github.


 

Read more: Link - Hash Table Benchmarks


A logger for multi threaded python that does not make python segfault

published Aug 26, 2015 11:19   by admin ( last modified Aug 26, 2015 11:19 )

I introduced logging to a a python application that is multi threaded, and it started to segfault. I switched to ConcurrentLogHandler but it still segfaulted. I then switched to log over http with restapi-logging-handler, and in that way introduced a bit of complexity, but eventually decided to take another sweep at pypi to see if there wasn't a simpler solution and found this:

multiprocessing-logging 0.2.1 : Python Package Index

It seems to work like a charm in initial tests. I use it like this (abbreviated code):

import multiprocessing_logging

log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs', 'app.log')
mhandler = multiprocessing_logging.MultiProcessingHandler('worker-logger', sub_handler= logging.handlers.RotatingFileHandler(
              log_file, maxBytes=20000000, backupCount=0))

 

 


Prevent Spotify stealing your icons on Ubuntu 14.04

published Aug 26, 2015 11:10   by admin ( last modified Aug 26, 2015 11:25 )

Well, it isn't actually stealing your icons but when interacting with Spotify on Ubuntu 14.04 Linux, it has a tendency to make your icons for applications and other stuff disappear. It seems to do this by switching themes somehow or some sorts. However there is a way of preventing that.

AppArmor is a program that can control what other programs can and cannot do, with regards to file access. It is mainly used for security reasons to make sure that programs, especially binary-only ones whose code you cannot scrutinize (such as Spotify), are not secretly veering off stealing data from your hard disk or mucking about in other ways.

AppArmor can be configured to prevent Spotify from doing this icon-disappearing thingy. In your AppArmor profile for Spotify, add these two lines (tested by me):

# block sni-qt
deny /usr/lib/i386-linux-gnu/qt4/plugins/systemtrayicon/libsni-qt.so r,
deny /usr/lib/x86_64-linux-gnu/qt4/plugins/systemtrayicon/libsni-qt.so r,

Or use the entire profile here https://raw.githubusercontent.com/ozcanesen/spotify-indicator/master/spotify (not tested by me)

"First you need to disable Spotify's indicator. Spotify is using sni-qt package to show indicator. Removing that package will disable indicator but this solution will affect other Qt based applications like Skype. But we got another option to do that. after some research i discovered that this task can be done using AppArmor. I wrote an experimental AppArmor profile, copy this profile and reload AppArmor."

 

 

 


How to update one file from the same file in another branch (git)

published Aug 24, 2015 04:10   by admin ( last modified Aug 24, 2015 05:31 )

Untested by me. My need is to carry over just the changes in one file to the same file in another branch in the same git repository.

 

A simple command already solved the problem for me if I assume that all changes are committed in both branches A and B:
git checkout A
git checkout --patch B f


Read more: Link - git - How do I merge changes to a single file, rather than merging commits? - Stack Overflow


How to create a desktop item on Ubuntu 14.04

published Aug 15, 2015 12:47   by admin ( last modified Aug 15, 2015 12:47 )
In GNOME desktop, you can use gnome-desktop-item-edit to configure a desktop shortcut easily.
$ gnome-desktop-item-edit ~/.local/share/applications --create-new
In this example, gnome-desktop-item-edit will automatically create a desktop launcher file in ~/.local/share/applications.
If gnome-desktop-item-edit is not available (e.g., on Ubuntu), you can install it as follows.
$ sudo apt-get install --no-install-recommends gnome-panel


Read more: Link - How to create desktop shortcut or launcher on Linux - Xmodulo


How to run individual tests in python

published Aug 15, 2015 02:40   by admin ( last modified Sep 01, 2015 11:42 )

Tested by me.

You specify the path to the file where the tests are residing. After the path you add a string that specifies the place of the test inside that file, in dotted format:

python <path_to_file> <class_name>.<test_method_name>
python testMyCase.py MyCase.testItIsHot


Read more: Link - python - Running single test from unittest.TestCase via command line - Stack Overflow


How to kill Linux process by pattern of process name

published Aug 15, 2015 02:00   by admin ( last modified Aug 15, 2015 02:00 )

Don't point pkill at anything you do not have the intention to kill.
Use

pgrep -f pattern

first, so you know what you are killing.

Use pkill -f, which matches the pattern for any part of the command line
pkill -f my_pattern


Read more: Link - linux - How to kill all processes with a given partial name? - Stack Overflow


What's the best way of writing readable javascript applications?

published Jul 29, 2015 03:11   by admin ( last modified Jul 29, 2015 03:11 )

Update 2014-08-02, see also these links:

Which take a Haskell/FP perspective on improvements

 

Understanding the code in a javascript application can be hard work. There are at least two reasons for that:

1. TIMTOWDI (There is more than one way to do it)

There's more than one way to do it, a term I believe originally coined by Perl creator Larry Wall. C++ and  Scala are also often said to suffer from different coding styles, while python does not. Javascript is by many felt as lacking a lot of features, but can be cajoled to emulate these features.

Different people have different preferences and decide to go about "fixing" these things in different ways. The result of this is that there are different ways of importing functionality, tracking dependencies, emulating a class base OO language and so on and so forth. All these extensions still rely on javascript syntax which makes them contrived in source code.

Even such a common solution as the object literal demands a lot of knowledge of the coder about anonymous functions, closures and so on to figure out what's going on. Also other ways of going about things become syntax-heavy:

(function() {
  this.Example || (this.Example = {});
  this.Example.Models = { Product: employee };
  this.Example.Collections = { Products: employees }

}).call(this);

On top of that there is a plethora of frameworks each one if their own idiosyncratic view of the world.

2. Javascript is asynchronous

"Callback hell" is a term often used for the default way of handling asynchronicity in javascript. It makes it hard to follow the program execution by reading the source code. There are other ways of handling asynchronicity in javascript, but then we are back to reason number 1 above: a plethora of solutions. Another aspect, put forth by my friend Mikael, is that javascript has exceptions, which doesn't sit very well with the structure of the language. I guess because it becomes quite unclear through what an exception is supposed to bubble up.

Ideas

What can one do in order to write javascript that is readable and understandable by another coder?

  • One way is to present upfront the unchangeable parts of the application, whatever they might be. Basically present the conceptual model for the implementation of the application.
  • Frameworks, as much as I am not fond of frameworks in general, do make this possible.  Frameworks suffer from that you need to lean them and then use their tools which often aren't as useful and universally applicable as the language underneath: You end up trying to screw in screws with a hammer.
  • One idea is to divide program flow into two categories: hierarchical and sequential, where the file indicates level of hierarchy. So there is a top file that deals with overall logic of the program, and then there are files that each contain code that carry out lower-level tasks. Ideally there should be no leakage of these abstractions: You should be able to rely on a file being its own universe, and ideally testable on its own. This is called a Multilayered architecture.
  • Another idea is to use some kind of actor model and disentagle callback hell into objects and messages.
  • Or write in another language altogether and transcompile it to javascript, hopefully with a source map.
  • Or use Dart or Typescript.
  • Typescript contains a lot of extensions to javascript on the language level (instead of on a framework level), which may make the syntax cleaner.

There is no publicly available code for tracing a node.js program line by line

Or at least I cannot find any. Jetbrains has acquired spy.js but that one is not open source. The node-inspector people seem less enthusiastic  Enhancement: Full trace of program execution · Issue #366 · node-inspector/node-inspector

There is something close to tracing though for node.js (and I have tested it):

(alpha) njstrace lets you easily instrument and trace you code, see all function calls, arguments, return values, as well as the time spent in each function.


Software architecture: Invariant things should be apparent

published Jul 29, 2015 02:55   by admin ( last modified Jul 29, 2015 03:07 )

I'm trying to figure out how to make the source code of a system readable, readable meaning that you can understand the system on a high level, and also its constituent parts, from the source code.

It seems to me, and I am just starting thinking about this, that there things (patterns, frameworks, data schemas) that are invariant, that is they don't change over time as the system runs.  I'm sure the word invariant has other definitions, but for this text that was invariant means. These invariant things are the things you can communicate to the developer/maintainer.

So it would seem that you should be upfront with your invariant stuff. Like in a central file or as imports to it. And if you have stuff that is changing and amorphous, can it be abstracted into, or at least abstractly described, as something invariant? Then do that.

It seems to me that the more of these invariant stuff you can get into your system and systems description, the easier it the system will be to understand.

However the invariants, such as e.g. a framework's modus operandi, should not lead to convoluted solutions.

So the rule might be:

Use as many invariants as you can in your system, but not to the point of convoluted constructs.

Could be a two step process: Find and describe the invariants you already have, and see if you can refactor code into invariants.

The invariants can work on many levels: Using a language that discourages TIMTOWDI, using frameworks (iff they fit the problem) and taking time to create well defined abstractions for as many parts of the code as possible. Abstractions here means in the direction of readability and understandability.

Another question then arises, what abstractions are easy to undertstand? In user interface design one measure of the complexity of a GUI is the number of objects on the screen and how many alignment lines there are. Fewer objects and aligned objects lead to lower complexity. I wonder how could one measure the complexity of abstractions in source code? Metrics could include

  • how many inputs
  • if there is mutable state in there somewhere
  • if there are side effects
  • how many other files the code interacts with
  • the cyclomatic complexity

Abstractions already familiar to the developer are easier for him to use, and re-using known abstractions with some magical twist may work too. it also means it may be a good idea to have a toolbox of powerful abstractios that covers most of the things needed to be done.

Sometimes there is a like precipice when interactions between even simple components get too complex to understand. In which case the sub system needs to be "black-boxed" and not leak into the environment.


OpenBSD does not seem the platform of choice for a virtual machine host

published Jul 17, 2015 01:30   by admin ( last modified Aug 31, 2015 11:38 )

Update 2015-08-31: Something is on its way: 'virtualization support' - MARC

While searching I noticed there was not much activity in the field of using OpenBSD as a host operating system, with some solutions such as VirtualBox and Vmware not supported at all.

Theo de Raadt, BDFL of OpenBSD, has said the following about x86 virtualization:

x86 virtualization is about basically placing another nearly full kernel, full of new bugs, on top of a nasty x86 architecture which barely has correct page protection

So the support for x86 virtualization in OpenBSD is less than enthusiastic.

Read more: Link - 'Re: About Xen: maybe a reiterative question but ..' - MARC

Some info is available though:

Running a Linux VM on OpenBSD

Install and Run Windows Within QEMU Virtualization on OpenBSD or Linux

 


Cross compiling go programs to ARM with big pages

published Jul 14, 2015 04:30   by admin ( last modified Jul 15, 2015 02:20 )

Disclaimer: I have no idea of what I am doing.

I have a WD My Cloud with an ARM processor running on 4.x of WD's OS, which is  a Debian with large page sizes. From my 32-bit i386 normal page sized Linux I just tried this:

GOOS=linux GOARCH=arm GOARM=7 CGO_ENABLED=1 go build -ldflags "-R 65536" hello.go

And that runs on the WD device. Not sure if it just dumb luck, maybe it won'y work for bigger programs.

Update: I have now tried to compile a much bigger program and it seems it worked fine, but I got

fatal error: runtime: cannot map pages in arena address space

Which if I undertand golang correctly, is an out of memory error. I never thought of how much RAM my little NAS has. It turns out it has 277MB of which 45MB is free. That is a bit on the low side for the rather huge project I was trying to run. I had to drop the CGO_ENABLED flag but I think that is only needed if there is C code in the project. I have an idea of putting a USB stick into the USB3 port of the NAS and use that as swap to increase the memory available.

I got the flags and switches from here, but I think that guy also built a special golang compiler:

panic on arm cross compile - Google Groups

Cross compilation just got a whole lot better in Go 1.5 | Dave Cheney

 

 


Obnam - a backup solution

published Jul 12, 2015 07:25   by admin ( last modified Jul 12, 2015 07:25 )

Untested by me, but looks promising. I wonder how many people use it?

 

Obnam can also access the live data over SFTP, instead of via the local filesystem. This means you can run Obnam on, say, your desktop machine to backup your server, or on your laptop to backup your phone (assuming you can get an SSH server installed on your phone). Sometimes it is not possible to install Obnam on the machine where the live data resides, and then it is useful to do a pull backup instead: you run Obnam on a different machine, and read the live data over the SFTP protocol.


Read more: Link - Backups with Obnam