Tuesday 8 September 2015

C++ Interview

Questions to apply for C++ position:

1.  What will this method return ?
const char* getWhenToDoSomething()
  {
     string aziTodo("today");
     return aziTodo.c_str();
  }

2.  And this beautiful code, what will he print ?
 char *ptr = new char[6];
 strcpy(ptr, "12345");
 int *x = (int*)ptr;
 x += 1;
 char* ptr2 = (char*)x;
 std::cout << *ptr2 << std::endl;

  Tip: after casting from char to int, increment step will be bigger

    Next be 3 dragons. They they will ask MATH. 
        While hard stuff,
             use Google search when necessary.

3.   Write a class for Complex numbers.
   Also choose a solution for the fact that there can be two constructors :
   Complex(double realNumber, double imaginaryNumber)
   Complex(double angle, double absoluteValue)
          both taking 2 double arguments as parameters,

             what is the solution to take care of both constructors ?



4.   Write the method to return the Taylor exponential function for x.

    The same as the std::exp(double x) function. Provide the code to calculate the sum, the Taylor series sum( 1+ x + ...) and do not call std::exp(just maybe in assert to verify results).


5.   Final level: Euler's formula.
   Use both solutions from exercise 3. and 4. to calculate e to power i*x.
   Assert that the result is equal to cos(x) + i*sin(x)











                                  5 levels done, 
                                         next act will touch the map,
                                                     Bogdan Nicolae Visoiu

                                                         GL HF 

Sunday 12 July 2015

Cake cuts

You are presented with a rectangular cake whose sides are of length X and Y.
The cake has been cut into (N + 1) pieces by making N
 straight cuts along the first side and N straight cuts along the second side.

The cuts are represented by two non-empty zero-indexed arrays A and B
 consisting of N integers. More precisely, A[i] such that 0 ≤ i < N
 represents the position of a cut along the first side, and B[j] such that
 0 ≤ j < N represents the position of a cut along the second side.
We could also make a different number of cuts on the second side but for now the number of cuts is equal on both sides.

The goal is to find the K-th piece of cake in order of size, starting with
 the largest piece first. We will consider the size of a piece to be its area.

N is an integer within the range [1..40,000];
X and Y are integers within the range [2..400,000,000];
K is an integer within the range [1..(N+1)*(N+1)];
each element of array A is an integer within the range [1..X−1];
each element of array B is an integer within the range [1..Y−1];
A[i − 1] < A[i] and B[i − 1] < B[i], for every i such that 0 < i< N;
1 ≤ A[i] − A[i − 1], B[i] − B[i − 1] ≤ 10,000, for every i such that 0 < i < N;
1 ≤ A[0], B[0], X − A[N − 1], Y − B[N − 1] ≤ 10,000

   - first the biggest piece is searched, then the second biggest piece .. all is done K times, and when the K iteration is reached, the size of the biggest piece of cake that was found, is returned

Sunday 7 September 2014

Linux File Commands

  • pwd- Output the current directory that you are in
  • ls - list the content of the current directory
  • ls -a - list all the content, including hidden files
  • ls -l - list the content and its information
  • cd someFolder – change directory to someFolder
  • cd .. - Go up a directory
  • cd - - Return to the previous directory
  • cp source destination – Copy sourceto destination
  • cp -r source destination – Copy a folder recursively from source to destination
  • mv source destination - Move (or rename) a file from source to destination
  • rm someFile- Remove someFile
  • rm -f someFile - Remove someFile without prompt
  • rm -r folder - Remove a folder and its content recursively
  • mkdir foldername – Create a new folder foldername
  • rmdir foldername – Remove an empty folder
  • file someFile – Show the file type of someFile
  • cat file1 file2 – Concatenate file1to file 2
  • cat > someFile – Concatenate standard input to someFile
  • less someFile - View and paginate someFile
  • head someFile - Show first 10 lines of someFile
  • tail someFile - Show last 10 lines of someFile
  • chmod unknown file - Change file permission of file to unknown
  • chown user:group file - Change ownership of fileto userand group group
  • ln -s source destination – Create a link from source to destination

Tuesday 21 January 2014

Github - Add files

 
    For file safety and good place for sharing, GitHub is the place your project files should be. Either private or public.
Project files are located on your computer and you want to add them to github, how to do it :

 - register, login to the github site
 - on the site, use the Create Repository button and create one for your project
 - after repository was created you need to copy somewhere the  www address of your repository. Something like https://github.com/User_Name/Repository_Name.git

Windows:
 - download windows application from : GitHub for Windows
 - add and commit the files using the downloaded application

Linux:  
 - using terminal :
 - go to the project's directory cd the_project
 - git init to start git
 - add all the files to local list git add *
 - commit the files git commit -m "commit" 
 - tell to your computer where to add the files 
 git remote add origin https://github.com/User/RepName.git
              - add files to github git push origin master

Saturday 20 April 2013

Shader effects in .NET


          Starting with .NET 3.5 SP1 hardware accelerated effects can imbue your WPF applications with superpowers.
You assign shaders to any UIElement via the Effect property.
The way to do that is myButton.Effect = myEffect, where:
  • myEffect can be any object derived from System.Windows.Media.Effects
  • it can be BlurEffect, DropShadowEffect or ShaderEffect
  • first 2 are build-in shaders and you can use them straight away(MyButton.Effect = new BlurEffect() { ... };) and ShaderEffect is the fun and customisable one
  • do not use BitmapEffect or any derived classes as it is obsolete and badly designed a ShaderEffect has 2 parts : a shader written in HLSL(a text file that contains some HLSL code and has the .fx extension) and a C# wrapper (.cs class file) that will allow you to use the shader in your .NET application
I provide full code example for a wpf application that does color manipulation (RGB gain, brightness, saturation, contrast, gamma ) at https://github.com/Pzkgw/WpfColorManipulationShader. Please feel free to use it.

To create a ShaderEffect :

  • compile the .fx text file containing the shader code and obtain a binary .px file 
  • write the C# wrapper

To use a ShaderEffect:

  • the C# wrapper will define what properties are connected to the shader
  • a property is connected to a certain register and the shader will use the same register. Registers used for sharing constants start with C letter (eg: C0,C1 ..), and the ones used for sharing images(samplers) start with S. The first one available is S1, as S0 will be reserved for the input image.
  • in the following example both the shader and the wrapper will use the saturation information from the C0 register

        static readonly DependencyProperty SaturationProperty =
            DependencyProperty.Register("Saturation", typeof(double), typeof(ColorManiPulatorEffect),
            new UIPropertyMetadata(1.0, PixelShaderConstantCallback(0))/* assigned to sampler register C0 */);

        double Saturation
        {
            get { return (double)GetValue(SaturationProperty); }
            set { SetValue(SaturationProperty, value); }
        }
  • in case you need to send a image or a LUT to the shader :
           - create a WritableBitmap

        wBmp = new WriteableBitmap(256, 1, 96, 96, PixelFormats.Rgb24, null);

- make a buffer to hold image information you need to send and add the information(in this case a 3 x 256 LUT):
        byte[] buff = new byte[768];



        - send information to graphics board
            wBmp.WritePixels(new Int32Rect(0, 0,
                wBmp.PixelWidth, wBmp.PixelHeight),
                buff, wBmp.PixelWidth * wBmp.Format.BitsPerPixel / 8, 0);

            LutColor = new ImageBrush(wBmp);

       - define the dependency property:
        static readonly DependencyProperty LutColorProperty =
            ShaderEffect.RegisterPixelShaderSamplerProperty("LutColor",
            typeof(ColorManiPulatorEffect), 1 /* assigned to sampler register S1 */);

        Brush LutColor
        {
            get { return (Brush)GetValue(LutColorProperty); }
            set { SetValue(LutColorProperty, value); }
        }


