Archive for the ‘Home’ Category:

It was very strange, I got a new 2 TB external USB drive for Christmas and I noticed a number of windows (nautilus windows) opening up throughout the night. So I would wake up to find 20 - 30 windows opened to the media mount directory (/media). Overtime and watching the logs, I noticed that the new USB drive was disconnecting itself and then reconnecting. As it would reconnect and mount, the new mount point /media/<some long character string> would pop open in a nautilus window. When the drive would eventually disconnect, the opened nautilus window would no longer have access to the data and would display contents from one directory up (/media). After a couple days I finally found the answer and tried it and it worked as advertised.

For those having the same problem, this is where I found the solution you see below.

Just as an attention grabber - we are going after this example in this article:

Keeping up

Ok, seeing that the php versions of open flash chart and open flash chart swf files continually change along with with the API (not saying this is a bad thing), I wanted to come up with an even more abstract solution. The goal is to not have to worry when the swf file is released with the latest set of graphs or changes its API. I simply don't want to worry about this method or that method, or this class or that class.

Feedback

This article will sort of act as a tutorial for those interested in metaprogramming and as a set of instructions for those looking to experiment with the latest version of the OFC II Rails Plugin that I am currently toying with. I would like to hear feedback, but just remember that phase 1 of this release will be very basic, meaning none of the ajaxy stuff. It will come, just not yet.

Let's see what we can get away with

I am already using method_missing() for pretty much everything in the OFC II Rails Plugin that is being used now. But every time new classes are added, I have to sit down and basically convert the php class to ruby - just plain tedious, not really what I had planned when I started all this. Ok, so method_missing() was great, but let me introduce (or possibly reintroduce) you to const_missing(), basically method_missing() but instead of methods, we can create classes or modules or other objects on the fly. This will definitely help when the php version gets a new class. Instead of getting hounded to update the rails version to be 100% like the php version, everything will just work, no updates to code required. Well, we hope ! So check this out:

Here is what we did with method_missing():

1234567891011121314151617181920212223

moduleOFCclassBasedefmethod_missing(method_name, *args, &blk)case method_name.to_swhen/(.*)=/# i.e., if it is something x_legend=# if the user wants to set an instance variable then let them# the other args (args[0]) are ignored since it is a set methodself.instance_variable_set("@#{$1}", args[0])when/^set_(.*)/# backwards compatible ... the user can still use the same set_y_legend methods if they wantself.instance_variable_set("@#{$1}", args[0])elseif inst = self.instance_variable_get("@#{method_name}") instelse# if the method/attribute is missing and it is not a set method then hmmmm better let the user knowsuperendendendendend

This says that any undefined (missing) constant of OFC should be defined as a new class that inherits from OFC::Base.

So when we say OFC::Foo, that has not been defined, so we will get back class OFC::Foo < OFC::Base;end; which will give us the initialize() method and method_missing() method from above. Let's see how this works:

So it all sort of came together right there. I've shown you all the code that comes with the Rails Open Flash Chart plugin now. No more definining idividual classes, no more trying to keep up with the never ending php version, and no more late nights converting php to ruby (!). About dang time.

Ok, but this is just the beginning, nothing has been set in stone, so like I said, give me your feedback, what works for you and what does not. And, hopefully, I will have solutions for you or you for me.

Example with new version (test version)

I am using rails 2.3.2, but I don't think it will matter what version you are using.

Create a controller to play in

123

> pullmonkey$ ./script/generate controller test_it# <And more stuff >

Get our assets

1234567

# first we will get swfobject.js> pullmonkey$ cp vendor/plugins/open_flash_chart/assets/javascripts/swfobject.js public/javascripts/# next the open flash chart swf (GET whatever is the latest version), right now that is here: http://teethgrinder.co.uk/open-flash-chart-2/open-flash-chart.swf> pullmonkey$ cd public/> pullmonkey$ wget http://teethgrinder.co.uk/open-flash-chart-2/open-flash-chart.swf> pullmonkey$ cd ..

Edit our controller

One thing you will notice about the examples, is that the php code is in the comments, so you can see how I would convert from the php examples to ruby. Please feel free to add your own examples, just fork the project.

