Posts Tagged ‘code



20
May
13

Keeping History Using the cd Command

If you use shell scripting a lot from the command line, this will probably improve your experience of it. This is for users of linux/mac command line or of cygwin on windows. Anywhere you can use the bash cd command.

Firstly (if you didn’t know) cd remembers the last directory you went to. To access this use;

cd -

This will change to the previous directory you were in. If you want to supercharge this you can add the following to your .bashrc/.profile/… customization file.

# petar marinov, http:/geocities.com/h2428, this is public domain
cd_func ()
{
  local x2 the_new_dir adir index
  local -i cnt

  if [[ $1 ==  "--" ]]; then
    dirs -v
    return 0
  fi

  the_new_dir=$1
  [[ -z $1 ]] && the_new_dir=$HOME

  if [[ ${the_new_dir:0:1} == '-' ]]; then
    #
    # Extract dir N from dirs
    index=${the_new_dir:1}
    [[ -z $index ]] && index=1
    adir=$(dirs +$index)
    [[ -z $adir ]] && return 1
    the_new_dir=$adir
  fi

  #
  # '~' has to be substituted by ${HOME}
  [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir="${HOME}${the_new_dir:1}"

  #
  # Now change to the new dir and add to the top of the stack
  pushd "${the_new_dir}" > /dev/null
  [[ $? -ne 0 ]] && return 1
  the_new_dir=$(pwd)

  #
  # Trim down everything beyond 11th entry
  popd -n +11 2>/dev/null 1>/dev/null

  #
  # Remove any other occurence of this dir, skipping the top of the stack
  for ((cnt=1; cnt <= 10; cnt++)); do
    x2=$(dirs +${cnt} 2>/dev/null)
    [[ $? -ne 0 ]] && return 0
    [[ ${x2:0:1} == '~' ]] && x2="${HOME}${x2:1}"
    if [[ "${x2}" == "${the_new_dir}" ]]; then
      popd -n +$cnt 2>/dev/null 1>/dev/null
      cnt=cnt-1
    fi
  done

  return 0
}

alias cd=cd_func

This means that you can keep a history of the past 10 directories which you have visited and change between them.

To access this list type

cd --

Which will print a list like.

0  /e/projects/dgc/or14126h_3
1  /e/projects/dgc/or14126h_3/orthotics.dev
2  /c/Users/dgc/Dropbox/Coding
3  /e/projects/dgc
4  /e/projects/dgc/or14126h_2
5  /e/devdisk/dcm/configs
6  /e/devdisk/dcm
7  /e/devdisk
8  /e

And then

cd -5

will take you to entry 5 in the list.

To be clear I did not write this, I found it in the default cygwin .bashrc. The author of this was Petar Marinov.

I have found this very helpful, particularly when using a new python module. This is the process;

  • I would be in my working area
  • download it from pypi
  • cd to my download area
  • untar it
  • cd into it
  • run python setup.py install
  • then want to go back but cd – would get me to my download area.

This function removes that minor inconvenience and I have found it very useful.

Thanks for reading.

Advertisements
18
Apr
13

Resource Acquisition is Initialization (RAII)

This post will be about the Resource Acquisition is Initialization (RAII) pattern which is a creational pattern. This is going to be the first non Gang of Four pattern I will write about.

The Purpose

The idea behind this pattern is to correctly dispose of all the resources that you acquire. This pattern was first written about by Bjarne Stroustrup, the creator of C++. The most common examples of this pattern are in opening and closing files and web sockets. It is also important in controlling mutexes so you can write tread safe code.

Continue reading ‘Resource Acquisition is Initialization (RAII)’

08
Apr
13

Comparisons in C++

This is about the comparison operators in C++ and making them easy to implement. There are 6 comparison operators in C++; ==, !=, <, <=, >, and >=. If you want to be able to apply all of these to a class, and you have the right type of order, you only need to implement one function which will determines them all. Incidentally this is called a total order, but I won’t go into what that means here.

The tl;dr of this is look at this repository and use a class from there to easily implement custom comparison operators.

This idea is to map the order onto the real numbers (doubles). So you have a function which takes two instances of a class and returns a double. If this function returns a negative number then the first instance is less than the second, if it returns 0 they are equal and if it returns a positive number then the first instance is greater than the second.

This will be easier to see with an example, so here is a class which is just data storage for an int.

Continue reading ‘Comparisons in C++’

25
Mar
13

C++ Sandbox

This is just a short post to tell you about my C++ sandbox. This is my area for trying out ideas (such as using mutable for caching) or testing C++ 11 features.

This is stored as a mercurial repository on bitbucket here. Please feel free to have a look or add to it if you have something you want to try out. I often use this to test answers to stackoverflow questions. A few of them have generated blog posts here as well.

The rest of this post is the current contents of the repository with a brief description of what I was trying to do with each file.

Arrays

In this file I was playing around with C style arrays, slightly old and a bit dated to be honest.

Comparisons

This may be a future post here. It defines a templatised base class for comparable class (using the curiously recurring template pattern . It means that if you inherit from this class and define one compare function, you get all 6 comparison operators.

ConstPointer

Testing out what you can do with const pointers. With a const Class* const you can only call const methods, with a Class* const you can call anything (this keeps the pointer const not what it points at) and with a Class* you can call anything.

Constness

Found an unusual bug and tested it here. If you have a reference (or a pointer) as a member of your class, in a const function you can call non-const functions on the member. This is because it doesn’t change the reference (or pointer) which the class keeps, what it does is change is the object it references.

CopyReference

Trying to copy a reference without using the copy constructor or assignment operator.

DivideByZero

I wondered what compiler errors/warnings you get from dividing by zero?
It turns out (in g++) that it will not give errors at all. It will warn you if you divide by a literal zero or a const zero, but not a variable with value zero.

ExclusiveOr

This was for checking the results of using xor on integers.

Lambda

This was testing the newly added lambda functions, but changed to using standard template library algorithms.

MustOverride

This was playing around with pure virtual functions with implementations. So you can call them using Base::function() in the derived class.

Mutable

Testing using a mutable member for data caching. This was the basis for the blog post mutable and data caching.

Operators

Testing calling operator() on pointer. Here is the calling code.

  Foo* f = new Foo();
  (*f)();
  (*f).operator()();
  f->operator()();

  delete f;

A common mistake doing this is to leave off the final brackets so.

  (*f).operator();
  f->operator();

But these will return a function pointer to operator(), they won’t call it.

Polygons

Archetypal polygon example for inheritance. A base polygon, a derived rectangle and triangle. Not great as you use a width and height for the polygon but not all polygons have it. Also I prepended all the classes with the letter C and allocated the instances as pointers to the base class.

SelfDeleting

Trying to make an executable to delete itself, unsurprisingly this doesn’t work.

SpareMemory

Something picked up from a dirty programming trick called the programming antihero (if you haven’t read that article I can’t recommend it enough!). In this there was a game programmer who reserved 2Mb of memory to lose later when memory was tight. I was testing to see how this worked by reserving some memory and checking memory usage. It is had to see the exact memory usage from this sort of thing due to differences in types of memory (i.e. private bytes/working set…) but it certainly took some memory.

StructClass

Testing out the differences between structs and classes in C++. I found that apart from private/public as default there is no difference! This includes if you declare class T in a template, you can still use a struct.

UserDefinedLiterals and UserDefinedLiteralsBinary

Trying to use C++ 11 user defined literals to be able to use syntax like this:

  Binary two = 10_b;

I was following a good guide from here.

VariadicPointerOffset

Quite a complicated file. I was trying to use variadic templates to access private methods of a class. Hopefully not of any practical use (it breaks encapsulation and is extremely fragile) but an interesting idea to try,

Windows

Unimplemented test for SetEvent() in windows.h.

get_env

Made to test getenv from cstdlib for getting environmental variables.

hashes

Using C preprocessor magic to join together variable names.

number_of_coins

Given an amount in cents (American currency as it was taken from an answer on stackoverflow) find the number of ways you can make it from quarters, dimes, nickles and pennies. This was taken from this answer.

stack_overflow_virtual

I didn’t think the reply to this question would compile so I tried it out. I realised you can override private virtual functions but not call them.

upper

My thoughts about the answer to this stackoverflow question being wrong, and my idea for a better way.

As always thanks for reading.

22
Feb
13

Iterator Pattern

This post will be about the Iterator pattern which is a behavioural pattern.

The Purpose

The idea behind this pattern is to have an object which you can loop over without needing to know the internal representation of the data. While in python nothing is private so you can find out the internals of the class, the iterator pattern gives you a standard interface.

Continue reading ‘Iterator Pattern’

21
Jan
13

Builder Pattern

This post will be about the Builder pattern which is a creational pattern.

The Purpose

The idea behind the builder pattern is to abstract away the construction of an object so that many implementations can use the same builder. This separates the construction logic of the desired class from it’s representation.

Continue reading ‘Builder Pattern’

21
Jan
13

Strategy Pattern

The strategy pattern is a behavioural design pattern. This means that it is a common communication method between objects and not concerned with how those objects are created or structured.

The Purpose

The idea behind the strategy pattern is to encapsulate the implementation details of an algorithm and make them interchangeable. This gives more flexibility in how an object can be used and enables each algorithm to be tested independently of the calling object.
Continue reading ‘Strategy Pattern’




Call Me
Endorse davidcorne on Coderwall

Categories

Copyright


© 2013 by David Corne.

Creative Commons License

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Advertisements