How to write the shader:

  • i suggest you use a separated tool to write the shader, one that allows you to view real time what your shader looks like on a target image before you start the integration in your .Net application
  • i used Fx Composer from https://developer.nvidia.com/fx-composer, it's a bit more than what you need for a basic shader develop but it's very good at what it does and it allows you to visualy test your shader 
  • however a simple shader can be written using notepad, adding some simple code and saving the file with a fx extension :
sampler2D inSampler : register(S0);//input image, sent using register S0
float brightness : register(C0);//input value, sent using register C0

float4 main(float2 uv : TEXCOORD) : COLOR {//declaration of shader body
  float4 color = tex2D(inSampler, uv);//get the source color at the current uv texture coordinates 
//as a vector of 4 float values r,g,b,a
  return color * brightness;//multiply all the values with the brightness
}

Compile that .fx file and get a .px file:

  •  go to Visual Studio\Tools\External Tools , click add and introduce the details: 
 Title : Directx compiler Command : Path to fxc.exe(fx compiler) in DxSdk instalation Arguments : /DWPF /Od /T ps_2_0 /E $(ItemFileName)PS /Fo$(ProjectDir)$(ItemFileName).ps $(ItemPath)Initial directory : $(TargetDir)Uncheck "Close on exit" to make sure output of fx compilation is visible Add fx file to solution explorer and select it , and use the new added tool
  • Resulted ps file must be added to solution and set "Build action" to Resource(!!!)
  • alternative, you can also try addins : 
  1. for build: HLSL Shader Build Task
  2. for syntax(optional): NShader

Monday 5 November 2012

3D Math: Rotate to point

1. Problem description:

    We have :
              - 3d object that is (let's assume), centered on the Y axis
Cone was rotated to face the point (x1,y1,z1)



         - arbitrary point in space v1 with the coordinates (x1,y1,z1)

    We want :
        - obtain the rotation matrix or Quaternion that will rotate your object towards the arbitrary point (look at)
        - so, input parameter is v1 and output will be a 4x4 transformation matrix

    Optional :
        - other implementations to this issue will also take as input parameters a up vector (in this case is the OY axis) and a rotation center (i used (0,0,0))

2. Implementation :


         - we solve this by finding the axis-angle representation for the rotation
         - i see this as the most simplest way, as many frameworks will already have implementations for the all math required (Vector Normalization, Cross Product, Dot Product, Axis-Angle to Matrix conversion)
         - code example, using the Vector3, Matrix4 and Quaternion classes from LibGdx  :
vec.nor();  
float angle = (float) (180f / Math.PI * Math.acos(vec.dot(Yaxis)));

  vec.crs(Yaxis);

  if (vec.len() == 0) {
   vec.set(Zaxis);
  }
  quaterion.set(vec, angle);
  vec.crs(Yaxis);
  if (vec.len() == 0) {   vec.set(Zaxis);  }  quaterion.set(vec, angle);  transformMatrix.rotate(quaterion.conjugate());
             1. Normalize v1
             2  Find the angle between OY and v1 :
                        - calculate the dot product between the 2 vectors to get the cosine of the angle between them
                        - get the angle value in radians by applying arccosine
                        - convert to degrees if necessary
             3. Calculate cross product between the vectors, to obtain the rotation axis, the vector that is perpendicular on both OY and v1
             4. If the cross product is zero (vectors are parallel), we use OZ as rotation axis
             5. We now have a rotation axis and a rotation angle.
                 This can be used as input to create a transformation matrix or a Quaternion(indirect aproach).
                 If,  using something like the code above, make sure your roation matrix is set to identity
                 If, for some reason you need to do the math yourself, see Conversion_from_and_to_axis-angle

Saturday 6 October 2012

Android NDK, simple step by step guide

NDK allows you to use native(C, C++) code for your android application and it's a delicate subject.

The book "Android NDK Beginner's Guide" by Sylvain Ratabouil is 425 pages long and it's just a "beginner's guide". I will try to make this as short as possible, and provide a quick step by step guide to a working NDK example.

What you need :
  - working Android environment. I will use Eclipse on Windows for this so it will be easier to have the same. Working means you already succeed with a Hello World example
 - Android NDK - check http://developer.android.com/tools/sdk/ndk/index.html. As a alternative in future developemnts you can also use CristaX's custom made NDK, which has some improvements but for this example the one from Google is enough
 - Cygwin - only for windows devices
 - for simplicity, NDK should just be unzipped to a directory and Cygwin installed via installer. No headaches with environment variables & stuff for now.  For this example, it should be enough.

The steps :
So, we will do the sum of two numbers, written in native code and used in the android project  :

1. Prepare your android project  : 
                 - you need a android project in Eclipse to begin with
                 - in the root directory(same level with "src"), create a new directory called "jni"
                 - in a package of your choosing(for me : com.blogspot.soiuz - replace all later occurrences with your package name) create the SimpleLib java class and add the code :
package com.blogspot.soiuz; 
public class SimpleLib {
 static {
 System.loadLibrary("sLib");
 }
  // Native  - sum of two numbers
 public static native long add(int a, int b);
}


                  - this is the minimum you need : loadLibrary with the name of the native library we will later create(in this case "sLib") and at least one function declaration to use\test(in this case, adding of two numbers).
                 - based on the code here we will automatically generate a header file, so this is important
                 - open Command Prompt, and navigate to the bin directory of your android project
                 - to create a header file, we will use javah from the JDK tools by calling :
                                                                      javah -jni com.blogspot.soiuz.SimpleLib
                 - if it says it cannot find the class, make sure you can navigate from the bin directory, to SimpleLib.java by going com\blogspot\soiuz\SimpleLib. EG: you might need to step into the directory classes and run javah from there.
                 - in the pointed directory you will have com_blogspot_soiuz_SimpleLib.h, This is the C header file that we need to implement next.
                 - move this file to the jni folder and refresh the folder in Eclipse
                 - if you look into the file, you will have the add function written in a wierd manner : JNIEXPORT jlong JNICALL Java_com_blogspot_soiuz_SimpleLib_add , this is standard jni signature

2. Implementing the C library :
                -  right-click on the jni folder and choose New→File. Save it as sLib.c
                -  add code to it :

#include "com_blogspot_soiuz_SimpleLib.h"
long add(int a, int b) {
 return a+b;
}
JNIEXPORT jlong JNICALL Java_com_blogspot_soiuz_sLib_add(JNIEnv *env, jclass obj, jint a, jint b) {
 return add(a, b);
}

            - so we : add the header, implement our method in C, copy the method declaration for the generated header file and the variable names and call the native function. Easy.

3. The Makefile :
              - we have some files and this makefile will tell how they will be used
              - so, again, New -->File and create Android.mk
              - add text to it :
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := sLib
LOCAL_SRC_FILES := sLib.c
include $(BUILD_SHARED_LIBRARY)

            - no spaces empty lines, indentation.All text should start from begin of line
            - in the makefile we need to specify : Module library - sLib, files we want to build - sLib.c

4. Building all :
           - for this we need 2 tools : NDK , and if you want to do this on windows you also need Cygwin 
           - assuming both are installed and configured, open cygwin and execute the 2 next commands
           -  cd /cygdrive/d/workspace/AndroidNdk (navigates to android project root directory. All drives are mapped under cygdrive)                                       
           -  /cygdrive/d/install/android-ndk-r6b/ndk-build (form the Ndk installation directory, it will execute ndk-build)
           - if all was ok, it will show some text saying that libsLib.so was created in \libs\armeabi\.This is the needed library

5. Using, testing
          - SimpleLib.add(1,2); This is all you need to do
          - class SimpleLib is already created inside the android project and i suggest you make a class like that to act as a intermediary between java code and native library