I've been using the spreadsheet gem lately for a couple projects I am working on to modify existing spreadsheets. I have quite often stumbled upon this error when opening modified spreadsheets in excel:

File error: data may have been lost

Like most microsoft errors, it was useless and the spreadsheet came up just fine. But that error was just so annoying, other spreadsheet applications (open office, excel on mac) opened without any problems. So after quite a bit of hacking and digging around, I finally tried setting the encoding, which defaults to UTF-8. Well it just so happens that the spreadsheet being modified was encoded with UTF-16LE.

So part one of my solution became this:

12

Spreadsheet.client_encoding = 'UTF-16LE'

Then doing a little more digging I decided that this would be a better long-term solution:

Got an email today, I have seen it before and I am sure it has been going around for years. This time, I thought that I would do an exercise and create a plugin that duplicates what I found in this email. See for yourself.

Here is the email I got:

What I gathered was that the only important letters are the first and last letter of each word, those have to be in the right order. So the rest of the letters can be in any random order. That is what I did - I created a plugin and put it out on github. You can install it like this:

This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.

So for this assignment we are only going to be doing input and output. So the only header file we need is the iostream library.

1234

#include<iostream>using namespace std;

Defining the Node Class

For the node class we need 5 private variables: type, value, node1, node2, next, a constructor, 5 member functions, and a friend class.

Because most of the functions only return a single variable it would be a waste to have the functions outside the class so I put them all inside the class.

This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.

So for this assignment we are going to be doing a lot of math calculations so we are going to need the include the both the iostream and the cmath libraries. We will also need the value of pi.

Writing the Actual Functions for the Complexn Class

First we have the 3 constructors and the copy constructor:

12345678910111213141516171819202122232425

// takes no arguments and sets r and i to 0.0complexn::complexn(){ r = i = 0.0;}// takes 1 argument and sets r to the argument and i to 0.0complexn::complexn(double real){ r = real; i = 0.0;}// takes 2 arguments and sets r to the first and i to the secondcomplexn::complexn(double real, double imag){ r = real; i = imag;}// this is a copy constructor that dereferences the complexn variable if it is referencedcomplexn::complexn(const complexn &c){ r = c.r; i = c.i;}

Next, we have the 3 member functions:

123456789101112131415161718192021222324252627282930

// takes no arguments and returns the distance from the 0 as a doubledouble complexn::complexabs(){return sqrt(pow(r,2.0) + pow(i,2.0));}// takes no arguments and returns the angle of the complex point as a double in radiansdouble complexn::complexangle(){double angle; // angle of coordinate from positive x axis angle = atan(r / i);if(r < 0 and i >= 0)return PI - abs(angle);if(r < 0 and i < 0)return -(PI - abs(angle));return angle;}// takes no arguments and returns the conjugate of the complex number as a complexn classcomplexn complexn::complexconj(){ complexn temp = *this; // complex number used for calculations temp.i *= -1;return temp;}// takes one complexn type argument and returns the distance between the argument and the current instancedouble complexn::distance(const complexn &temp){return sqrt(pow(temp.r -r, 2.0) + pow(temp.i - i, 2.0));}

I don't do too much with php these days, and really haven't since I found rails many years ago. But I figured I would give magento a try, just for fun. Most of it worked, but I continually came across this PCRE error - the full error that I go was:

Warning: preg_match_all() [function.preg-match-all]: Compilation failed: this version of PCRE is not compiled with PCRE_UTF8 support at offset 0 ...

Ok, loads and loads of research led no where, or at least no where that I was willing to go. I tried so hard to find a solution that didn't require me recompiling apache ... well no such luck. I am using slicehost's ubuntu 8.04, so I took the dpkg approach to help make things simple.

Well, I am sure you have found out by now that apache comes with its own version of pcre built in (version 5). This version does not come with UTF-8 support. The trick is to tell apache to use an external system package of pcre. This requires the slightest bit of reconfiguring of apache.

Initially, my pcre looked like this (notice the version of 5.0...):

As mentioned earlier this is a pretty good indicator that your pcre is the built-in apache version. This is not good.

Ok, the solution is not too bad. Compared to this article, which I learned a few things from, it is much simpler. One thing, you will note in the article is the use of --with-pcre=/usr - this is quite different than the --with-pcre=yes that apache2 comes configured with from gusty.

So the solution is to make that change by doing this:

1) Get the source code:

123

mkdir apache_srccd apache_src/apt-get source apache2

2) Modify the configuration (specifically the AP2_COMMON_CONFARGS in debian/rules)
Once the source is downloaded you should have several files and a directory. Edit the debian/rules files from within the apache directory. The only change that is needed is to find the line that says --with-pcre=yes and change it to say --with-pcre=/usr.

This, of course, assumes that you installed pcre and it lives in /usr/(bin,lib ...):

12

vi apache2-2.2.4/debian/rules # make those changes./apache2-2.2.4/debian/rules

This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.

So for this assignment we are going to be doing a lot of math calculations so we are going to need the include the both the iostream and the cmath libraries. We will also need the value of pi.

Defining the Coordinate Class

For the coordinate class we need 2 private variables x and y, 3 constructors, and 11 member functions.

The way you do the constructors and member functions can be done 2 different ways. You can either do them inside the class, or you can define them inside the class, like you do prototypes, and then have the actual functions at the bottom of your code. I like to define them and then put the functions at the bottom, making the code a little bit easier to read so that is the way that I'll show you, but if you want to do it the other way then just do it how you normally would with a regular function.

So here is what your class should look like (keep in mind that this all goes at the top before the main function):

123456789101112131415161718192021222324

class coordinate{private:double x; // x value of the coordinate pointdouble y; // y value of the coordinate pointpublic: coordinate(); // 1st constructor requiring that no arguments are passed coordinate(double ); // 2nd constructor requiring that only 1 argument is passed coordinate(double , double ); // 3rd constructor requiring that 2 arguments are passedvoid set(double , double ); // sets both values and requires 2 arguments to be passedvoid setx(double ); // sets x value and requires 1 argument to be passedvoid sety(double ); // sets y value and requires 1 argument to be passedvoid read(); // allows user to input both x and y values void print(); // prints out the coordinate point in "(x, y)" formdouble distancezero(); // calculates distance of point from zero and returns the valuedouble distancetwo(coordinate ); // calculates distance between 2 points (current instance and coordinate value passed) and returns the valuedouble ranglezero(); // calculates the angle of the coordinate in radians and returns the valuedouble danglezero(); // calculates the angle of the coordinate in degrees and returns the valueint quadrant(); // find what quadrant the coordinate is in and returns the valuevoid midpoint(coordinate ); // calculates the midpoint between 2 points (current instance and coordinate value passed) and prints the value as a coordinate};

Writing the Actual Functions for the Coordinate Class

Since we are not actually writing the functions in the same place we are doing the class we will write them at the bottom after the main function. However, to do this we will need a little more than what we would with regular functions. For member functions we have to define what class the function is actually a member of. To do this we have to do coordinate::[function]().

Next, is the read and print functions. All we want the read to do is to do a cin of the 2 values (x and y). The print is just the opposite. All it does is do a cout of the x and y values in the (x, y) format.

Next, we have the distance functions. distanczero calculates the distance of the current instance coordinate from 0. distancetwo calculates the distance between 2 points (the current instance and the coordinate passed in).

Next, we have the angle functions. ranglezero uses the function in the math library atan()(arc tangent) to find the angle in radians from the positive x axis. danglezero does the same thing but converts the value from radians to degrees. To convert from radians to degrees you multiply the value by 180 / pi

Next, we have the quadrant function. This looks at whether the x and y values are positive or negative to determine which quadrant the coordinate is in. It will return the number of the quadrant as an integer 1-4 and 0 if the coordinate is (0, 0)

Last, we have the midpoint function. you will need to pass this function a coordinate instance and it will calculate the midpoint between the current instance and the passed instance and print the coordinate instance.

Update: Bloggity does not require the Engines plugin to run if you are using Rails 2.3 or above (where the Engines plugin is baked in). -- Noted below by Bill.

Update: Added the plugin to github - simple_blog. It is not production ready or really all that usable quite yet.

Ok, so this a rant and I am sorry for that - but as simple as it is, I have been looking for a blog plugin lately. The problem with the plugins I find is that I don't want to have to deal with the engines plugin or have the controllers, models, views, etc ... all extracted into my applications code. I want it all external (hence a plugin) but let it be minimally configurable.

So in my recent search for a blog plugin for rails, I came across two that look very useful, but each with their flaws:

1) bloget - Everything is extracted to my code space. Why? Yes, I realize that it is most likely because I will want to override things, but get out of my space and keep to yourself!

Provide me a way to override things that I would need to (there really shouldn't be too many), after all it is ruby.

2) bloggity - Uses the engines plugin! I have nothing against the engines plugin (I think it is well written and documented) but for a freaking blog plugin?!? Why?

Is there a third option?

Glad you asked - yes, there is a third option - I hate to say it, but do it right! There's your third option.

Ok, but really, if there is a third option (a third plugin), I would love to hear about it.

Ok, so all that to lead up to a little plugin tutorial? Well, it got your attention didn't it?

This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.

Part A

1. Create a structure (called point) that includes a time and y value (both doubles).

This is very simple using the typedef struct and listing your variables.

1234567

typedefstruct{double time;double y;} point;

2. Create a main program that has an array of 40 points (or structures), keeps track of the number of values in the array and has variables for each of the values needed to calculate above.

In the main program we will need an array of points p, an integer with the total number of points values, and 4 double variables, one for each of the functions (I used vert_shift, amp, freq, and phase_shift).

Then you will need to call each function and for testing I printed each value out to make sure everything was coming in right. It is short, simple, and to the point like all programming should be. Your main should look something like this:

3. The main program should then call the read_data function. This function will have one argument (the array of points - or structures - which will be passed as a pointer to the function) and will return the number of values in the array. It should read the data from the data file using a pointer and the arrow (->) operator.

First, we are going to be reading from a file in this function so we are going to need to include the fstream library.

123

#inlcude <fstream> // reading from file

Next, we need to create the prototype for this function called read_data. This will go above the main. The read_data function will need the array of points and will return the total number of points as an integer. So it should look like this:

123

int read_data(point *);

Now below the main we can create our function and lets call the array of points a. In this function we will need 2 more variables, an integer (total) for counting the number of points that we read from the file and an ifstream variable (f) for opening and closing the file.

First, we need to try to open the file using f.open("sp09prog1.txt"). Next, we need to test to make sure the file was opened and that we can read from it and if not then print out error message and exit. If the file was opened then we need to read in the values into the point array and count the number of points using the total integer variable. We do this until we read the end of the file and we find out if we are at the end of the file with f.eof(). Finally, we will want to return the total. It should look like this:

Notice that we return total - 1. This is because we increment total and then we find out it is the end of the file. So we incremented one too many times so we need to subtract 1 before returning it.

4. Main should then call the vertical function to calculate the vertical shift. This function has two arguments (the array of points - passed as a pointer - and the number of values in the array). It will calculate the vertical shift by finding the average of the maximum and minimum y-values. You will need to search through the array of points to find these max and min values.5. Next, main will call the amplitude function to calculate the amplitude. This function has two arguments (the array of points - passed as a pointer - and the number of values in the array; you must also use the arrow operator in this function) and will return the amplitude. To find the amplitude, you need to calculate half the difference between the maximum and minimum values of the y-values (you will need to search through the array for the maximum and minimum values again).

The functions are both almost identical. The only difference is the equation at the end so we will do them at the same time.

First, we will create the prototypes. Both functions take the array of points and the integer total number of points and they both return a double. So the prototypes should look like this:

1234

double vertical(point *, int );double amplitude(point *, int );

So lets call the point array p and the integer total.

To find the max and min values we need to create 2 double variables (max and min) and an integer (lcv) that we will use for the loop.

Next we will need to set both max and min to the first y element in the array of points. Then we will have a loop and start from 0 to total. Each time we run through this loop we need to do 3 things:

1. Test if max is less than the current y value? If yes then set max to the current y

2. Test if min is greater than the current y value? If yes then set min to the current y

3. Increment a to the next position in the array. Because we are using a pointer to the array we can do this easily by doing a++

Next we will just return the result of the equation as a double. So your functions should look something like this:

6. The next function called by main is the frequency function that has two arguments (the array of points - passed as a pointer - and the number of values in the array; again using the arrow operator to access values) and will return the frequency. To calculate the frequency, find the period which is time difference between the maximum and minimum y-values and multiply by 2. Then, divide to calculate the frequency. Please note that you are using the difference between time values, not the y values, to perform the overall computation.7. Finally, main will call the pshift function that contains two arguments (the array of points - passed as a pointer - and the number of values in the array; again using the arrow operator to access values) and will return the phase shift or horizontal shift. This shift can be found by finding the average of the time values where the maximum and minimum y-values occur; then subtracting it from half the period (see step 6 to find the period).

The functions for steps 6 and 7 are both almost identical expect for the equation at the end so we will do these both at the same time.

For the frequency function we will need to use the absolute value function in the cmath library. To include this you will need to do this at the top of your file.

123

#include<cmath>

Like the functions in step 4 and 5 they need to have the array of points and the integer total number of points and they both return a double. So the prototypes should look like this:

1234

double frequency(point *, int );double pshift(point *, int );

So lets call the point array p and the integer total.

To find the max and min values we need to create 2 pointers to point variables (max and min) and an integer (lcv) that we will use for the loop.

Next we will need to set both max and min pointers to the same address as a points which is the first position in the array of points. Then we will have a loop and start from 0 to total. Each time we run through this loop we need to do 3 things:

1. Test if max->y is less than the current a->y value? If yes then set max to the current a address.

2. Test if min->y is greater than the current a->y value? If yes then set min to the current a address.

3. Increment a to the next position in the array. Because we are using a pointer to the array we can do this easily by doing a++

Next we will just return the result of the equation as a double. So your functions should look something like this:

Notice how in the pshift function after the loop we do a -= total. This is because a is currently pointing the last element in the array and if we want to call frequency and pass the address of the first element in the array of points then we need to set a back to the first element.

Also notice that the frequency function uses a variable called PI. This is the value of pi so at the top above the main you will need to define it as a constant. You can do this one of 2 ways:

12345

#define PI 3.14159or constdouble PI=3.14159;

Either way will work but I prefer to use the #define since it uses less memory and only takes more processing when you compile the program not in running it.

Outcome

Using the text file provided this is what I got when I ran the program:

Part B

Using MATLAB, you need to plot the original data using the data file sp09prog1.txt. To do this, load the file into MATLAB, then assign the first column to be the x values and the second column to be the y values. You can then use the plot command to plot these (you should only plot the points - not any connecting lines).

This is easy. Use the load() function to read in data from the file into a matrix.

123

table = load('sp09prog1.txt')

Then we need to get the data into arrays of time and y. To do this use matrixvairable(row,column). Use a colon (:) to get everything in either the row or column. In this case we will want all rows in the first column for time and all rows and second column for y.

1234

time = table(: , 1)y = table(: , 2)

Then plot the data using the plot() function. For this you will need to pass 3 things (x values, y values, and symbol). Our x values is the array time and our y values is array y.

123

plot(time, y, 'o')

Then, using the values you found in the C++ program for each of the four variables, create a cosine curve that can be plotted over the data. You will need to create a matrix of x-values that run from 1 to 2π with an increment of π/100. Then, create a matrix of y values using the cosine equation: where vs is the vertical shift, ps is the phase shift, amp is the amplitude and freq is the frequency. Plot these x and y values using a red line.

This is just the same as the first part only we need to find the x and y values using equations. But first lets set all the values we will need for our calculations which we can get from Part A of the program.

1234567

vs = -4amp = 2.9956freq = 1.93329ps = -1.5166PI = 3.14159

Next we will have to create the array x with all the x values. In this case we are going to go from 0 to 2pi and step by pi/100. To do this we have a colon (:) between each argument like this:

123

x = 0 : PI / 100 : 2 * PI

Now, to create the array y with all the y values we use the equation we were given.

123

y = vs + amp * (cos(freq * x - ps))

Now, all we need to do is plot it on the graph. However, we want to plot the new equation on the same plot as the last one. To do this we need to use the command hold on. We also want the new graph to look different so lets make it a full line 4px wide and the color be dark red. Like this: