Tully Rankin

My blog includes various articles on Linux, PHP, BASH, Programming, Security, and other technology related topics.

MySQL Import CSV With Quotes

I was tasked to write a automated script to download a CSV file and import it into our database. This is an easy task but ran into an issue I hadn’t faced before. The CSV file had quotes on some columns and not on others. This was mix matched so my import script was not working properly. After doing some research I was able to get this working with the MySQL directive OPTIONALLY ENCLOSED BY.

Optionally Enclosed By Example
load data local infile 'example.csv' into table example_table
fields terminated by ','
OPTIONALLY ENCLOSED BY '"'
lines terminated by '\n'
(Column1, Column2, Column3)

C++ Random String

Yesterday I was working with vectors and pointers. I decided to create a simple script to display random phrases for fun. The code I wrote uses only 2 custom functions. The first function is to get a random number between 0-4 and display that index of the vector. The second is a function to display 70 newlines to clear the screen. To get a random index I use the srand and rand functions. The first function srand is used to seed the rand function. To get a number between 0-4 I used the expression (rand() % 4) which will produce 1 number between 0 and 4. In the main of my program I create a infinite while loop and use the usleep function to sleep the program after each run. I used this function so there was time to read each phrase.

C++ Random String



// Display Random String
// C++ Example
// www.TullyRankin.com
#include
#include
#include
#include
#include
#include
using namespace std;

string randomPhrase( const vector & p );
void clearScreen();

int main()
{
   vector phrases(4);
   phrases[0] = "The more I C, the less I see.";
   phrases[1] = "Backups? We don’t need no stinking backups.";
   phrases[2] = "Avoid the Gates of Hell. Use Linux";
   phrases[3] = "When you say \"I wrote a program that crashed Windows\",
   people just stare at you blankly and say \"Hey, I got those with the system, *for free*";
   clearScreen();
   while ( true )
   {
   cout << randomPhrase( phrases ) << endl;
   usleep(5000000);
   clearScreen();
   }
   return 0;

}

string randomPhrase( const vector & p )
{
   int size = p.size();
   srand( time(NULL) );
   return p[rand() % 4];
}

void clearScreen()
{
   for( int i = 0; i < 75; i++ )
      cout << endl;
}

Selection Sort Algorithm

Today I read a new chapter from DIETEL C++ How To Program on Pointers and Pointer-Based String. This chapter has been great on helping me understand how pointers work and why they are efficient. One of the algorithms the book discussed was the Selection Sort Algorithm. This was a simple algorithm but explains that it is inefficient on large lists and can even be slower on it’s similar algorithm the insertion sort. The way this algorithm works is that it iterates through the array selecting the smallest element in the array and swapping it with the first element. This process continues until it reaches the second to last element in the array. I have provided an example of the sort in C++ which you can view from the link below.

Selection Sort Algorithm

Bubble Sort PHP Example

Yesterday I posted an example of the Bubble Sort algorithm in C++. Today I wrote the sorting algorithm in PHP. I have provided an example of the Bubble Sort Algorithm in PHP.


// Bubble Sort Algorithm
// www.TullyRankin.com/bubble-sort-php

$numbers = array(1,3,2,5,2);
$array_size = count($numbers);

echo "Numbers before sort: ";
for ( $i = 0; $i < $array_size; $i++ )
   echo $numbers[$i];
echo "\n";

for ( $i = 0; $i < $array_size; $i++ )
{
   for ($j = 0; $j < $array_size; $j++ )
   {
      if ($numbers[$i] < $numbers[$j])
      {
         $temp = $numbers[$i];
         $numbers[$i] = $numbers[$j];
         $numbers[$j] = $temp;
      }
   }
}

echo "Numbers after sort: ";
for( $i = 0; $i < $array_size; $i++ )
   echo $numbers[$i];
echo "\n";

Bubble Sort Algorithm

Was reading about sorting arrays in C++ and came across the bubble sort. Wikipedias definition says the bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

Example Bubble Sort Algorithm in C++


// Bubble Sort in C++
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

    int num[ 10 ] = { 0, 2 ,1 ,55 ,22, 77, 32, 22, 77, 99 };
    int numSize = 10;
    int temp;

    // Before sorting
    cout << "Before the sort! " << endl;
    for ( int i = 0; i < numSize; i++ )
        cout << setw(5) << num[i];
    cout << "\n\n";

    for( int i = 0; i < numSize; i++ )
    {
        for (int j = 0; j < numSize; j++)
        {
            if ( num[i] < num[j] )
            {
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
            }
        }
    }

    cout << "After the sort!" << endl;
    for ( int i = 0; i < numSize; i++ )
        cout << setw(5) << num[i];
    return 0;
}

Ubuntu 64 10.04 LTS Flash

Today I upgraded to Ubuntu 10.04 LTS. After upgrading I was unable to get flash working. I had successfully installed  the 32bit version working with flash at work. After doing some searches on Google for my problem, I found the cause. The problem is that the version in the repository is for the 32 bit version. This was not going to work. After doing some more research, I found a shell script that could get flash working

Steps to get flash working under Ubuntu 10.04 LTS.

  1. Open up a terminal Applications->Accessories->Terminal
  2. wget http://www.tullyrankin.com/code/ubuntu-64-10-04-flash.sh
  3. chmod +x ubuntu-64-10-04-flash.sh
  4. ./ubuntu-64-10-04-flash.sh

Ubuntu 64 10.04 LTS Flash Player Fix

JAVA Letter Frequency

I picked up a book on JAVA this last weekend at the local borders. The book I bought was JAVA in 24 hours. So far I’m on page 116 in 2 days and the read is very easy. I’m currently on chapter 9 “Storing Information with Arrays” and found JAVA a very easy language to pick up. In this chapter they have an example program that counts the letter frequency in an array of phrases. I thought this was a pretty cool and have provided the JAVA class below.

I plan on developing Android applications within the next couple months. I set-up the Android SDK and emulator with Net Beans IDE. So far I have only created the basic “Hello World!” application which I got running successfully. I will provide my Android application code on this site as soon as I have some source code to reveal.

// Word Frequency Class

class Wheel {
public static void main(String[] args) {
String phrase[] = {
"A STITCH IN TIME SAVES NINE",
"DON'T EAT YELLOW SNOW",
"JUST DO IT",
"EVERY GOOD BOY DOES FINE",
"I WANT MY MTV",
"I LIKE IKE",
"PLAY IT AGAIN, SAME",
"FROSTY THE SNOWMAN",
"ONE MORE FOR THE ROAD",
"HOME FIELD ADVANTAGE",
"VALENTINE'S DAY MASSACRE",
"GROVER CLEVELAN OHIO",
"SPAGHETTI WESTERN",
"AQUA TEEN HUNGER FORCE",
"IT'S A WONDERFUL LIFE"
};
int[] letterCount = new int[26];
for (int count = 0; count < phrase.length; count++) {
String current = phrase[count];
char[] letters = current.toCharArray();
for (int count2 = 0; count2 < letters.length; count2++) { char lett = letters[count2]; if ( (lett >= 'A') & (lett <= 'Z') ) {
letterCount[lett - 'A']++;
}
}
}
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount[count - 'A'] +
" ");
}
System.out.println();
}
}

Output:
A: 22 B: 1 C: 4 D: 9 E: 34 F: 7 G: 6 H: 7 I: 18 J: 1 K: 2 L: 10 M: 8 N: 19 O: 20 P: 2 Q: 1 R: 12 S: 15 T: 20 U: 4 V: 7 W: 6 X: 0 Y: 7 Z: 0

C++ Development Phases

Phase 1: Creating a Program
Phase 1 consists of editing a file with an editor program (normally known simply as an editor). You type a C++ program (typically referred to as source code) using the editor, make any necessary corrections and save the program on a secondary storage device, such as your hard drive. C++ source code filenames often end with the .cpp, .cxx, .cc or .C extensions (note that C is in uppercase) which indicate that a file contains C++ source code. See the documentation for your C++ compiler for more information on file-name extensions.
Two editors widely used on UNIX systems are vi and emacs. C++ software packages for Microsoft Windows such as Microsoft Visual C++ (msdn.microsoft.com/vstudio/express/visualc/default.aspx) and Code Gear C++ Builder (www.codegear.com) ahve editors integrated ito the programming environment. You can also use a simple text editor, such as Notepad in Windows, to write your C++ code. We assume you know how to edit a file.

Phase 2 and 3: Preprocessing and Compiling a C++ Program
In phase 2, you give the command to compile the program. In a C++ system, a preprocessor program executes automatically before the compiler’s translation phase begins (so we call preprocessing phase 2 and compiling phase 3). The C++ preprocessor obeys commands called preprocessor directives, which indicate that certain manipulations are to be performed on the program before compilation. These manipulations usually include other text files to be compiled, and perform various text replacements. In phase 3, the compiler translates the C++ program into machine-language code (also referred to as object code).

Phase 4: Linking
Phase 4 is called linking. C++ programs typically contain references to functions and data defined elsewhere, such as in the standard libraries or in the private libraries of groups of programmers working on a particular project. The objectcode produced by the C++ compiler typically contains “holes” due to these missing parts. A linker links the object code with the code forthe missing functions to produce an executable image (with no missing pieces). If the program compiles and links correctly, an executable image is produced.

Phase 5: Loading
Phase 5 is called loading. Before a program can be executed, it must first be placed in memory. This is done by the loader, which takes the executable iamge from disk and transfers it to memory. Additional components from shared libraries that support the program are also loaded.

Phase 6: Execution
Finally, the computer, under the control of its CPU, executesthe program one instruction at a time.

Six logical units of a computer

Input unit – This is the “receiving” section of the computer. It obtains information (data and computer programs) from input devices and places this information at the disposal of the other units for processing. Most information is entered into computers through keyboards and mouse devices. Information also can be entered in many other ways, including by speaking to your computer, scanning images, uplaoding digital photos and videos, and receiving information from a network, such as the Internet.

Output unit - This is the “shipping” section of the computer. It takes information that the computer has processed and places it on various output devices to make the information available for use outside the computer. Most information output from computers today is displayed on screens, printed on paper or used to control other devices. Computers also can output their information to networks, such as the Internet.

Memory unit - This is the rapid-access, relatively low-capacity “warehouse” section of the computer. It stores computer programs while they are being executed. It retains information that has been entered through the input unit, so that it will be immediately available for processing when needed. The memory unit also retains processed information until it can be placed on output devices by the output unit. Information in the memory unit is typically lost when the computer’s power is turned off. The memory unit is often called with memory or primary memory. [Historically, this unit has been called "core memory," but that term is fading from use today.]

Arithmetic and logic unit (ALU) – This is the “manufacturing” section of the computer. It is responsible for performing calculations, such as addition, subtraction, multiplication and division. It contains the decision mechanisms that allow the computer, for example, to compare two items from the memory unit to determine whether they are equal.

Central processing unit (CPU) - This is the computer’s “administrative” section. It coordinates and supervises the other sections’ operations. The CPU tells the input unit when information should be read into the memory unit, tell the ALU when information from the memory unit should be used in calculations and tells the output unit when to send information form the memory unit to certain output devices. Many of today’s computers have multiple CPUs and, hence, can perform many operations simultaneously—such computers are called multiprocessors.

Secondary storage unit - This is the computer’s long-term, high-capacity “warehousing” section. Programs or data not actively being used by the other units normally are placed on secondary storage devices, such as your hard drive, until they are needed, possibly hours, days, months or even years later. Information in secondary storage takes much longer to access than information in primary memory, but the cost per unit of secondary storage is much less than that of primary memory. Other secondary storage devices include CDs and DVDs, which can hold hundreds of millions and billions of characters, respectively.

Apache Includes Parser

Wrote this script to read and parse all included files in httpd.conf or any file specified when calling the PHP script. Will output content from httpd.conf(or any file specified) and all included files found and output to stdout. I used this to pipe the output to grep when searching for various Apache directives. Useful to find directives that are in a included file that are overwriting your directives set in httpd.conf.


<?php
error_reporting
(0);
if (
$argc != 2) {
echo <<<FILE
#################################################

Reads all ”Included files” in specified file and outputs to stdout.

Usage: php $argv[0] file
Example: php $argv
[0] httpd.conf
#####################################

FILE;
}
else
{
$file = file($argv[1]);
$content = “”;
try {
foreach (
$file as $line) {
$line = str_replace(“\n”,“”,$line);
if (
stristr($line,‘Include’) && !stristr($line,‘#’)) {
if (
preg_match(‘/^.*\*\.conf$/’,$line)) {
$str = str_replace(“Include ”,“”,$line);
$str = str_replace(“*.conf”,“”,$str);
$dirFiles = @scandir($str);
foreach (
$dirFiles as $dirFile) {
if (
stristr($dirFile,“.conf”)) {
$content .= file_get_contents($str.$dirFile);
}
}
}
elseif (
preg_match(‘/^.*[a-zA-z0-9]\.conf$/’,$line)) {
$content .= file_get_contents(substr($line, 8));
}
else
{
$str = str_replace(“Include ”,“”,$line);
$dirFiles = @scandir($str);
foreach (
$dirFiles as $dirFile) {
if (
stristr($dirFile,“.conf”)) {
$content .= file_get_contents($str.$dirFile);
}
}
}
}
print_r($content);
}
} catch (
Exception $e) {
echo
$e->getMessage();
}
}