posts - 19 , comments - 8 , trackbacks - 0

Wednesday, June 10, 2015

JavaScript Properties

Overview

The following code demonstrates how to use prototype base getters and setters in JavaScript.

function Colour(red, green, blue, alpha) {
    this.value = [red, green, blue, alpha];
    
}

Object.defineProperty(Colour.prototype, "red", {
    get: function () {
        return this.value[0];
    },
    set: function (x) {
        this.value[0] = x;
    }
});
    
Object.defineProperty(Colour.prototype, "green", {
    get: function () {
        return this.value[1];
    },
    set: function (x) {
        this.value[1] = x;
    }
});

Object.defineProperty(Colour.prototype, "blue", {
    get: function () {
        return this.value[2];
    },
    set: function (x) {
        this.value[2] = x;
    }
});

Object.defineProperty(Colour.prototype, "alpha", {
    get: function () {
        return this.value[3];
    },
    set: function (x) {
        this.value[3] = x;
    }
});

Colour.prototype.toString = function() {
    return "red=" + this.red + ", green=" + this.green + ", blue=" + this.blue + ", alpha=" + this.alpha;
};

var colour = new Colour(255, 128, 16, 100);

console.log(colour.toString());
console.log("red=" + colour.red);
console.log("green=" + colour.green);
console.log("blue=" + colour.blue);
console.log("alpha=" + colour.alpha);

colour.red = 0;
console.log(colour.toString());
console.log("red=" + colour.red);
console.log(colour.value);

Posted On Wednesday, June 10, 2015 9:21 AM | Comments (0) | Filed Under [ JavaScript Property Properties get set getters setters ]

Tuesday, May 19, 2015

Wpf TreeView MVVM view model

You can find my implementation of an MVVM TreeView model for WPF on github.

Link: https://github.com/rob-blackbourn/JetBlack.WpfTreeView.

Posted On Tuesday, May 19, 2015 9:34 AM | Comments (0) | Filed Under [ C# .Net MVVM TreeView WPF ]

Lightweight Linq style enumerators for Java

I have written a lightweight linq style enumerator for java. You can find it on github.

Link: https://github.com/rob-blackbourn/jetblack-java-utils.

Posted On Tuesday, May 19, 2015 9:32 AM | Comments (0) | Filed Under [ java linq enumerators ]

Indexing a one dimensional array by n dimensions

There's an example on how to index a 1-dimensional array by n-dimensions on github.

Link: https://github.com/rob-blackbourn/JetBlack.ArrayIndexing.

Posted On Tuesday, May 19, 2015 9:31 AM | Comments (0) | Filed Under [ C# .Net Array Indexing ]

Network programming with reactive extensions

I've written some examples of using reactive extensions for network communication. You can find the project on github.

Link: https://github.com/rob-blackbourn/JetBlack.Network.

Posted On Tuesday, May 19, 2015 9:28 AM | Comments (0) | Filed Under [ C# Reactive Extensions rx .Net Network Socket Select TcpClient TcpListener ]

Monads in C#

I've written some example moands with practical examples. Checkout the github project.

Link: https://github.com/rob-blackbourn/JetBlack.Monads.

Posted On Tuesday, May 19, 2015 9:25 AM | Comments (0) | Filed Under [ C# .Net Monads ]

Sunday, March 29, 2015

Using a Raspberry Pi For Lanc

Setup

  1. Download the Raspian distribution

    I used the one dated 2015-02-16, kernel version 3.18.

  2. Prepare the distribution

    • $ sudo apt-get update
    • $ sudo apt-get upgrade
  3. Fixup the network interface

    I have an Edimax EW-7811Un which uses the Realtek 8192cu driver. This is configured for a client side connection, and the power saving mode disconnects it from the network after a period of inactivity. I want this to be a server side component so I disabled the power saving mode.

    Create a file "/etc/modprobe.d/8192cu.conf" and add the following:

    # Disable power management

    options 8192cu rtw_power_mgnt=0 rtw_enusbss=0

  4. Install node

    Download the package

    $ wget http://node-arm.herokuapp.com/node_latest_armhf.deb

    Install the package

    $ sudo dpkg -i node_latest_armhf.deb
    $ node -v
    v0.12.0

  5. Install node serial port

    $ sudo npm -g install serialport

Writing the code

  1. Create a folder for the project and add the serialport package.

    $ mkdir lanc-controller
    $ cd lanc-controller
    $ npm install serialport

LANC

The first byte

In the LANC standard the first byte sent usually identifies the device being spoken to. The first nibble is often the type of the device (eg. 1=VTR, 2=Camera), and the second nibble is a unique identifier for the device.

BinaryHexDescription
0001 10000x18Normal command to VTR or video camera
0010 10000x28Special command to video camera
0011 10000x38Special command to VTR
0001 11100x1ENormal command to still video camera

Posted On Sunday, March 29, 2015 4:06 PM | Comments (1) |

Friday, December 19, 2014

A timeout dictionary in C#

Overview

My use case was a authentication system which stored user details. Fetching this information was expensive, so it was decided to only do this if the record was older than 15 minutes. The following code implements a dictionary were the values "timeout" after a given time period.

The timeout dictionary

The following code implements the dictionary. The constructor takes a date time provider which you can find in a previous post. This allows me to pass in a faster implementation of DateTime, and also allows me to test the code.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JetBlack.Common.Timers;

namespace JetBlack.Common.Collections
{
    public class TimeoutDictionary<TKey,TValue> : IDictionary<TKey,TValue>
    {
        private readonly IDictionary<TKey, TValue> _valueMap;
        private readonly IDictionary<TKey, DateTime> _timeMap;

        private readonly IDateTimeProvider _dateTimeProvider;
        private readonly TimeSpan _timeout;

        public TimeoutDictionary(IDateTimeProvider dateTimeProvider, TimeSpan timeout)
        {
            _dateTimeProvider = dateTimeProvider;
            _timeout = timeout;
            _valueMap = new Dictionary<TKey, TValue>();
            _timeMap = new Dictionary<TKey, DateTime>();
        }

        private void Reap(DateTime now)
        {
            ISet<TKey> expiredKeys = new HashSet<TKey>();
            foreach (var item in _timeMap)
            {
                if (now - item.Value >= _timeout)
                    expiredKeys.Add(item.Key);
            }
            foreach (var key in expiredKeys)
            {
                _valueMap.Remove(key);
                _timeMap.Remove(key);
            }
        }

        public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            Reap(_dateTimeProvider.Now);
            return _valueMap.ToList().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Add(KeyValuePair<TKey, TValue> item)
        {
            Add(item.Key, item.Value);
        }

        public virtual void Add(TKey key, TValue value)
        {
            var now = _dateTimeProvider.Now;
            DateTime time;
            if (!_timeMap.TryGetValue(key, out time))
            {
                _valueMap.Add(key, value);
                _timeMap.Add(key, now);
            }
            else if (now - time >= _timeout)
            {
                _valueMap[key] = value;
                _timeMap[key] = now;
            }
            else
                throw new ArgumentException("An element with the same key already exists", "key");
        }

        public virtual void Clear()
        {
            _valueMap.Clear();
            _timeMap.Clear();
        }

        public virtual bool Contains(KeyValuePair<TKey, TValue> item)
        {
            DateTime time;
            if (!_timeMap.TryGetValue(item.Key, out time))
                return false;

            if (_dateTimeProvider.Now - time < _timeout)
                return Equals(_valueMap[item.Key], item.Value);

            _valueMap.Remove(item.Key);
            _timeMap.Remove(item.Key);

            return false;
        }

        public virtual void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            Reap(_dateTimeProvider.Now);
            foreach (var item in _valueMap)
                array[arrayIndex++] = item;
        }

        public virtual bool Remove(KeyValuePair<TKey, TValue> item)
        {
            DateTime time;
            if (!_timeMap.TryGetValue(item.Key, out time))
                return false;

            var isStale = _dateTimeProvider.Now - time >= _timeout;
            var isEqual = Equals(_valueMap[item.Key], item.Value);
            if (isStale || isEqual)
            {
                _timeMap.Remove(item.Key);
                _valueMap.Remove(item.Key);
            }

            return isEqual && !isStale;
        }

        public virtual bool Remove(TKey key)
        {
            DateTime time;
            if (!_timeMap.TryGetValue(key, out time))
                return false;

            _timeMap.Remove(key);
            _valueMap.Remove(key);

            return _dateTimeProvider.Now - time >= _timeout;
        }

        public virtual int Count
        {
            get
            {
                Reap(_dateTimeProvider.Now);
                return _valueMap.Count;
            }
        }

        public bool IsReadOnly { get { return false; } }

        public virtual bool ContainsKey(TKey key)
        {
            DateTime time;
            if (!_timeMap.TryGetValue(key, out time))
                return false;

            if (_dateTimeProvider.Now - time < _timeout)
                return true;

            _valueMap.Remove(key);
            _timeMap.Remove(key);

            return false;
        }

        public virtual bool TryGetValue(TKey key, out TValue value)
        {
            DateTime time;
            if (_timeMap.TryGetValue(key, out time) && _dateTimeProvider.Now - time < _timeout)
                return _valueMap.TryGetValue(key, out value);

            value = default(TValue);
            return false;
        }

        public virtual TValue this[TKey key]
        {
            get
            {
                DateTime time;
                if (_timeMap.TryGetValue(key, out time))
                {
                    if (_dateTimeProvider.Now - time < _timeout)
                        return _valueMap[key];

                    _valueMap.Remove(key);
                    _timeMap.Remove(key);
                }

                throw new KeyNotFoundException();
            }
            set
            {
                _valueMap[key] = value;
                _timeMap[key] = _dateTimeProvider.Now;
            }
        }

        public virtual ICollection<TKey> Keys
        {
            get
            {
                Reap(_dateTimeProvider.Now);
                return _valueMap.Keys;
            }
        }

        public virtual ICollection<TValue> Values
        {
            get
            {
                Reap(_dateTimeProvider.Now);
                return _valueMap.Values;
            }
        }
    }
}

The thread safe implementation

The following code adds thread safety.

using System;
using System.Collections.Generic;
using JetBlack.Common.Timers;

namespace JetBlack.Common.Collections
{
    public class ConcurrentTimeoutDictionary<TKey,TValue> : TimeoutDictionary<TKey,TValue>
    {
        public ConcurrentTimeoutDictionary(IDateTimeProvider dateTimeProvider, TimeSpan timeout)
            : base(dateTimeProvider, timeout)
        {
        }

        public override void Add(TKey key, TValue value)
        {
            lock (this)
            {
                base.Add(key, value);
            }
        }

        public override void Clear()
        {
            lock (this)
            {
                base.Clear();
            }
        }

        public override bool Contains(KeyValuePair<TKey, TValue> item)
        {
            lock (this)
            {
                return base.Contains(item);
            }
        }

        public override bool ContainsKey(TKey key)
        {
            lock (this)
            {
                return base.ContainsKey(key);
            }
        }

        public override void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            lock (this)
            {
                base.CopyTo(array, arrayIndex);
            }
        }

        public override int Count
        {
            get
            {
                lock (this)
                {
                    return base.Count;
                }
            }
        }

        public override IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            lock (this)
            {
                return base.GetEnumerator();
            }
        }

        public override ICollection<TKey> Keys
        {
            get
            {
                lock (this)
                {
                    return base.Keys;
                }
            }
        }

        public override bool Remove(KeyValuePair<TKey, TValue> item)
        {
            lock (this)
            {
                return base.Remove(item);
            }
        }

        public override bool Remove(TKey key)
        {
            lock (this)
            {
                return base.Remove(key);
            }
        }

        public override bool TryGetValue(TKey key, out TValue value)
        {
            lock (this)
            {
                return base.TryGetValue(key, out value);
            }
        }

        public override ICollection<TValue> Values
        {
            get
            {
                lock (this)
                {
                    return base.Values;
                }
            }
        }

        public override TValue this[TKey key]
        {
            get
            {
                lock (this)
                {
                    return base[key];
                }
            }
            set
            {
                lock (this)
                {
                    base[key] = value;
                }
            }
        }
    }
}

Testing

Finally we can test the time dependent code!

using System;
using JetBlack.Common.Collections;
using JetBlack.Common.Timers.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JetBlack.Common.UnitTest.Collections
{
    [TestClass]
    public class TimeoutDictionaryUnitTest
    {
        [TestMethod]
        public void TestContainsKey()
        {
            var dateTimeProvider = new DiscreteDateTimeProvider(DateTime.Today, TimeSpan.FromMilliseconds(200));
            var timeoutDictionary = new TimeoutDictionary<string, int>(dateTimeProvider, TimeSpan.FromMilliseconds(500));

            timeoutDictionary.Add("one", 1);
            Assert.IsTrue(timeoutDictionary.ContainsKey("one"));
            Assert.IsTrue(timeoutDictionary.ContainsKey("one"));
            Assert.IsFalse(timeoutDictionary.ContainsKey("one"));
        }
    }
}

Posted On Friday, December 19, 2014 9:17 AM | Comments (1) | Filed Under [ C# TimeoutDictionary ]

Thursday, December 18, 2014

Testing code with time dependency in C#

Introduction

Testing code that is date or time dependent is clearly problematic! The first step is to create an interface which we will use instead of accessing the DateTime object itself.

The interface

using System;

namespace JetBlack.Common.Timers
{
    public interface IDateTimeProvider
    {
        DateTime Today { get; }
        DateTime Now { get; }
        long Ticks { get; }
    }
}

A native date time provider

We can wrap up the standard date time object with the following code.

using System;

namespace JetBlack.Common.Timers
{
    public class DateTimeProvider : IDateTimeProvider
    {
        public DateTime Today { get { return DateTime.Today; } }
        public DateTime Now { get { return DateTime.Now; } }
        public long Ticks { get { return DateTime.Now.Ticks; } }
    }
}

A test provider

The following code implements a test provider which takes a start date/time and adds an increment every time it is called.

using System;

namespace JetBlack.Common.Timers.Testing
{
    public class DiscreteDateTimeProvider : IDateTimeProvider
    {
        private readonly TimeSpan _interval;
        private DateTime _dateTime;

        public DiscreteDateTimeProvider(DateTime startDateTime, TimeSpan interval)
        {
            _dateTime = startDateTime;
            _interval = interval;
        }

        public DateTime Today
        {
            get { return Now.Date; }
        }

        public DateTime Now
        {
            get
            {
                var prev = _dateTime;
                _dateTime += _interval;
                return prev;
            }
        }

        public long Ticks { get { return Now.Ticks; } }
    }
}

A faster DateTime

Finally we can improve the performance of time dependent code by implementing our own DateTime class. The problem with the system supplied implementation is speed. While the CPU contains timers, it does not know the time. This ability is provided by the real time clock (RTC) which is a separate chip on the motherboard that has a battery to keep it running when the computer is switched off. Whenever we call DateTime the CPU makes a call to the RTC which takes time (a lot of time).

The solution is to initialise the datetime once, and from then on query the internal timers in the CPU. This means the CPU only has to call the RTC once.

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace JetBlack.Common.Timers
{
    public class FastDateTime : IDateTimeProvider
    {
        private static DateTime _epochDateTime = default(DateTime);
        private static readonly long CountDivisor = QueryPerformance.Frequency / CountsPerMs;
        private static long _epochCount = long.MaxValue;
        private const long TicksPerMs = 10000;
        private const long CountsPerMs = 1000;

        public static long Ticks
        {
            get { return Now.Ticks; }
        }

        public static DateTime Now
        {
            get
            {
                var count = QueryPerformance.Counter;

                if (count < _epochCount)
                {
                    _epochDateTime = DateTime.Now;
                    _epochCount = count;
                    return _epochDateTime;
                }

                var elapsed = count - _epochCount;
                var ticks = (elapsed * TicksPerMs) / CountDivisor;
                return _epochDateTime.AddTicks(ticks);
            }
        }

        public static DateTime Today
        {
            get { return Now.Date; }
        }

        #region IDateTimeProvider

        public static IDateTimeProvider Provider = new FastDateTime();

        DateTime IDateTimeProvider.Now
        {
            get { return Now; }
        }

        DateTime IDateTimeProvider.Today
        {
            get { return Today; }
        }

        long IDateTimeProvider.Ticks
        {
            get { return Ticks; }
        }

        #endregion

        private static class QueryPerformance
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

            [DllImport("kernel32.dll", SetLastError = true)]
            private static extern bool QueryPerformanceFrequency(out long frequency);

            /// <summary>
            /// Retrieves the current value of the high-resolution performance counter.
            /// </summary>
            public static long Counter
            {
                get
                {
                    long performanceCount;
                    if (!QueryPerformanceCounter(out performanceCount))
                        throw new Win32Exception();
                    return performanceCount;
                }
            }

            /// <summary>
            /// Returns the number of counts per second for the high-performance counter.
            /// </summary>
            public static long Frequency
            {
                get
                {
                    long frequency;
                    if (!QueryPerformanceFrequency(out frequency))
                        throw new Win32Exception();
                    return frequency;
                }
            }
        }
    }
}

Posted On Thursday, December 18, 2014 4:55 PM | Comments (0) | Filed Under [ C# DateTime Testing ]

Array pooling in C#

Introduction

The following class reduces garbage collection by maintaining a pool of allocated arrays.

DisposableValue

I wanted a simple way to manage the lifetime of the arrays. To do this I have borrowed an idea from reactive extensions

using System;

namespace JetBlack.Common
{
    public class DisposableValue<T> : IDisposable
    {
        private readonly Action _dispose;

        public DisposableValue(T value, Action  dispose)
        {
            _dispose = dispose;
            Value = value;
        }

        public T Value { get; private set; }

        public void Dispose()
        {
            _dispose();
        }

        public static DisposableValue<T> Create(T value, Action dispose)
        {
            return new DisposableValue<T>(value, dispose);
        }
    }
}

ArrayPool

The actual array pool is also quite simple. The public interface provides an allocater, a resizer, a way to clear down the cache, and a field representing the empty array. This is a minor optimisation, as an empty array is immutable we only need one.

using System;
using System.Collections.Generic;

namespace JetBlack.Common
{
    public class ArrayPool<T>
    {
        private readonly Dictionary<int, Stack<T[]>> _pool = new Dictionary<int,Stack<T[]>>();

        public readonly T[] Empty = new T[0];

        public DisposableValue<T[]> AllocateDisposable(int size)
        {
            var array = Allocate(size);
            return DisposableValue<T[]>.Create(array, () => Free(array));
        }

        public DisposableValue<T[]> Resize(DisposableValue<T[]> source, int size)
        {
            if (size < 0) throw new ArgumentOutOfRangeException("size", "Must be positive.");

            var dest = AllocateDisposable(size);
            Array.Copy(source.Value, dest.Value, size < source.Value.Length ? size : source.Value.Length);
            source.Dispose();
            return dest;
        }

        public virtual void Clear()
        {
            _pool.Clear();
        }

        internal virtual T[] Allocate(int size)
        {
            if (size < 0) throw new ArgumentOutOfRangeException("size", "Must be positive.");
            
            if (size == 0) return Empty;

            Stack<T[]> candidates;
            return _pool.TryGetValue(size, out candidates) && candidates.Count > 0 ? candidates.Pop() : new T[size];
        }

        internal virtual void Free(T[] array)
        {
            if (array == null) throw new ArgumentNullException("array");
            
            if (array.Length == 0) return;

            Stack<T[]> candidates;
            if (!_pool.TryGetValue(array.Length, out candidates))
                _pool.Add(array.Length, candidates = new Stack<T[]>());
            candidates.Push(array);
        }
    }
}

Concurrency

Concurrent support is fairly straightforward.

namespace JetBlack.Common
{
    public class ConcurrentArrayPool<T> : ArrayPool<T>
    {
        internal override T[] Allocate(int size)
        {
            lock (this)
            {
                return base.Allocate(size);
            }
        }

        internal override void Free(T[] array)
        {
            lock (this)
            {
                base.Free(array);
            }
        }

        public override void Clear()
        {
            lock (this)
            {
                base.Clear();
            }
        }
    }
}

Posted On Thursday, December 18, 2014 3:57 PM | Comments (1) | Filed Under [ C# array ArrayPool ]

Powered by: