Pyton - How to find out if a key exists in a dictionary

9. April 2013 08:00

 

Another simple python example which is how to find out if a key exists in python

 

Just use "if" and "in" like in the following example

 

 

>>> x['item1'] = 0
>>> if 'item1' in x:
...  print "True"
...
True

 

 

Some of the mistakes that I have seen is this will "appear" to work correctly but in fact it does not. Have a look at these examples. You can see here that it will fail because it is testing the value rather than the key.

 

 

>>> x['item1'] = 1
>>> if x['item1']:
...  print "True"
...
True
>>>

>>> x['item1'] = 0
>>> if x['item1']:
...  print "True"
...
>>>
E-mail Kick it! DZone it! del.icio.us Permalink


Python - json encode / decode

4. April 2013 08:00

 

This is a short example to be able to encode / decode json inside python. Its actually really easy to do.

You will first need to import the json library using

import json

 

Encoding to json

 

>>> x = {}
>>> x['1'] = 0
>>> x['2'] = 0
>>> x['3'] = 0
>>> x['4'] = 0
>>> json.dumps(x)

 

Deocoding from json

 

>>> x = json.loads('{"1": 0, "2": 0, "3": 0, "4": 0}')
>>> print x
{u'1': 0, u'3': 0, u'2': 0, u'4': 0}
>>>

 

It really is as simple as that!

E-mail Kick it! DZone it! del.icio.us Permalink


C++ - std::vector add, insert, remove, process, erase, swap, sort, clear

2. April 2013 08:00

 

Here is some examples of how to use std::vector with string for most of the common operations that can be performed on std::vector.

 

The following example assume the following has been declared

 

 

std::vector<std::string> vec;

 

 

Adding Items

vec.push_back("Item 1");
vec.push_back("Item 2");
vec.push_back("Item 3");
vec.push_back("Item 4");
vec.push_back("Item 5");

 

Adding Items to front

vec.insert(vec.begin(), "Front 2");
vec.insert(vec.begin(), "Front 1");

 

Remove Last Item

 

vec.pop_back();

 

 

Remove Last Item

 

vec.erase(vec.end());

 

 

Remove First Item

 

vec.erase(vec.begin());

 

 

Process All Items

for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
  printf("%s\n", it->c_str());
}

 

Process All Items

for(size_t i = 0; i < vec.size(); i++)
{
  printf("%s\n", vec[i].c_str());
}

 

Reverse The Order - Note you can also just run the above backwards instead.

for(size_t i = 0; i < vec.size() / 2; i++)
{
  std::string tmp = vec[i];
  vec[i] = vec[vec.size() - i - 1];
  vec[vec.size() - i - 1] = tmp;
}

 

Sorting

std::sort(vec.begin(), vec.end());

 

Find and Remove an item

for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
  if (*it == "Item 2")
  {
    vec.erase(it);
    break;	//it is now invalud must break!
  }
}

 

Clear All Items

vec.clear();
E-mail Kick it! DZone it! del.icio.us Permalink


C++ - Why you need a copy constructor

29. March 2013 10:29

 

In C++ you may come across an issues where you need to use a copy constructor. This is because when a class is assigned from one variable to another it has to copy the values across. If we are dealing with pointers that are inside the class then the pointer will be copied. So this can create and issue if the pointer is deallocated in the destructor. Since now there is two copied of the same pointer which is going to be deallocated twice. This will result in a common issue such as a double free.

 

In this short program you can see the effect here that will cause a double free. In this case I am using "malloc" to keep the example short. The following program will crash when the main function returns as it will call free from the destructor twice on the same pointer value.

 

 

class MyClass {
    public:
        char *buf;
		size_t buf_len;

        MyClass(size_t len) {
            printf("Alloc\n");
			buf_len = len;
            buf = (char *) malloc(len * sizeof(buf));
        }

        ~MyClass() {
            printf("Free\n");
            free(buf);
        }
};


int main(int argc, char **argv) {
    MyClass x = MyClass(4096);
    MyClass y = x;

    return 0;
}

 

 

To get another the issue above in C++ we must use a copy constructor which will allow us to override the default functionality when the class is copied in order to allocate and copy the contents of the buffer and a new pointer which will completly seperate the source class from the new class that is being assigned.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

class MyClass {
    public:
        char *buf;
		size_t buf_len;

        MyClass(size_t len) {
            printf("Alloc\n");
			buf_len = len;
            buf = (char *) malloc(len * sizeof(buf));
        }

        ~MyClass() {
            printf("Free\n");
            free(buf);
        }
        
        MyClass(const MyClass &source)
        {
        	buf_len = source.buf_len;
        	buf = (char *) malloc(buf_len * sizeof(buf));
        	memcpy(buf, source.buf, buf_len);
        }
};


int main(int argc, char **argv) {
    MyClass x = MyClass(4096);
    MyClass y = x;

    return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


C++ - Boost Optional

27. March 2013 17:21

 

Using boost::optional can be an advantage in certain situation. In C++ it effectivly works by being able to turn any datatype into a nullable value. It works much the same way as returning a null pointer to an object but without using a pointer. Instead this will work by being able to return an object which may or may not valid.

 

It is typically used to return a value from a function where the function may fail in certain situations. If you attempt to use the optional value which has not been set it will fail and the program will abort. This of course is also useful for debugging in order to catch issues sooner rather than later by accessing various variable that may not have valid values.

 

It can of course also be used to pass optional paramaters to functions where you may not want to use operator overloading.

 

Here is an example of it converting an string to an int which will obviously fail on one of the strings.

#include <stdio.h>
#include <string>

#include <boost/optional.hpp>

boost::optional<int> func(const std::string &str)
{
        boost::optional<int> value;
        int tmp = 0;

        if (sscanf(str.c_str(), "%d", &tmp) == 1)
                value.reset(tmp);

        return value;
}

int main(int argc, char **argv)
{
        boost::optional<int> v1 = func("31245");
        boost::optional<int> v2 = func("hello");

        if (v1)
                printf("%d\n", v1.get());
        else
                printf("v1 not valid\n");

        if (v2)
                printf("%d\n", v2.get());
        else
                printf("v2 not valid\n");

        return 0;
}
The output of the above is
31245
v2 not valid
E-mail Kick it! DZone it! del.icio.us Permalink