Konda.eu

Tag Archives: Programming

5 comments

ASP.NET 5 and SignalR 3

SignalR is a great library from Microsoft for working with WebSockets. It's really fast and supports various fallbacks even for people that use browsers from stone age itself (IE6 for example, but let just hope nobody uses it anymore).

Of course not everything is that nice... When it comes to implementing it in ASP.NET 5 with absolutely NO documentation the entire process of setting this two frameworks/libraries together can be very, very painful.

First thing, to be able to download latest version of SignalR 3 for ASP.NET 5 MyGet repository needs to be referenced. I Added Nuget.config with the following content, but you can also add an URL to global NuGet configuration:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageRestore>
    <add key="enabled" value="True" /> <!-- Allow NuGet to download missing packages -->
    <add key="automatic" value="True" /> <!-- Automatically check for missing packages during build in Visual Studio -->
  </packageRestore>
  <packageSources>
    <add key="aspnetmaster" value="https://www.myget.org/F/aspnetmaster/api/v3/index.json" />
  </packageSources>
</configuration>

After that is set up, go to project.json and add the following line to dependencies:

"Microsoft.AspNet.SignalR.Server": "3.0.0-*"

The last thing needed to be done is to add SignalR to the application. To do that go to Startup.cs and make sure that you have the following line somewhere in Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...
    app.UseSignalR();
    // ...
}

At this step everything is ready to go. You can follow any SignalR tutorial, like this chat room for example. At this point there are no updated client side JavaScript libraries, version 2.2.0 works just fine but on the bad side you're still stuck with jQuery...

Some unfortunate souls like myself may stumble upon the following exception:

InvalidOperationException: No service for type 'Microsoft.AspNet.SignalR.Hubs.IJavaScriptProxyGenerator' has been registered.

At this point there are two choices. First one is to manually generate JavaScript files for all Hubs in the project, more about this you can read here, or the second option that I prefer is to register the default provider and all of the JavaScript code is automatically generated. To do this, simply go back to your Startup.cs into ConfigureServices method, and make sure that you have the following line inside:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSignalR();
    // ...
}

That's it! SignalR 3 should now successfully work together with ASP.NET 5 with automatic code generation.

No comments

Building OpenCV Stereo Vision - Calibration

Once the hardware is set up, entire rig must be calibrated. Cheap cameras have a lot of distortion. Two major distortions are radial and tangential. Radial is usually noticed on the edge of the screen where image is slightly curved. Edges that should be perfectly straight are suddenly slightly bended. With tangential distortion the problem is somewhat similar, only that certain points on the image appear closer than their neighbors, even though they are not.

In order to overcome this problems cameras must be calibrated. Therefore, a series of images is taken with a well know pattern. OpenCV uses chessboard as shown below.

chessboard

Continue reading

No comments

Building OpenCV Stereo Vision - Setup

For my most recent project I decided to build Stereo Vision for depth detection. The idea is simple. Two cameras working together similar to human eyes and detecting depth in the image. There are a few nice practical usages such as 3D pictures or point clouds, measuring distance to a point on an image and many more.

I used two Logitech's S7500 cameras. Pretty old cameras supporting resolution of 640x480px for video capture, but were enough to build a basic setup. It is not completely necessary, that cameras are of the same model, but it is highly recommended for better results. Different lens distortion, quality etc. can affect calibration, resulting in larger errors.

Cameras

I duct taped both cameras on a piece of wood so that they were completely stable. The distance between camera lenses was approximately 7 cm, similar to the distance between human eyes. I additionally aligned camera heads so they were as parallel as possible.

At this point everything is ready for the last step before making depth maps - calibration.

No comments

Taming Bootstrap 3 - Columns Same Height

During my recent work on a web design layout with bootstrap, I came across a layout that required all bootstrap columns to be the same height. After some experimenting with various positions such as absolute inside relative etc. and none of them working as they should, I ended up using display: flex and wrapped it in a snippet as bellow.

@media (min-width: 992px) {
    .row-eq-height, .row-eq-height > div[class*='col-'] {
        display: -webkit-flex;
        display: flex;
        flex:1 1 auto;
    }
}

Usage example and demo are shown here:

<div class="container">
    <div class="row row-eq-height">
        <div class="col-sm-4 col-1" style="background: red">
            Some Text
        </div>
        <div class="col-sm-4 col2" style="background: green"></div>
        <div class="col-sm-4 col3" style="background: blue"></div>
    </div>
</div>
No comments

Measuring Decibels from Microphone

This year was my third year as a mentor at a summer computer camp. We all had lots of fun, the only problem was that the participants - mostly teenage kids at the beginning of the high school - were quite talkative. Loud. To solve this problem a colleague and I came up with a nice solution for the next year.

Continue reading

No comments

Install, compile and link OpenCV from Terminal on Linux

Almost all my development is done in Visual Studio. Currently the best IDE in my opinion, but such tools can quickly spoil you. After being thrown in front of a Linux with only a terminal and an OpenCV dependent program that needed to compile, it was a struggle, but I found the following line to compile everything:

g++ `pkg-config --cflags --libs opencv` source.cpp -o program

And in case you haven't got OpenCV yet installed, you can use simple apt-get command:

sudo apt-get install libopencv-dev
No comments

C++ - Unicode Strings! Say Goodbye to std::string

During my years of programming in C++, the biggest pain were probably strings. There is no simple standard cross platform way for Unicode strings. std::string class by itself is also lacking a lot of methods for every day work. Comparing it to C#, Java or any other language is almost useless. Features as starts withends withto lower, to upper, trim and similar are all missing. It has ==, while Java doesn't. Yes, all of the functions above can be easily written with templates but it adds an extra load of work and maintenance, which we all try to avoid.

After a couple of years I finally decided to try ICU - International Components for Unicode. It's a C++ library for Unicode strings. It weights roughly 20MB when shipped with executable, but it's totally worth it. Linux, Apple, Google Chrome and other mayor companies or products use it. All of the above functions are provided and a couple more, all mayor code tables are supported, file access is with already familiar C like interface and as a bonus it's fully integrated with C++ streams.

icu::UnicodeString str = L"Hi ICU with öäüšćž!";
str = str.toLower();
str = str.append(" Foo!   ").trim();

cout << str << endl;

I urge you, give ICU a try!

No comments

C# - Dependency Injections and Automatic Registration with Autofac

Dependency Injections are an awesome design pattern for adding a layer of abstraction into your application for various services and providers. Those can be quickly changed by registering another class and an instance is simply acquired by specifying desired interface as a parameter in constructor therefore decreasing or completely removing factory design pattern.

The only thing I find disturbing is whenever a new dependent class is added it must be registered with dependency injection provider, manual by default. As I consider everything that must be changed or added on a completely different place bad practice, I help myself with the following snippet of code:

var builder = new Autofac.ContainerBuilder();
var assembly = Assembly.GetExecutingAssembly();
var assemblyTypes = assembly.GetTypes();

foreach (var type in assemblyTypes)
{
    // Ignore interfaces
    if (type.IsInterface)
        continue;

    var typeInterfaces = type.GetInterfaces();

    // Class should implement IDependecy or ISingletonDependency
    if (!typeInterfaces.Any(i => i.IsAssignableFrom(typeof(IDependency))))
        continue;

    var registration = builder.RegisterType(type).AsImplementedInterfaces();

    if (typeInterfaces.Any(i => i.IsAssignableFrom(typeof(ISingletonDependency))))
        registration.SingleInstance();
    else
        registration.InstancePerRequest();
}

Where IDependency and ISingletonDependency are:

public interface IDependency {}

public interface ISingletonDependency : IDependency {}
No comments

Java AES Decryption


Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead in /www/wp-content/plugins/latex/latex.php on line 47

Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead in /www/wp-content/plugins/latex/latex.php on line 49

A while ago I needed to do some AES decryption in Java.In order to use 128-bit AES key and IV should be exactly 16 characters long \(\) where 8 is a size of UTF-8 character).

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AESDemo {

    private static final String key = "Ma5(;8F:;2u%X[YW";
    private static final String IV = "*Z^L_=-**d^jbR*=";
    
    private static final String decrypt = "";
    
    public static void main(String[] args) throws Exception {
        SecretKeySpec s = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes("UTF-8"));
        
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, s, iv);
        
        byte[] original = cipher.doFinal(hexStringToByteArray(decrypt));
        System.out.println(new String(original));
    }
    
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}
No comments

C++ - OpenBLAS Matrix Multiplication


Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead in /www/wp-content/plugins/latex/latex.php on line 47

Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead in /www/wp-content/plugins/latex/latex.php on line 49

Matrices are extremely popular in many fields of computer science but many operations are slow, especially the useful ones like matrix multiplication where the complexity reaches \(\). There are of course algorithms to speed things up, but there are much faster ways that can fully utilize computer's hardware.

Every operation when doing matrix multiplication is independent which means it can be parallelized through multiple CPU cores or even put on a GPU if you want the best you can get. But sometimes just CPU is enough to avoid expensive copies between CPU and GPU and to reach speed ups up to 10 times. This is where OpenBLAS comes in.

Continue reading