vendredi 27 décembre 2013

C++: How to handle exception in CTOR

Yesterday I was reading that thread on Linkedin, and I realized once again that the exception handling in/or around a constructor(CTOR) is still an obscure topic as only one commenter mentioned the correct try-catch form for CTOR that can handle every exception even those coming from the initialization list.
The main problem when an exception occur during a CTOR is what have we to do for cleaning memory allocated on the heap.
To summarize the easiest way to handle exception, I produced the following example.

The output will be (I added some comments:
  • object_t CTOR ==> object_t allocation in our initializer list put in a smart_ptr (1)
  •  test_t CTOR ==> here we enter in the test_t CTOR Impl
  • object_t CTOR ==> we allocated a new object (2)
  • … here we have thrown the exception
  • object_t DTOR ==> the smart pointer object is on the stack, so the stack unwinding run and the memory allocation (1) is cleaned
  • here we handle our dynamic allocation ==> we are now in the CTOR catch section, as we have correctly ordered our data member we can check `if (ptr != nullptr)` and delete it if needed.
  • object_t DTOR ==> now the memory allocation (2) is released.
  • exception just to test... ==> as we have and should always RETHROW the exception, we catch it!

Conclusion: If we based all our class on that model, there is no reason anymore to fear about memory leaks.

mardi 24 décembre 2013

Use Beyond Compare as SVN diff tool under Linux

Today a quick note on that topic as I extended my own configuration with that tricks. BeyondCompare is a well known tool to compare and merge different  version file.

I used it a lot combined with ToirtoiseSVN, but as I worked more and more under linux using Remote Workstation, I would also use it. But I mainly work on remote workstation using a putty prompt. I will not describe here how to setup bcompare on a linux workstation, but it’s the 1st thing todo.

Next you have to follow my previous post to redirect the all X application to your local (I mean Windows 7 in my case) X11 server.

Now when you run “svn diff” on a file, you expect to use bcompare. To achieve that goal, follow me step by step.

cd ~

touch .subversion/bcompare_svn.sh

nano .subversion/bcompare_svn.sh

COPY/PASTE the folllowing in that script:

#!/bin/bash

/usr/bin/bcompare $6 $7 &

exit 0

Set execution permission

chmod 755 .subversion/bcompare_svn.sh

nano .subversion/config

Add that line just after “# diff-cmd = diff_program (diff, gdiff, etc.)”


diff-cmd=/home/YOURFOLDER/.subversion/bcompare_svn.sh

And done !

Now at each svn diff  command you start, BeyondCompare will start and display on the own PC.

vendredi 13 décembre 2013

STL String to/from wide string

Yesterday I spend sometimes to help one of my teammate with a piece of code he wrote to convert a std::string  into a std::wstring. At the beginning it seems to be a complex issue for him and he used a complex C based code managing wchar buffer convert char to wchar with mbstowcs.

But finally as often the STL provide everything we need to convert one string type into the other and it’s quite simple.

I quickly use Ideone to demonstrate how to deal with:

As you see we can just use the iterator (old-style or new style like below)

wstring ws(s.begin(), s.end()); or wstring ws(begin(s), end(s));

lundi 2 décembre 2013

Redirect X from remote linux machine on your windows host.

When you use a remote linux machine from your own Windows Desktop machine using a putty connection, you can easily redirect X application on your desktop.

To do that, there is several steps:

1) You need to have a cygwin setup on your windows host, and follow the following instruction to setup all package required to run a X server.

2) Setup your putty connection to allow X11 forwarding.

Putty-Enable-X11Forwarding

To check if everything is OK, restart a connection and from linux prompt, check the value of “DISPLAY” (echo $DISPLAY). It should return something similar to:

localhost:13.0

3) To start your windows X11 server, create a shortcut file in your cygwin folder.

the target will be: C:\ cygwin\bin\run.exe /usr/bin/bash.exe -l -c /bin/startxwin.exe

And for its name, “StartX” is a good choice!

Double-click on that shortcut and check that you now have the X11-server icon in your Windows systray.

4) To run that server every time you start your window session, save a copy of that shortcut in:

%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

5) Final check, start xclock from your Linux prompt, the xclock windows will appear on your Windows Desktop !

vendredi 29 novembre 2013

Text processing: Word List Challenge.

I read this morning a question on Stackoverflow where user tried to solve that text processing challenge with a really complex code.

With only 3 line of code we can do that in C++. Using STL and optionally a BOOST header.

It works in 3 steps:

1) transform to lower case,

2) split using multiple delimiters (boost::any_of),

3) sort the resulting vector.

….

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

#include "boost/algorithm/string.hpp"

const char* testStr = "This is. a sample piece of, text to illustrate \n this problem.";

int main(int argc, char* argv[])
{
string inputText(testStr);
cout << inputText << endl << "*******************" << endl;
vector<string> strs;
boost::split(strs,boost::algorithm::to_lower_copy(inputText),boost::is_any_of("\t ,\n,,,."),boost::token_compress_on);
cout << "list : " << strs.size() << endl;
cout << "without sort\n", copy(begin(strs), end(strs), ostream_iterator<string>(cout, "\n"));
std::sort(strs.begin(), strs.end());
cout << "with sort\n", copy(begin(strs), end(strs), ostream_iterator<string>(cout, "\n"));


return 0;
}

lundi 25 novembre 2013

Override a default STL operator >>

In that question, user need to override the default STL operator >> for complex number. First keep in mind that the STL provide a template for complex number define in <complex> and that this type come with its own syntax for I/O.

By default the syntax is (real,imag).

As the user want to use: real+imagi, we have to change the default behavior.

In the following you will see how I wrote a new global function to override the default operator and how I use a Regular Expression to extract the real and imaginary number.

template<class _Ty> inline istream& operator>>(istream& _Istr, complex<_Ty>& _Right)
{
// extract a complex<_Ty> with syntax REAL+IMAGi
long double _Real = 0;
long double _Imag = 0;
string s; _Istr >> s;
string regexPattern = string(R"r(([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)\s*\+\s*([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)i)r");
regex reg(regexPattern);
smatch sm; // same as std::match_results<const char*> cm;
regex_match (s,sm,reg);

_Real = std::atof(sm[1].str().c_str());
_Imag = std::atof(sm[2].str().c_str());

_Right = std::complex<_Ty>((_Ty)(_Real), (_Ty)(_Imag));

return (_Istr);
}


There is place for improvement in that version:


  • no match

  • match are not number

  • etc…

But it’s a good example of how to start!

vendredi 22 novembre 2013

FFMPEG from Compressed to RAW video.

I f consult some of my previous post, you may noticed that I’m an ffmpeg fan.

I often used ffmpeg command line to pipe raw video, in my own soft or some soft I develop in my professional environment. But I recently discover a good to share trick about ffmpeg.

Imagine a video file of 20min at 24fps, you have extract those information using the ffmpeg –i command. But when you extract the raw video frame in a file, you discover that the output file is bigger than expected (like a Tardis….).

Example of simple decoding as YUV 420p:

ffmpeg –I input.mp4 –c:v raw_video –pix_fmt yuv420p – >> output.yuv

the reason can be that if the input file hasn’t PTS corresponding to a Constant Frame-Rate (CFR), ffmpeg duplicate or drop some frames.

hopefully ffmpeg is explicit and full of useful information to troubleshoot those situation, for example in the following ffmpeg output latest line we see that it “duplicate” 60 frame.

frame=  119 fps=0.0 q=0.0 Lsize=  160650kB time=00:00:02.00 bitrate=657102.5kbits/s dup=60 drop=0

To prevent that the parameter to use is “-vsync”.


-vsync parameter

Video sync method. For compatibility reasons old values can be specified as numbers. Newly added values will have to be specified as strings always.

0, passthrough

Each frame is passed with its timestamp from the demuxer to the muxer.

1, cfr

Frames will be duplicated and dropped to achieve exactly the requested constant frame rate.

2, vfr

Frames are passed through with their timestamp or dropped so as to prevent 2 frames from having the same timestamp.

drop

As passthrough but destroys all timestamps, making the muxer generate fresh timestamps based on frame-rate.

-1, auto

Chooses between 1 and 2 depending on muxer capabilities. This is the default method.


So to only have the encoded frame in our output the correct line is:

ffmpeg –I input.mp4 –vsync 0 –c:v raw_video –pix_fmt yuv420p – >> output.yuv

OpenMP support in different compiler.

OpenMP is a powerful and useful standard supported by many compiler to introduce parallelism (multi-threading) in your C/C++ source code with “minimal effort.

But, depending of your developing environment, you may face some problems and the 1st from my POV is that if you compile the same source code with GCC/G++ and Visual Studio C++ compiler you cannot use the complete and last OpenMP functionnalities.

The reason is that VS' C/C++ compiler (even the last version VS’2013) only support OpenMP 2.0. It’s an old version released in March 2002.

While OpenMp support in VS was frozen since its 1st introduction in VS’2005, GCC/G++ support evolve and a recent GCC version like v4.9 support the last OpenMP v4.0 (July 2013).

You can consul that page to find which version of OpenMP is supported in the GCC version you used to build.

Note that CLang also provide OpenMP support but only for the v3.1.

---------------------------------

So, to conclude if you develop for several compiler and want to share your source code you should choose to keep using the ‘old’ v2.0. It’s a bit silly because the 3.1 and v4 introduce a lot of new functionalities like task, simd, device, etc …

Extract PTS from a video stream

 

I often used ffmpeg to extract raw_video data from compressed file or device stream, but when we do that we lost a useful information the PTS (presentation timestamp) of each frame.

For example, if you have a program using the output of ffmpeg (pipe mode),

ffprobe –show_frames –select_streams v:0 input.ts | grep pkt_pts_time= >> output.pts

output.pts file will contain:

pkt_pts_time=0.000000
pkt_pts_time=0.034022
pkt_pts_time=0.067689
…..

those number are in seconds, so you can use them easily in any software you develop.

mardi 5 novembre 2013

C# Any CPU executable using native DLL

Once again I meet an issue today when starting a software on my Win7 64bit platform. It's not the 1st time that when I start a soft, it crash immediately with a 0xe0434f4d error/exception code, but everything I'm wondering why ?

In fact if you see that behavior,, it could means that you are running a .Net executable build to start on "Any CPU" but that native win32/x86 DLL are require. On an old 32bit only windows system it work fine, but on a 64bit XP or Win7, the .Net process don't start in WoW64 and will not be able to load the x86 DLL.

To check and fix that issue, you need CorFlags. It's a simple executable that you can find for example in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin.

For example using: CorFlags proc.exe
I got:

Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32
CorFlags  : 1
ILONLY    : 1
32BIT     : 0
Signed    : 0


As the 32BIT flags is set to 0 and that the ILONLY is set to 1, that process can start as a 32bit executable on a 32bit only PC or as a 64bit executable on a 64bit PC.

To change that state you can update the PE header with: CorFlags /32BIT+ proc.exe
Run again: CorFlags proc.exe

Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32
CorFlags  : 3
ILONLY    : 1
32BIT     : 1
Signed    : 0


Now you can start proc.exe on any CPU and OS, 32bit only or 64bit, It will always start as a 32bit executable (WoW64 mode on a 64 bit Windows OS).

From Visual Studio if you want to exactly specify the target, you can use the C#/.Net Project page.


mardi 15 octobre 2013

C++ - Finding all arrangement (a.k.a permutation) of object.

When you have a set of object, you may have to build all arrangement of those object.

Example, a vector num = {0,1,2}, you want the 3! permutations ( {0,1,2}, {0,2,1}, {1,0,2},{1,2,0},{2,0,1},{2,1,0} )

Hopefully the Standard Template Library (STL) come with some useful function for that, but their behavior really depend of the operator you provide with your objects.

If you take a look at next_permutation, it stands to "Rearranges the elements in the range [first,last) into the next lexicographically greater permutation." but that point rely to the "bool operator( const T& elt)" of the object (class/type) you use.

A quick example of the pitfall in which I fall today. Imagine a type point define like below:

struct pos_t {
int x; int y;
pos_t(){x = 0 ; y = 0;}
pos_t(int X, int Y){x=X; y=Y;}
pos_t(pos_t const & r) {x = r.x; y=r.y;}
pos_t& operator=(pos_t const & r) {x = r.x; y=r.y; return *this;}
bool operator < ( pos_t const & p) const
{
return (x + y)
< ( p.x+p.y);
}
friend ostream& operator << (ostream &o, const pos_t& p)
{
return o << "(" << p.x << "," << p.y << ")";
}
};


Now using the following list of point,  (1,3) ,(2,2) , (3,0) ,(3,1), you expect to get 24 permutations. But you will not !!!! The reason is the operator < we define in our class/struct. Using that operator (1,3) is similar to (3,1) and that the reason why when using next_permutation we implicitly use the less-than operator and we fail.

To really get all permutation out-of next_permutation we need to define clear compare operator.


bool operator < ( pos_t const & p) const
{
  return (x < p.x) || ((x == p.x) && (y < p.y));
}


Now using our list of 4 points, we can call a simple loop to store and display all permutations. See below a piece of code extract of Coding Challenge call "Treasure Hunter" (a kind of A* algorithm can be use to solve it .... )


deque<vector<pos_t>> treasure_order;
std::sort(begin(treasurePos), end(treasurePos));
do {
  vector<pos_t> c;

  c.push_back(pos_t(0,0));
  copy(begin(treasurePos), end(treasurePos), back_inserter(c));
  c.push_back(pos_t(maze.size()-1, maze.size()-1));

  copy(begin(c), end(c), ostream_iterator<pos_t>(cout, " -> "));
  cout << endl;
  treasure_order.push_back(c);

} while ( std::next_permutation(begin(treasurePos),end(treasurePos)) );//*/
cout << "we stored " << treasure_order.size() << " path to get all the treasure (=nbTreasure! = " << fact((int)treasurePos.size()) << ")" << endl;


Using that simple 2D maze where * mark treasure position:

. . . .
. # . *
. # * .
* * # .

We now that based on the 4 treasure we have, we can visit those 4 position using 24 different order....
Remark, here all list start and end with the same point (top-left and bottom-right corner) because they are the starting and ending point of th "Treasure Hunt" !

(0,0) -> (1,3) -> (2,2) -> (3,0) -> (3,1) -> (3,3) ->
(0,0) -> (1,3) -> (2,2) -> (3,1) -> (3,0) -> (3,3) ->
(0,0) -> (1,3) -> (3,0) -> (2,2) -> (3,1) -> (3,3) ->
(0,0) -> (1,3) -> (3,0) -> (3,1) -> (2,2) -> (3,3) ->
(0,0) -> (1,3) -> (3,1) -> (2,2) -> (3,0) -> (3,3) ->
(0,0) -> (1,3) -> (3,1) -> (3,0) -> (2,2) -> (3,3) ->
(0,0) -> (2,2) -> (1,3) -> (3,0) -> (3,1) -> (3,3) ->
(0,0) -> (2,2) -> (1,3) -> (3,1) -> (3,0) -> (3,3) ->
(0,0) -> (2,2) -> (3,0) -> (1,3) -> (3,1) -> (3,3) ->
(0,0) -> (2,2) -> (3,0) -> (3,1) -> (1,3) -> (3,3) ->
(0,0) -> (2,2) -> (3,1) -> (1,3) -> (3,0) -> (3,3) ->
(0,0) -> (2,2) -> (3,1) -> (3,0) -> (1,3) -> (3,3) ->
(0,0) -> (3,0) -> (1,3) -> (2,2) -> (3,1) -> (3,3) ->
(0,0) -> (3,0) -> (1,3) -> (3,1) -> (2,2) -> (3,3) ->
(0,0) -> (3,0) -> (2,2) -> (1,3) -> (3,1) -> (3,3) ->
(0,0) -> (3,0) -> (2,2) -> (3,1) -> (1,3) -> (3,3) ->
(0,0) -> (3,0) -> (3,1) -> (1,3) -> (2,2) -> (3,3) ->
(0,0) -> (3,0) -> (3,1) -> (2,2) -> (1,3) -> (3,3) ->
(0,0) -> (3,1) -> (1,3) -> (2,2) -> (3,0) -> (3,3) ->
(0,0) -> (3,1) -> (1,3) -> (3,0) -> (2,2) -> (3,3) ->
(0,0) -> (3,1) -> (2,2) -> (1,3) -> (3,0) -> (3,3) ->
(0,0) -> (3,1) -> (2,2) -> (3,0) -> (1,3) -> (3,3) ->
(0,0) -> (3,1) -> (3,0) -> (1,3) -> (2,2) -> (3,3) ->
(0,0) -> (3,1) -> (3,0) -> (2,2) -> (1,3) -> (3,3) ->

mardi 8 octobre 2013

C++ Command Line using standard input/output.

As programmer you may be familiar with a lot a program design to use input file and/or input stream using the standard input. It’s one of the powerful aspect of tools like grep, sed, etc… And if you want to implement such command-line tool by yourself you may meet one big issue.

Windows vs. Linux.

As often, we would write our code in a portable way and just create a simple while loop like
while(!feof(stdin)) 
  {
    size_t bytes = fread(bufferInput, 1, m_blocksize, stdin);

    // ....
  }

but here you are face to a piece of code dependent of the platform you target, let me explain.


  • On Linux stdin and stdout are by default open using the binary mode.

  • On the other side on Windows they will be open using the text mode.

because of that, the feof and all the fread, fgets function can have different output on the 2 systems. For example, on Windows, reading using the normal mode will convert \r\n (Windows newline) to the single character ASCII 10, instead of returning 2 bytes under Linux !

To avoid that pitfall, you can use 2 approach:


  • freopen, portable and easy to put before using stdin

  • or _setmode/setmode available under Windows and also Linux/GCC under certain condition.

freopen:


Basically, the best thing you should do is this:

freopen(NULL, "rb", stdin);

This will reopen stdin using the binary mode, so under Linux it will change nothing, and on Windows, 
it will avoid abnormal character interpretation (premature end-of-stream, etc…). But take care of the 
compiler you use because depending of the freopen spec you read the behavior when passing path 
equal to NULL may be different... see the 2 following description:

setmode:

That method is less portable and may require some addition to your GCC environment.
With VS for example, you can call _setmode (require fcntl.h and io.h)

  _setmode(_fileno(stdin), _O_BINARY);
  _setmode(_fileno(stdout), _O_BINARY);

But under linux, the setmode isn’t a standard lib function, it’s a libbsd function. So you have to include <bsd/unistd.h> and link with –lbsd.

Conclusion


If you have to write a multi-platform command line tool using stdin/stdout the most portable way to do it is the freopen solution!

vendredi 4 octobre 2013

Screen capture with ffmpeg.

ffmpeg is the perfect tool to transcode video, but you may don’t know that it can also be use to capture your PC’s screen and as I didn’t found a clear page explaining how to do that, I will try to do my own (and hope it will help someone ….)

Performing a screen capture is an usual task to report bug, recording a presentation you make (adding your voice and your webcam recoding over-the-top of your slide), etc…

There is several tools you can found under the web (GOOGLE IT), But you have to setup a new application, you don’t even control the Audio/Video filter used to capture and encode the video. If you want to keep control, you would like my command line based solution.

Note that the solution I describe here is for Windows, but it could also work under Linux  with some adaptation, look at –x11grab)

First, check if you have Audio & Video Capture filter:

ffmpeg -list_devices true -f dshow -i dummy
it should return something like:


dshow @ 00000000002fb2e0] DirectShow video devices

dshow @ 00000000002fb2e0]  "…."

dshow @ 00000000002fb2e0] DirectShow audio devices

dshow @ 00000000002fb2e0]  "…."


If you don’t find a filter name between the quotes, you have to setup filters and /or enable the audio output recoding capabilities.


  • Setup Video Capture filter for x86 and x64 (it depend of your ffmpeg version).

I recommend the Unreal Screen Capture DirectShow source filter , download the version you need and perform the installation.



  • Setup the Audio Capture. That part depends of your device, but for example on my PC, I have a “Realtek High Definition Audio” Device. I clicked on the speakers icon in the system bar and select “recording device”, I had to enable the “stereoMix” device and boost its capture level.

EnableAudioOutRecording


After check again if ffmpeg detect your device/filter, it should be something like:



dshow @ 00000000002fb2e0] DirectShow video devices

dshow @ 00000000002fb2e0]  "UScreenCapture"

dshow @ 00000000002fb2e0] DirectShow audio devices

dshow @ 00000000002fb2e0]  "Stereo Mix (Realtek High Defini"


Run your 1st capture



ffmpeg -f dshow -i video="UScreenCapture":audio=Stereo Mix (Realtek High Defini" cap.mp4


Just hit [q] to stop the recoding and play cap.mp4 (ffplay cap.mp4).


By default, it capture the whole screen, and the whole means ALL your screen i.e. for my dual-screen system I recorded a 3840x1200 video.


Select your ROI(Region Of Interest)


We will use the -vf crop=width:height:xtopleft:ytopleft syntax of ffmpeg to select the part of the big picture we really want to record.


For the example, we will capture the output of a video player, but how to get the windows or video area coordinates ? In fact it’s really simple, I use the small application called “Point Position”.


 


PointPosition


Using that tool you can get the top-left and bottom-right coordinate of any window you want to capture, and by the way compute the width and height of the area!


Now capture:



fmpeg -f dshow -r 14.985 -i video="UScreenCapture":audio="Stereo Mix (Realtek High Defini" -vf crop=1278:541:98:198,scale=480:270 -c:v libx264 -profile:v baseline -level:v 3.0 -b:v 350k -r 14.985 -pix_fmt yuv420p cap.mp4


here I added several option to set a capture frame-rate, rescale the cropped area and encode the video using explicit parameters (encoder, bit-rate, etc….)


Conclusion:


No need of additional tool to perform a task that our video’s Swiss knife can do !

vendredi 27 septembre 2013

Windows PATH Environment Variable too long!

 

Yesterday, I unzipped several useful command line tools each in their respective folder and tried to add all those path in my PATH to easily access all tools from any command prompt, BUT ….

When I tried to copy/paste all the new path through the Environment Variables Editor, you can open from :

“Control Panel\System and Security\System”, click on “Advanced system settings”, select “Advanced” Tab and now click on the “Environment Variables” button…..

Smile  a shortcut will be welcome !

The Editor here has a 2048 characters limit. And I already have a too long path !!!!

An easy workaround from here was to use the “User” PATH as I’m the only user of my workstation it was fine.

But If you really need to update the PATH for all users you can use the registry editor (regedit.exe):

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path

The Editor (rigth click on the key and select “Modiffy”) will allow you to use more characters.

But if one day your change are finally truncate, It could mean you hit the maximum of 32767 characters (CONSIDERING ALL YOUR VARIABLES ….)

mardi 17 septembre 2013

Coding Style: Detect tabulation and use a given number of space instead.

 

If you need to respect a Coding Style, and that your coding style require tab to be replaced by a given number of space (2 in my case), you may have to check before each commit that the files you have in your working copy doesn’t contain any tab.

To realize that preliminary step, you can use grep.

Run: grep -n -P "\t" *.h && grep -n -P "\t" *.cpp

It will get you the file name and the line number where grep found tabulation.

Now if we want to automatically apply the Coding Styles rules and replace tabs by 2 spaces we can also use a command line.

find ./ -type f -name "*.h" -exec sed -i 's/\t/  /g' {} \;

and

find ./ -type f -name "*.cpp" -exec sed -i 's/\t/  /g' {} \;

The number of space between \t/ and /g has to be the number of space for tab !

Note that grep, find and sed are Linux command, but Windows developer can also use those command if they setup Cygwin.

lundi 16 septembre 2013

C++: Find max top 5 number from 3 array.


Yesterday, I read that blog post where C# developer demonstrate how powerful is LINQ to solve a simple problem.
We have 3 array of Integer  and we want to find the 5 maximum number from those 3 Array.  With LINQ, 7 cascaded operation are enough to do that in 3 line of code.
And I’m wondering how many line I would use in C++ to do the same !
Here is my 1st Draft made in 5min. I use only 5 line of code.
//Headers we need
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int Array1 [] = { 9, 65, 87, 89, 888 };
int Array2 [] = { 1, 13, 33, 49, 921 };
int Array3 [] = { 22, 44, 66, 88, 110 };

vector<int> A1(begin(Array1), end(Array1)); 
A1.insert(end(A1), begin(Array2), end(Array2)); 
A1.insert(end(A1), begin(Array3), end(Array3));
sort(begin(A1), end(A1));
vector<int> max(end(A1)-5, end(A1));

//to output the result
copy(begin(max), end(max), ostream_iterator<int>(cout, " "));




But I would see on Stack Overflow if someone has a better solution.

[UPDATE] : you can found interesting to read answer to my StackOverFlow question.
 C++ and C++11 solution are proposed, taking into account the complexity introduce by the sorting. 

jeudi 12 septembre 2013

Let your hand on the keyboard.

 

I don’t know all the “magic” keyboard shortcut but I always try to learn new shortcut, just because typing and switching between keyboard and mouse is just losing time.

Today I was try to get a shortcut for word/outlook word spell suggestion and find that it’s easy. If the spell checker is enable and that something you just typed appears with the red-underline (saying something is wrong), get back on that word and use MAJ+F10 to open the suggestion list.

Now I can correct a lot of typo mistake on-the-fly without living my keyboard !

C++/Boost Finding files in a folder.

 

Interaction with the file system are not so easy to implement using C++, and that’s where Boost can help you. Boost contain a lot of useful libraries, and FileSystem is one I used the the most.

To build a simple example, let say that we would go through all files in a given folder and remove them with a specific extension '.bak.

First include boost FileSystem header file and I would recommend to use a namespace alias to reduce the length of your code line (typing boost::filesystem:: blahblah every time is too long !)

#include "boost/filesystem.hpp"
namespace fs = boost::filesystem;



Now we have to define the folder path and directory_iterator

fs::path outputFolder(".");
for(fs::directory_iterator it(outputFolder); it != fs::directory_iterator() ; ++it)
{
....
}



Here we iterate over files in the current directory of the program. But using a specific path string you could reach all accessible folder.


Now in the loop, using the valid directory_iterator it, you can do a lot of different things. Below I will test if extension is .bak and if true remove that file.

if(fs::extension(it.path().filename()) == ".bak") 
{
fs::remove(file);
}



Now you can still rely to system command and that you don’t have to del with different FileSystem, under windows just use the system function (<stdio.h>) like : system(‘del *.bak”);


It mainly depend of your project, because adding and using Boost for using only one  of those functionality may be a bad idea.

jeudi 5 septembre 2013

Terminal 2–Don’t assign CTRL+C for Copy

 

Terminal 2 is a powerful tools under windows to run cmd.exe, Cygwin bash and other command prompt. Users can customized their hot-key (hit CTRL+S to open the Settings dialog box). But if you assign the CTRL+C keyboard shortcut for the common “Copy to clipboard” action, you may have trouble in killing programs you run.

Prefer the “copy on select” behavior and re-assign the copy action to another shortcut (i.e. SHIFT+CTRL+C).

After that change, you run program and stop them with CTRL+C as in the classic cmd.exe (windows prompt)

mercredi 4 septembre 2013

C++11: Combining lambda and smart pointer to handle create/release API

I use a library in which several class use create/release pattern for memory and resources management. it means that there is no public constructor (ctor) and destructor (dtor).

Example:

class FileInterface
{
public:
virtual ~FileInterface() {}

virtual bool isValid() = 0 ;
virtual void release() = 0;
};

class RealFile : public FileInterface
{
public:
static int createFileInterface(const std::string& filename, FileInterface*& pFileInst)
{
try {
pFileInst = new RealFile(filename);
} catch (...){
return -1;
}
return 0;
}
virtual bool isValid() { return (m_pFile != NULL);}
virtual void release() { delete this;}

protected:
RealFile(const std::string& filename)
: m_pFile(NULL)
{
m_pFile = fopen(filename.c_str(), "wb");
if(m_pFile == NULL) {
throw std::runtime_error("error while opening file.");
}
}
~RealFile() {
std::cout << "DTOR" << std::endl;
fclose(m_pFile);
}
private:
FILE* m_pFile;
};





To use that kind of class you have to deal with the release by yourself. it means that if you have several return path or a complex exception management, you have to put a call to the release function everywhere (with additional check for  not null).

FileInterface* pFile = nullptr;
int ret = RealFile::createFileInterface("test.bin", pFile);
if( ..... )
{
....
std::cout << "isValid = " << pFile->isValid() << std::endl;
pFile->release();
return ...;
}
else
{
....
if(pFile != nullptr)
pFile->release();
return ...;
}



That’s why I like the C++ smart pointer, at allocation you define the custom deleter and when the smart pointer instance goes out-of the scope, everything will be free.

auto smartDeleter = [](FileInterface* ptr){ptr->release();};
auto smartAllocator = [](const std::string& filename) -> FileInterface* {
FileInterface* pFile = nullptr;
int ret = RealFile::createFileInterface(filename, pFile);
if (ret != 0) return nullptr;
else return pFile;
};

std::unique_ptr<FileInterface, decltype(smartDeleter)> smartFile(smartAllocator("test.bin"));
std::cout << "isValid = " << smartFile->isValid() << std::endl;



Now we can use the smartFile instance as a pointer on a FileInterface and let the life management responsibility to the unique_ptr.

IE–“Toolbars and extension management” (StExBar missing)

 

Sometime I don’t understand how Microsoft organize & manage the relation between the different program running under Windows (Seven) ?

I had an Explorer shell extension call StExBar and today after an update and the restart (as usual), it disappear and the in Explorer Menu (View –>ToolBar) I found it but it was grey and un-clickable !

After some Googling, I found some discussion in which users had the same issue. In fact depending of the version (x86 or x64) of the plugin or extension you use (the StExBar in my case) you can Enable/disable them through the x86 or the x64 version of Internet Explorer (a.k.a IE).

Open the right version of IE, ALT+T (Menu “Tools”) –> “Internet Options”

image

Go into “Programs'” and click ”Manage Add-ons”

image

It’s definitely not the place where I had search by myself to found enable/disable button for shell extension used only by Explorer.exe. I’m wondering in why those settings are in IE….

mercredi 21 août 2013

FFMPEG deprecated on Ubuntu .... it's not a joke !

As I created a new virtual PC to host a Ubuntu 12.04.2 LTS, I tried to setup all my favorites command line tools.

But after setting up ffmpeg: sudo apt-get install libav-tools
I asked for the version and got the following message:

ffmpeg version 0.8.6-4:0.8.6-0ubuntu0.12.04.1, Copyright (c) 2000-2013 the Libav developers
built on Apr 2 2013 17:02:36 with gcc 4.6.3
*** THIS PROGRAM IS DEPRECATED ***
This program is only provided for compatibility and will be removed in a future release. Please use avconv instead.
ffmpeg 0.8.6-4:0.8.6-0ubuntu0.12.04.1
libavutil 51. 22. 1 / 51. 22. 1
libavcodec 53. 35. 0 / 53. 35. 0
libavformat 53. 21. 1 / 53. 21. 1
libavdevice 53. 2. 0 / 53. 2. 0
libavfilter 2. 15. 0 / 2. 15. 0
libswscale 2. 1. 0 / 2. 1. 0
libpostproc 52. 0. 0 / 52. 0. 0


ffmpeg .... DEPRECATED, it looks like the Ubuntu community push to replace the original ffmpeg command line by the avconv (a fork of ffmpeg....)
For me it's just a pain, as ffmpeg and avconv will not have the same development cycle, and their features and command line may vary, so switching from windows, to centos, to ubuntu and not having the same tools is terrible !

Will rebuild my own ffmpeg up-to-date instead of using the package manager !


mercredi 7 août 2013

How to use MS Live Writer with Blogger

 

  • Setup MS Live Writer that you can find here.
  • Start MS Live Writer.
  • On the first dialog box, select “Other Blog, Blogger etc…”.
  • On the second dialog box, for your blog URL, use your blog URL, but use HTTPS instead of HTTP. Fill correctly your username and password.
    • WARNING with 2-factor Authentication, you have to create a specific App password.

 

  • Next, Next, … All remaining Step are easy.

mercredi 31 juillet 2013

Replace STL Algorithm with "Parallel" Algorithm.

The goal is to keep a C++ syntax and STL style of writing code while using parallelism. It's a recent topic and lot of C++ Framework emerged in the 2 or 3 previous year.

 Note that an automatic replacement of all STL algorithm by a parallel equivalent isn't a good idea, so that in any case you will have to update your code.

in the following example, I just define a small lambda and apply that one on a 1d array using std::transform.
I called  a parallel version using the PPL(in the VS'2012). Only have 2 cores but seems lead to the expected factor 2.



#include <ppl.h>

void main ()
{
float otherScalingFactor = 0.3f;
#define size 59999999
float* local_arr = new float[size]; std::fill(local_arr, local_arr + size, 1.5f);
float* out = new float[size];
auto normalize = [&] (float x) { return fabs(x / otherScalingFactor) * otherScalingFactor + expf(x) * cosf(x) ; };
time_t start = time(NULL);
std::transform(local_arr, local_arr + size, out, normalize);
time_t end = time(NULL);
std::cout << "end in ..." << difftime(end, start) << std::endl;

std::fill(out, out + size, 0.0f);

start = time(NULL);
concurrency::parallel_transform(local_arr, local_arr + size, out, normalize);
end = time(NULL);
std::cout << "end in ..." << difftime(end, start) << std::endl;

delete [] local_arr;
delete [] out;

getchar();
}

mardi 30 juillet 2013

Producer - Consumer: a common conception error.

Producer-Consumer design or Pipeline of task are often use in programming to introduce multi-threading. But some programmer are wrong in the way they implement that. For example, I found the following question on Stackoverflow: concurrent_queue memory consumption exploded, then program crashed. The question is why the memory rise a limit so that the program crash !

After some comment, I finally post an answer, but I realize that it may be useful to explain a bit more with some schema.


If the producer run 2x faster than the consumer the number of element in the Fifo will grow linearly. So as in the real life, we have to specify a limited stock size. So that if the stock is full, the producer must wait.


That can be achieve with a dual synchronization:
  • Consumer wait if the fifo is empty and is awake if an element is pushed.
  • Producer wait if the fifo is full and is awake if an element is remove so that the size goes under the threshold.
For the code, see my answer on Stackoverflow!

dimanche 28 juillet 2013

Optimization - Where Meta-Programming can help...

In this post, I will show 2 different methods of computing the n-th element of the Fibonacci Suite.
The goal is to show that in some context instead of using run-time to compute something, you can compute that at compile-time.

  • run-time, is what you want to optimize.
  • compile-time, what you can increase (in some limit) without impact on your customer.
If compile-time become really too long, you will be depressed waiting in front of your computer. But your compiler can do a lot for you.

See below a simple recursive function to compute the n-th element of the Fibonacci suite.


int Fibonacci_recursive(int nieme)
{
if( 0 == nieme)
return 0;
if( 1 == nieme)
return 1;

return Fibonacci_recursive(nieme-1) + Fibonacci_recursive(nieme - 2);
}


Now if you use that function "Somewhere in your code", and disassemble the resulting binary, you will see something like:

00E91357 call Fibonacci_recursive (0E91270h)

The code you call use a lot of op-code and call itself several time depending of the element you ask. This kind of computation is not time-constant !

So it will be interesting if compiler can compute the value! At run-time we will have directly have the value in constant-time.... To achieve that goal, you can use Macro (Preprocesor), or Template (C++ Meta Programming). I choose the template way :


template<int I> struct Fibonacci_meta {
enum { value = Fibonacci_meta<I-1>::value + Fibonacci_meta<I-2>::value };
};
template<> struct Fibonacci_meta<1> {
enum { value = 1 };
};
template<> struct Fibonacci_meta<0> {
enum { value = 0 };
};


And now if you write Fibonacci_meta<10>::value in your code, and analyze the result, you will just see something like:

008F7BFF push 37h

And as you may know 0x37 == 55... the 10-th element of Fibonacci.
It's a simple example, but we removed several function call and have let the compiler find the result at compile-time!!!!


vendredi 26 juillet 2013

Playing with JS and Web API.

One thing really fun is this area, is that more and more data are freely available from/to the Web. Those data can be REALLY free like Weather Real-time information like the service i used below, or NEED APP REGISTRATION.

Note that for a lot of Web API, App Registration is free, it's more for tracking and avoid duplicate App development or that an IP 'get' too much data.

I'm not a Web Developer, but I think that as a developer if you don't know basis of JavaScript and HTML in our 21 century, you would be lost. So my today experiment, I will get Temperature information for my city, and simply display that.

So in the code below I declared 2 HTML label using an ID, temp_celsius, and temp_fraenheit.


<div>
<p> Rennes Today's Temperatures</p>
<ul>
<li><text> Celsius : </text><label id="temp_celsius" ></label></li>
<li><text> Farenheit : </text><label id="temp_farenheit" ></label></li>
<ul>
</div>


The result is here

Rennes Today's Temperatures
  • Celsius :
  • Farenheit :

To feel those 2 HTML label with data, i started using JQUERY (you can live without, but when you become familiar with its notation to access DOM element, you always start with it):


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>




And now let's call the OpenWeather service . It propose a free Web/REST API to get (or push if you setup your own Weather station) data using JSON format.
My request is "http://api.openweathermap.org/data/2.5/weather?q=Rennes,fr" and in response i received something like:

{"coord":{"lon":-1.67429,"lat":48.11198},"sys":{"country":"FR","sunrise":1374813353,"sunset":1374868234},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"gdps stations","main":{"temp":297.15,"pressure":1012,"humidity":50,"temp_min":297.15,"temp_max":297.15},"wind":{"speed":2.6,"deg":290,"var_beg":250,"var_end":330},"clouds":{"all":36},"dt":1374849000,"id":2983990,"name":"Rennes","cod":200}


One of the advantage of using JQuery is that you can get and parse the JSON data in only 1 call of $.getJSON. The field Temp is express in JKelvin as you can have guess when looking its value (297.15 ...).


<script type="text/javascript">
$(document).ready(function(){
var json_request = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=Rennes,fr&callback=?", function(data) {
console.log("in cb ????" + data.main.temp);
var celsius = (data.main.temp - 273.15);
$("#temp_celsius").html(celsius);
var farenheit = (celsius * 1.8 ) + 32
$("#temp_farenheit").html(farenheit);


}).done(function() { console.log( "second success" ); })
.fail(function() { console.log( "error" ); });
});
</script>


There is nothing really dynamic after that, but my next step will be nicer, it will be the "Stackoverflow Question Meter" to dynamically show how many question are ask on Stackoverflow and using Google Chart API.

samedi 20 juillet 2013

Counting occurence and histogram

A recurrent question on Stackoverflow [c++] is, hopw can we count word, sentence in string or a text file, or how can we build an histogram showing all unique number in a list and their number of occurence.

In fact every time those question found quite the same answer because in all case, whatever you want count, it can be really easy to do with C++ and STL. If we use the std::map class we can do that in 2 loop.

First, imagine we have a list containing random number.


srand(time(NULL));
std::vector list;
int N = 1 , M = 100;

for (int i = 0; i < M; ++i) { int rnd = M + rand() / (RAND_MAX / (N - M + 1) + 1); list.push_back(rnd); }


Ok, so now we have 100 number with some redundancy, let's count that with a map.


std::map histo;

for (auto rnd : list)
{
histo[rnd] += 1;
}


And it's done !, nothing else .... Just a loop to display the result:


for(auto var = begin(histo) ; var != end(histo) ; ++var)
{
std::cout << var->first << " have " << var->second << " occurence " << std::endl; }


Simple and efficient

Why you really need a "Gravatar" !

At first glance when a web site asked me for a gravatar, I found that annoying and just let my account without avatar or picture of me.

But few week ago I changed my mind, Having a gravatar account let you change your picture once and all the account you linked with, will be automatically update!

At the end, it's just the same thing under Google .... 1 Profile picture for everything, for all the account you have.

So if you want a Gravatar it take only few minutes.

I use mine for Stackoverflow, CoderBits and some other and finally I found that more convenient than uploading a picture for each!

lundi 1 juillet 2013

Don't forget to 'EncodeURL'

In  http://tinyurl.com/qa3nmtv I presented a small script/exe I made to quickly convert selected path (folder or file) from Explorer to a string in the clipboardwhich can be 'paste' in a browser editor as an URL to a local resssource.

In fact I forgot something important in my script. You may hate or love it but Windows allow 'spaces' in path. So I have to convert SPACE to %20, to build a correct URL.

I updated my script this morning:

https://github.com/alexbuisson/Project/tree/master/UsefullScript

Just pull Path2URL.exe, and configure your StExBar like in the following Snapshot.





Visual Studio 2008Randomly crashing.


If you are using VS'08 and a lot of plugin you may experience some random crash when using "Intellisense" functionality (performing a right click in the source code) or when switching from Debug to Release configuration.

 I may be really difficult  for some to figure from where and for why the crash/freeze occur.

In fact I meet that issue and I finally attached another Visual Studio instance with a debugger and realize that VS was hanging somewhere in the FEACP.DLL

That DLL is the engine of Intellisense.

If you have that kind of problem and that you want double check or experiment VS'08 without Intellisense running behind, you just have to rename that dll in your VS'08 setup folder and restart VS.

It's work fine but without Intellisense, you really need additional plugin to provide, some source browsing capabilities ("Find all references", etc...)


Build a script/tool to make your life easier.

Hi,
Just wanted to share some work done to simplify the everyday life of my teammates.

One week ago, one of my colleague had a lot of file path to share through our CRM system and in fact he found that was very boring because he had to copy all network path and apply a transformation on every string. To transform network file or folder path from their UNC or Drive path (mounted drive) representation to a file/folder URL style that can be use to access local system storage through a browser.

To do that he had to 'manually' switch all '\' (windows path separator) to '/' and concatenate 'file://'. I understood it could become a pain to do that kind of boring task, so I developed a simple script/executable to do that for one or multiple selected file or folder with only 1 click from Windows Explorer.

My Teammates and I already used StExBar to improve our Windows Explorer experience. It's a highly customizable tools in which you can add your own custom command, with button and/or hot-key.


As the function we need has only to run under windows, I choose a windows only tool called AutoHotKey to build a script performing multiple path selection, conversion to URL style and injection into the clipboard.

AutoHotKey provide every things I needed to develop the script:
  • File parsing 
    • StExBar selection (single or multiple) are store in a temp text file that can be pass to any cmd or application through "%selafile"
  • Clipboard
    • From AHK (AutoHotKey) point of view the winows clipboard is just a variable.
  • String parsing, Regex Matching etc...
    • To detect Drive letter
    • To detect UNC Path
    • To replace '\' and concatenate the 'file://' prefix.


link := "file:///"
pathrep := ""

CR := Chr(13)
LF := Chr(10)

GetUNCPath(letter)
{
  localName = %letter%
  length := 1000
  VarSetCapacity(remoteName, length)
  result := DllCall("Mpr\WNetGetConnection"
      , "Str", localName
      , "Str", remoteName
      , "UInt *", length)
  if (ErrorLevel <> 0 || result != 0)
  {
     return ""
  }
  else
  {
;     MsgBox, %remoteName% (%length%) -- result: %result%
    return remotename ; end function
  }
}

Loop Read, %1%
{
 p := A_LoopReadLine
 ;MsgBox %p%
  if ( RegExMatch( p , "[A-Za-z][:]") ) ; match a regex for drive letter "^:"
  {
    unc := GetUNCPath( SubStr( p, 1, 2) )
    if ( unc <> "" )
    {
      withoutDriveLetter := SubStr( p, 3, strLen(p)-2 )
      pathrep = %link%%unc%%withoutDriveLetter%%CR%%LF%%pathrep%
    }
  }
  else ; should already be an unc (check to be sure)
  {
    if ( RegExMatch( p , "\\\\") ) 
    {
      pathrep = %link%%p%%CR%%LF%%pathrep%
    }
    else
    {
      ; Msgbox "ignored " %p%
    }
  }
   
}

StringReplace, pathrep, pathrep, \, /, All
; MsgBox %pathrep% 
clipboard =  %pathrep% 

The main advantage of using AHK script is that it can be build and provide as a binary file without any dependency. And the integration of the resulting executable as an StExBar Command is really simple like you can see in the following snapshot:


That script is publicly available on my GitHub repo



mardi 18 juin 2013

About the importance of unit-test defintion

Last week, a friend and I submitted some piece of code to solve an on-line coding challenge. It was a 'french' challenge but I will try to explain the problem and present the data vector used to test submitted function. We will show that their data vector definition is incorrect and doesn't detect if a function can really solve to problem !

First, the problem:

As developer and team member of a High-Tech Company, your manager ask you to register and join the maximum of development and tech-event you can.
So, you list all the incoming event and some are in the same time.
But you still need to be in the "maximum" of event.

So nothing magic... you cannot be in 2 different place the same day.
For each event, you only know when it start and its duration (days).

Second, the test data they use:

They propose 3 different test to check the function output:



Simple

2013-01-12;5
2013-01-01;13
2013-01-16;20

function should return 3





Complex

2014-04-28;4
2014-05-01;7
2014-05-03;7
2014-05-09;5
2014-05-11;11
2014-05-16;3
2014-05-20;1

function should return 4




With a leap year

2012-02-20;10
2012-03-01;2
2012-03-12;2
2012-03-14;2
2012-03-15;2
2012-03-20;13

function should return 5


And now where the defined test failed ...

My co-worker and I had 2 different favorite language (Python for him and C++ for me) and 2 different solution.
In fact he use a real exhaustive exploration using the 'permutation' function to find the 'maximum number of event', but it lead to a high complexity if the number of event grows. On my side, I preferred a linear complexity and I used a common 'greedy' solver. But in fact case, it's well known that it can not find the 'optimal' solution.

My simple C++ implementation use an t_event class define by:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class event_t 
{
public:
 event_t(const std::string& _date)
 {
  memset(&_start_date, 0, sizeof(struct tm));

  sscanf(_date.c_str(), "%d-%d-%d;%d", &_start_date.tm_year, &_start_date.tm_mon, &_start_date.tm_mday, &_duration);
  _start_date.tm_year -= 1900;
  _start_date.tm_mon -= 1;

  _start_pt = mktime(&_start_date);
  _end_pt = _start_pt + _duration * 24 * 60 * 60;

  memset(&_end_date, 0, sizeof(struct tm));
  memcpy(&_end_date, gmtime(&_end_pt), sizeof(struct tm));
 }

 event_t(const event_t& e)
 {
  _duration = e._duration;
  _start_date = e._start_date;
  _start_pt = e._start_pt;
  _end_pt = e._end_pt;
  _end_date = e._end_date;
 }

 bool operator < (const event_t& r)
 {
  return this->_end_pt < r._end_pt;
 }

 friend std::ostream& operator<< (std::ostream& stream, const event_t& evt);

public:
  struct tm _start_date;
  unsigned int _duration;
  struct tm _end_date;

  time_t _start_pt;
  time_t  _end_pt;
} ;

And use the following function to build a planning:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void CreatePlanning( std::vector<event_t> &_list )
{
 std::ostream_iterator< event_t > dump_events( std::cout, "" );

 std::sort(_list.begin(), _list.end()); 
 std::cout << " Start \t End \t Duration \n", 
  std::copy(_list.begin(),_list.end(), dump_events);

 std::vector<event_t> _planning;
 _planning.push_back(_list[0]);
 unsigned int j = 0;
 for (unsigned int i = 1 ; i < _list.size() ; ++i)
 {
  if(_list[i]._start_pt >= _list[j]._end_pt)
  { 
   _planning.push_back(_list[i]);
   j = i;
  }
 }

 std::cout << "Nb event planned : " << _planning.size() << std::endl;
 std::cout << " Start \t End \t Duration \n", 
  std::copy(_planning.begin(),_planning.end(), dump_events);
}

That code is ok regarding the expected result of the unit-test, but as i said before the price for the lower complexity is that it can lead to a no optimal solution.
The heuristic I use can be summarize, start ASAP and restart ASAP again and again ... Simple and efficient, I'm a greedy person !!!

mardi 28 mai 2013

Const-Correctness .... with example.

Some of my friend have trouble with the terrible "const" keyword this morning
They have a class 'test', an instance of that class and they want to pass it through a function as 'const test*' parameter.

The question was: what 'const classname*' means ? and by the way what is the difference with 'const classname* const' ?

To answer, let create a 'test' class defined with 'const' and not const function:


class test
{
public:
test(){}
~test(){}

int DoConstOp() const { return 0;}
int DoNotConstOp() { return 0;}

};


And now we create different version of a method call 'process_blahblah' in which we will call the 2 test's function. Those method will take a object of type 'test' but with 4 different signature:

  • const test&
  • const test*
  • const test* const
  • test* const

And call the 4 method from a main:

process_as_const_ref(t);
process_as_const_ptr(&t);
process_as_const_ptr_const(&t);
process_as_ptr_const(&t);


And now have a look at their implementation. I put under comment the lines that doesn't compile (under VS'12 at least... but result looks correct regarding the C++ standard !) + error message.



void process_as_const_ref(const test& t)
{
t.DoConstOp();
//t.DoNotConstOp();//Cannot build: cannot convert 'this' pointer from 'const test' to 'test &'
}

void process_as_const_ptr(const test* t)
{
t->DoConstOp();
//t->DoNotConstOp(); //Cannot build: cannot convert 'this' pointer from 'const test' to 'test &'
(const_cast<test*>(t))->DoNotConstOp(); //trick
}

void process_as_const_ptr_const(const test* const t)
{
t->DoConstOp();
//t->DoNotConstOp();//Cannot build: cannot convert 'this' pointer from 'const test' to 'test &'
(const_cast<test* const>(t))->DoNotConstOp(); //trick remove the const on the class not on pointer
//t++;//but this you can't do : 't' : you cannot assign to a variable that is const
}

void process_as_ptr_const(test* const t)
{
t->DoConstOp();
t->DoNotConstOp();
//t++;//but this you can't do : 't' : you cannot assign to a variable that is const
}


So the answer is:
  • const test& or const test* declare the the test instance you use as const, thats why you cannot non-const method.
  • and with const test* const or test* const, the 2nd const keyword declare the pointer as const, it means that you cannot do any modification of the pointer value (ptr++ ptr = another ptr ...etc ...).
Note that using the "test* const" syntax may be confusing and useless as by default the pointer you get is a "copy" of the pointer you have in the caller !


vendredi 24 mai 2013

HTML/CSS for fixed background image and a nice scrolling effect

As I was looking some news about the next XBox on http://www.wired.com/gadgetlab/2013/05/xbox-one/ I found the web page design and scrolling effect really nice. And I'm wondering if that kind of effect required JS or if it only use CSS. Note that I'm not a web developer, but just as usual curious of "how it works ?" ...

In fact after inspecting the page (thank you to the Firefox Inspector ! a nice functionality) I found that a small piece of CSS is enough and than the main trick is in the size of the image !!!!

Look at the following image they use http://www.wired.com/images_blogs/gadgetlab/2013/05/0521-tall-controller-v1.jpg. It's a 1050x2000 pixels image.

Below I tested the insertion on their image (Thank you Microsoft ...) to do the same in the middle of a fake text ....


#container div.fixedbackgroundimg {
position: relative;
overflow: visible;
}
.fixedbackgroundimg.example {
background: url("http://www.wired.com/images_blogs/gadgetlab/2013/05/0521-tall-controller-v1.jpg") repeat-y fixed 50% center transparent !important;
}

<div class="fixedbackgroundimg example" data-type="background" data-speed="5">
<h2 class=""> test </h2>
<img src="http://www.wired.com/images_blogs/gadgetlab/2013/05/0521-tall-controller-v1.jpg" style="visibility: hidden; height: 500px" data-lazy-loaded="true"></img>
</div>


The trick is to create a div containing an hidden image, or with a fixed width and height, and in the style of that div, you specify a background image bigger than the div and centered inside !

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus




Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus


Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

jeudi 23 mai 2013

Mastermind : build the k-combination of n colors(with repetitions)

In my 'Mastermind serie', I wrote a small C++ code that i would template later to create the list of the 4-combination of 6 peg (with repetitions) as we already know that for the classic mastermind game:
  • we have 6 colors,
  • the code is 4 peg long,
  • so the total number of combination is 6^4 = 1296

To build that list, I apply the recursion/induction method and obtain finally a short and cool code :)
 Recall that our colors are describe by letters from 'A' to 'F'.


const color_code_map_t color_code = map_list_of (color_e::white, 'A')(color_e::blue, 'B')(color_e::green, 'C')(color_e::yellow, 'D')(color_e::orange, 'E')(color_e::red, 'F') ;


I build the list through the following code:

vector<char> elements;
std::for_each(color_code.begin(), color_code.end(), [&elements](const color_code_map_t::value_type& p) { elements.push_back(p.second); });
auto combi_found = combinations_with_repetitions(elements, TheHiddenCode.size());
std::cout << "total combination you can try = " << combi_found.size() << std::endl;



and in the 2 following function, I use the recursion/induction approach:


void combinations_with_repetitions_recursion(deque< vector<char> >& combi, const vector<char> &elems,
unsigned long req_len,
vector<unsigned long> &pos,
unsigned long depth)
{
// Have we selected the number of required elements?
if (depth >= req_len) {
vector<char> depth_r_combi;
for (unsigned long ii = 0; ii < pos.size(); ++ii){
depth_r_combi += elems[pos[ii]];
}
//copy(depth_r_combi.begin(), depth_r_combi.end(), ostream_iterator<char>(cout, " ")), cout << endl;
combi.push_back(depth_r_combi);
return;
}

// Try to select new elements to the right of the last selected one.
for (unsigned long ii = 0; ii < elems.size(); ++ii) {
pos[depth] = ii;
combinations_with_repetitions_recursion(combi, elems, req_len, pos, depth + 1);
}
return;
}

deque<vector<char>> combinations_with_repetitions(const vector<char> &elems, unsigned long r)
{
if(r > elems.size()){
throw std::logic_error("combination length (r) cannot be greater than the elements list (n)");
}

vector<unsigned long> positions(r, 0);
deque<vector<char>> combi;
combinations_with_repetitions_recursion(combi, elems, r, positions, 0);

return combi;
}


the 'depth' parameters is the key to stop the recursion and drill-up all the results. Based on those function we can easily create function to build permutations, combination(without repetitions), and ....