<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Hdelossantos.com&#187; Code</title>
	<atom:link href="http://www.hdelossantos.com/category/technology/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hdelossantos.com</link>
	<description>Tales of the Wisconsin Experience</description>
	<lastBuildDate>Sat, 21 Jan 2012 19:54:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Writing a *NIX Shell in C</title>
		<link>http://www.hdelossantos.com/2012/01/21/writing-a-nix-shell-in-c/</link>
		<comments>http://www.hdelossantos.com/2012/01/21/writing-a-nix-shell-in-c/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 19:51:52 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=707</guid>
		<description><![CDATA[The shell will take in a maximum line length of 512 characters. Additionally it will support batch execution of commands specified in an input file. To call the shell in batch execution mode execute as: The shell will fork and execute each process as a child process so that in the event of an infinite [...]]]></description>
			<content:encoded><![CDATA[<p>The shell will take in a maximum line length of 512 characters. Additionally it will support batch execution of commands specified in an input file. To call the shell in batch execution mode execute as:</p>
<pre class="brush: plain; title: ; notranslate">
./shell &lt;input file&gt;
</pre>
<p>The shell will fork and execute each process as a child process so that in the event of an infinite loop the terminal can still respond to the SIGTERM command. Output can be piped to an external file using the &#8220;<b>></b>&#8221; operator. In the event that the destination file is not found, it is created with the permissions <b>755</b>. The permissions and line length can be changed in the parameters in the header file below.<br />
<span id="more-707"></span><br />
The header files declares the two functions which will be used. The <b>trimspace</b> function trims a given string of leading and trailing spaces. The <b>executecmd</b> function is given a command line to execute.</p>
<p><b>shell.h</b>:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;stdio.h&gt;
#include &lt;assert.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;sys/wait.h&gt;
#include &lt;unistd.h&gt;
#include &lt;ctype.h&gt;

#define MAX_ARGS 512
#define PERMS 0755

char *trimspace(char *str);
void executecmd(char *commands);
</pre>
<p><b>shell.c</b>:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;537sh.h&quot;

// Trim function from code @:
// http://goo.gl/gVRb
char *trimspace(char *str){
	char *last;

	while(isspace(*str)) {
		 str++;
	}
	if(*str == 0) {
		return str;
	}

	last = str + strlen(str) - 1;
	while(last &gt; str &amp;&amp; isspace(*last)) {
		 last--;
	}

	*(last + 1) = 0;

	return str;
}
</pre>
<p>The <b>executecmd</b> function:</p>
<p>This function sets up the default error message to output on any type of error, and a variable to store the child process ID information. </p>
<pre class="brush: cpp; title: ; notranslate">
void executecmd(char *commands) {
	char error_message[30] = &quot;An error has occurred\n&quot;;
	pid_t child_pid;
</pre>
<p>It then checks to see if the &#8220;<b>+</b>&#8221; operator is used. This operator is used to feed more than one command per line. It works similar to the &#8220;<b>&#038;&#038;</b>&#8221; operator in the Linux shell. </p>
<pre class="brush: cpp; title: ; notranslate">
	// Split the input line if the multiple cmd operator is used
	char *argv_parent[MAX_ARGS];
	int more_args_parent = 1;
	int argv_index_parent = 0;

	argv_parent[argv_index_parent++] = strtok(commands, &quot;+&quot;);
	while(more_args_parent) {
		argv_parent[argv_index_parent++] = strtok(NULL, &quot;+&quot;);
		if(argv_parent[argv_index_parent - 1] == NULL) more_args_parent = 0;
	}
</pre>
<p>Since every command can have a redirect to an output file &#8220;<b>+</b>&#8220;, or a sorted redirect to an output file &#8220;<b>==</b>&#8221; it must check every individual command which was separated using the string tokenizer <b>strtok</b>.</p>
<pre class="brush: cpp; title: ; notranslate">
	// For every split command fork &amp; exec
	int i;
	for(i = 0; i &lt; argv_index_parent; i++) {
		// Variables
		char *redirect = (char*) malloc(512);
		char *redirraw = NULL;
		char *sortredirraw = NULL;
		char *redirect_args[MAX_ARGS];
		int more_args_redirect = 1;
		int index_redirect = 0;

		if(argv_parent[i] != NULL) {
			redirraw = strchr(argv_parent[i], '&gt;');
			sortredirraw = strstr(argv_parent[i], &quot;==&quot;);

			if(redirraw != NULL) {
				redirect_args[index_redirect++] = strtok(argv_parent[i], &quot;&gt;&quot;);
				while(more_args_redirect) {
					redirect_args[index_redirect++] = strtok(NULL, &quot;&gt;&quot;);
					if(redirect_args[index_redirect - 1] == NULL) more_args_redirect = 0;
				}
				if(redirect_args[1] != NULL) {
					// There must be a redirect location
					redirect = trimspace(redirect_args[1]);
				}
			}
			else if(sortredirraw != NULL) {
				redirect_args[index_redirect++] = strtok(argv_parent[i], &quot;==&quot;);
				while(more_args_redirect) {
					redirect_args[index_redirect++] = strtok(NULL, &quot;==&quot;);
					if(redirect_args[index_redirect - 1] == NULL) more_args_redirect = 0;
				}
				if(redirect_args[1] != NULL) {
					// There must be a redirect location
					redirect = trimspace(redirect_args[1]);
				}
			}
		}
</pre>
<p>The shell implements 3 built in commands <strong>exit, cd,</strong> and <strong>pwd</strong>. If the <strong>exit</strong> command is found anywhere in a line containing multiple commands, the shell child process immediately exits and execution of the commands following the current one are not carried out. If the <strong>cd</strong> command is executed without any parameters, the shell switches to the user&#8217;s home directory, detected with the <strong>getenv(&#8220;HOME&#8221;)</strong> system call, much like <strong>cd ~</strong> would do in UNIX. If a path is specified, the current directory is changed to it using the <strong>chdir</strong> system call, unless the path does not exist, in which case an error is displayed. The <strong>pwd</strong> command utilizes the <strong>getcwd</strong> system call to get the current working directory and displays it on the screen.</p>
<pre class="brush: cpp; title: ; notranslate">
		/**
		 * BUILT IN COMMANDS
		 **/

		// EXIT
		if(argv_parent[i] != NULL &amp;&amp; strcmp(trimspace(argv_parent[i]), &quot;exit&quot;) == 0) exit(0);

		// PWD
		else if(argv_parent[i] != NULL &amp;&amp; strncmp(trimspace(argv_parent[i]), &quot;pwd&quot;, 3) == 0) {
			if(strcmp(trimspace(argv_parent[i]), &quot;pwd&quot;) == 0) {
			char directory[MAX_ARGS];
				getcwd(directory, MAX_ARGS);
				strcat(directory, &quot;\n&quot;);
				write(STDOUT_FILENO, directory, strlen(directory));
			}
			else {
				write(STDERR_FILENO, error_message, strlen(error_message));
			}
		}

		// CD
		else if(argv_parent[i] != NULL &amp;&amp; strncmp(trimspace(argv_parent[i]), &quot;cd&quot;, 2) == 0) {
			if(strlen(argv_parent[i]) &gt; 3) {
				// Split the string @ char 3 &amp; trim white spaces
				char *directory = (char*) malloc(strlen(argv_parent[i])-2);
				strncpy(directory, trimspace(argv_parent[i])+2, strlen(argv_parent[i]));
				directory = trimspace(directory);
				if(chdir(directory) == -1) {
					write(STDERR_FILENO, error_message, strlen(error_message));
				}
			}
			else {
				chdir(getenv(&quot;HOME&quot;));
			}
		}
</pre>
<p>All other commands are handled by the <strong>execvp</strong> system call. Since the output of any of these commands can be redirected, we must check to see if the redirection character has been detected. If it has, then we know that we need to get two arguments rather than 1 from the array of commands. Each command is then executed as a child process using the <strong>fork</strong> system call. For the piping commands, the output is redirected to the specified file using the <strong>dup2</strong> system call. For the sorted redirect, a pipe must be created so that the output of the command is fed into the input of the sort command. The output of the sort is then sent to the external file specified.</p>
<pre class="brush: cpp; title: ; notranslate">
		/**
		 * SYSTEM COMMANDS
		 **/
		else {
			// Check if this is an empty command, if it is do nothing
			if(argv_parent[i] != NULL &amp;&amp; strcmp(trimspace(argv_parent[i]), &quot;&quot;) != 0) {

				// Sorted redirect variables
				int fd[2];
				int secondChild_pid = -1; // Neg means it failed

				if(redirect != NULL &amp;&amp; strlen(redirect) &gt; 0 &amp;&amp; strstr(redirect, &quot; &quot;) != NULL) {
					// There must be two output files separated by space
					write(STDERR_FILENO, error_message, strlen(error_message));
					exit(0);
				}

				if(sortredirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) &gt; 0)
					pipe(fd);

				child_pid = fork();
				if(child_pid == 0) {
					char *argv[MAX_ARGS];
					int more_args = 1;
					int argv_index = 0;

					if(redirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) &gt; 0) {
						int file = open(redirect, O_CREAT | O_WRONLY, PERMS);
						if(file == -1) {
							// File not found
							write(STDERR_FILENO, error_message, strlen(error_message));
							exit(1);
						}
						dup2(file, 1);
					}
					else if(redirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) == 0) {
						write(STDERR_FILENO, error_message, strlen(error_message));
						exit(1);
					}
					else if(sortredirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) &gt; 0) {
						close(fd[0]);
						dup2(fd[1], STDOUT_FILENO);
					}
					else if(sortredirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) == 0) {
						write(STDERR_FILENO, error_message, strlen(error_message));
						exit(1);
					}

					// Determine the command arguments
					argv[argv_index++] = strtok(argv_parent[i], &quot; &quot;);
					while(more_args) {
						argv[argv_index++] = strtok(NULL, &quot; &quot;);
						if(argv[argv_index - 1] == NULL) more_args = 0;
					}
					if(execvp(argv[0], argv)) {
						// This executes if there's an error
						write(STDERR_FILENO, error_message, strlen(error_message));
						exit(0);
					}
				}
				else if(child_pid &lt; 0) {
					fprintf(stderr, &quot;Fork Failed&quot;);
					exit(1);
				}
				else {
					// Code executed by parent
					if(sortredirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) &gt; 0) {
						secondChild_pid = fork();
						if(secondChild_pid == 0) {
						// Child code
							close(fd[1]);
							dup2(fd[0], STDIN_FILENO);
							int file = open(redirect, O_CREAT | O_WRONLY, PERMS);

							if(file == -1) {
								// File not found
								write(STDERR_FILENO, error_message, strlen(error_message));
								exit(1);
							}
							else
								dup2(file, STDOUT_FILENO);

							char *sortarg[2] = {&quot;sort&quot;, NULL};

							// SORT
							execvp(sortarg[0], sortarg);
							write(STDERR_FILENO, error_message, strlen(error_message));
							exit(0);
						}
						else if(child_pid &lt; 0) {
							fprintf(stderr, &quot;Fork Failed&quot;);
							exit(1);
						}
					}
					close(fd[1]);
					if(sortredirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) &gt; 0)
						close(fd[0]);
					waitpid(child_pid, NULL, 0);
					if(sortredirraw != NULL &amp;&amp; redirect != NULL &amp;&amp; strlen(redirect) &gt; 0)
						waitpid(secondChild_pid, NULL, 0);
				}
			}
		}
	}
}
</pre>
<p><b>main</b> function:<br />
The main function determines if the application will run in shell mode, or batch mode. In batch mode it takes the line inputs from a file, while shell mode loops the prompt until the exit command is entered. If more than one input file are specified or the input file is not found, an error is displayed.</p>
<pre class="brush: cpp; title: ; notranslate">
int main (int argc, char *argv[]) {
	char commands[MAX_ARGS];
	char error_message[30] = &quot;An error has occurred\n&quot;;
	char cmdline[8] = &quot;537sh% &quot;;

	if(argc == 1) {
		while(strcmp(trimspace(commands), &quot;exit&quot;) != 0) {
			// STDIN
			write(STDOUT_FILENO, cmdline, strlen(cmdline));
			fgets(commands, MAX_ARGS, stdin);
			if(strchr(commands, '\n') ==  NULL) {
				// Output an error since the line was truncated
				write(STDERR_FILENO, error_message, strlen(error_message));
			}
			else {
				// Execute the command if the line is good
				executecmd(commands);
			}
		}
	}
	else if(argc == 2){
		// Batch input
		FILE *input = fopen(argv[1], &quot;r&quot;);
		if(input != NULL) {
			while(fgets(commands, MAX_ARGS, input) != NULL) {
				if(strchr(commands, '\n') == NULL)
					strcat(commands, &quot;\n&quot;);
				write(STDOUT_FILENO, commands, strlen(commands));
				executecmd(commands);
			}
		}
		else {
			write(STDERR_FILENO, error_message, strlen(error_message));
			exit(1);
		}
	}
	else {
		write(STDERR_FILENO, error_message, strlen(error_message));
		exit(1);
	}

	return 0;

}
</pre>
<p><!--adsensestart--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2012/01/21/writing-a-nix-shell-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Register File using Behavioral Verilog</title>
		<link>http://www.hdelossantos.com/2010/10/18/creating-a-register-file-using-behavioral-verilog/</link>
		<comments>http://www.hdelossantos.com/2010/10/18/creating-a-register-file-using-behavioral-verilog/#comments</comments>
		<pubDate>Mon, 18 Oct 2010 17:58:56 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Sample Work]]></category>
		<category><![CDATA[behavioral verilog]]></category>
		<category><![CDATA[hardware description language]]></category>
		<category><![CDATA[hdl]]></category>
		<category><![CDATA[register]]></category>
		<category><![CDATA[register file]]></category>
		<category><![CDATA[Verilog]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=701</guid>
		<description><![CDATA[Behavioral Verilog is the most abstract style of Verilog code. The code looks very similar to C, but one has to remember that in hardware operations occur in parallel, and everything is running at once. This sample register file will be a 16 entries by 8-bits per entry. It will have 2 synchronous write ports, [...]]]></description>
			<content:encoded><![CDATA[<p>Behavioral Verilog is the most abstract style of Verilog code. The code looks very similar to C, but one has to remember that in hardware operations occur in parallel, and everything is running at once. </p>
<p>This sample register file will be a 16 entries by 8-bits per entry. It will have 2 synchronous write ports, and an asynchronous read port as well as an active low asynchronous reset.<br />
<span id="more-701"></span><br />
We begin with our module header, parameters, and i/o declarations.</p>
<pre class="brush: verilog; title: ; notranslate">
module register_file(data_out, clk, wr_en_1, wr_en_2, rst, data_in_1, data_in_2,	wr_addr_1, wr_addr_2, rd_addr);

	parameter ENTRIES = 16;
	parameter REG_OFFSET = 8;
	integer i;

	input clk, wr_en_1, wr_en_2, rst;
	input [7:0] data_in_1, data_in_2;
	input [2:0] wr_addr_1, wr_addr_2;
	input [3:0] rd_addr;
	output reg [7:0] data_out;

	reg [7:0] registers [ENTRIES - 1:0];
</pre>
<p>By using parameters we can easily create register files of different sizes by passing new parameter values during instantiation. This can be done as such:</p>
<pre class="brush: verilog; title: ; notranslate">
register_file #(16, 32) reg_file(data_out, clk, wr_en_1, wr_en_2, rst, data_in_1, data_in_2,	wr_addr_1, wr_addr_2, rd_addr);
</pre>
<p>This will instantiate the same module with 16 32-bit entries.</p>
<p>Inside our module in an always block we declare that we want it to execute only in case of a clock&#8217;s positive edge, or a reset&#8217;s negative edge. Since the rest is active low, it will change states from 1->0 (negative edge).</p>
<pre class="brush: verilog; title: ; notranslate">
always @(posedge clk, negedge rst) begin
</pre>
<p>We then take care of our two write ports and reset. If reset is equal to 0, then we need to reset all of the values in the register file. Otherwise if wr_en_1 is 1, we want to write to write port 1, else we want to write to write port 2.</p>
<pre class="brush: verilog; title: ; notranslate">
always @(posedge clk, negedge rst) begin
		if(rst == 1'b0) begin
			for(i = 0; i &lt; ENTRIES; i = i + 1) begin
				registers[i] &lt;= 7'b0;
			end
		end

		else if(wr_en_1)
			registers[wr_addr_1] &lt;= data_in_1;
		else
			registers[REG_OFFSET + wr_addr_2] &lt;= data_in_2;
end
</pre>
<p>That take care of the two synchronous write ports. Since hardware operations occur in parallel, we can have multiple always blocs which will all execute at the same time. For the write port we simply want the always block to be triggered every time the read address (<b>read_addr</b>) changes.</p>
<pre class="brush: verilog; title: ; notranslate">
always @(rd_addr) begin
		data_out = registers[rd_addr];
end
</pre>
<p>And this is the complete code for the register file:<br />
<b>register_file.v</b>:</p>
<pre class="brush: verilog; title: ; notranslate">
module register_file(data_out, clk, wr_en_1, wr_en_2, rst, data_in_1, data_in_2,	wr_addr_1, wr_addr_2, rd_addr);

	parameter ENTRIES = 16;
	parameter REG_OFFSET = 8;
	integer i;

	input clk, wr_en_1, wr_en_2, rst;
	input [7:0] data_in_1, data_in_2;
	input [2:0] wr_addr_1, wr_addr_2;
	input [3:0] rd_addr;
	output reg [7:0] data_out;

	reg [7:0] registers [ENTRIES - 1:0];

	always @(posedge clk, negedge rst) begin
		if(rst == 1'b0) begin
			for(i = 0; i &lt; ENTRIES; i = i + 1) begin
				registers[i] &lt;= 7'b0;
			end
		end

		else if(wr_en_1)
			registers[wr_addr_1] &lt;= data_in_1;
		else
			registers[REG_OFFSET + wr_addr_2] &lt;= data_in_2;
	end

	always @(rd_addr) begin
		data_out = registers[rd_addr];
	end

endmodule
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2010/10/18/creating-a-register-file-using-behavioral-verilog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mean Median and Mode in C++</title>
		<link>http://www.hdelossantos.com/2010/10/16/mean-median-and-mode-in-c/</link>
		<comments>http://www.hdelossantos.com/2010/10/16/mean-median-and-mode-in-c/#comments</comments>
		<pubDate>Sat, 16 Oct 2010 18:01:28 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[mean]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[mode]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=688</guid>
		<description><![CDATA[Yesterday I had to complete a programming exercise as part of a research internship I will be starting Nov. 2nd. I had to create a simple C++ program which would take the mean, median, and mode of a set of numbers of unknown length. I was free to implement it any which way, with the [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I had to complete a programming exercise as part of a research internship I will be starting Nov. 2nd. I had to create a simple C++ program which would take the mean, median, and mode of a set of numbers of unknown length. I was free to implement it any which way, with the exception of using arithmetic libraries to do my mean, median, and mode computations.<br />
<span id="more-688"></span><br />
I chose to retrieve data from a file into a Vector of integers. The vector is then passed to the 3 functions to perform their corresponding operation. The result is returned and printed.</p>
<p>The <b>mode</b> function sorts the vector and iterates through it keeping a count of how many times the current value appears. Since the array is in sorted order, we know that if the next value is greater than the current, then we must be done counting the current, so it can be added to a temporary vector. If a new value is found, which has a greater count than the current highest, then the vector is cleared and the new value is added. If the new value has a count equal to that of the current high count, it is added to the temporary vector. The temporary vector is returned at the end.<br />
</p>
<h4>Function Descriptions: </h4>
<p>The <b>median</b> function check to see if the vector has an even number of items. If it does, then the median is computed as the average of the two medians of the vector in sorted order. Otherwise, the median is the result of the middle value. The return type for this function is float because of the need to represent decimals in cases when the average must be taken.</p>
<p>The <b>mean</b> function iterates through the vector taking the sum of all the values, then divides them by the total number of items in the vector. The return type is a double for large numbers which require greater precision than a float can provide.</p>
<p>Header File:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;iterator&gt;
#include &lt;algorithm&gt;
#include &lt;fstream&gt;

using namespace std;

template &lt;typename T&gt; vector&lt;int&gt; mode(vector&lt;T&gt; &amp;data);
template &lt;typename T&gt; float median(vector&lt;T&gt; &amp;data);
template &lt;typename T&gt; double mean(vector&lt;T&gt; &amp;data);
</pre>
<p>Main:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;mean_median_mode.h&quot;

int main(int argc, char *argv[]) {
	// Function declaration

	vector&lt;int&gt; data;

	// Load a small set of variables into the vector

	int input_int;
	ifstream infile(argv[1]);

	if(!infile) {
		if(argv[1] != NULL) {
			// There was an error opening the file
			cout &lt;&lt; &quot;There was an error opening &quot;
				&lt;&lt; argv[1]
				&lt;&lt; &quot; for reading.&quot;
				&lt;&lt; endl;
		}
		else {
			cout &lt;&lt; &quot;Syntax error. mean_median_mode &lt;input file name&gt;&quot; &lt;&lt; endl;
		}

	}

	else {
		while (infile &gt;&gt; input_int) {
			data.push_back(input_int);
		}

		sort(data.begin(), data.end());
		cout &lt;&lt; &quot;Data Set: &quot;;
		int j;
		for (j = 0; j &lt; data.size(); j++) {
			printf(&quot;%i &quot;, data[j]);
		}
		cout &lt;&lt; endl;

		printf(&quot;Mean: %f Median: %f, Mode: &quot;, mean(data), median(data));
		vector&lt;int&gt; tmp = mode(data);
		int i;

		for(i = 0; i &lt; tmp.size(); i++) {
			printf(&quot;%i &quot;, tmp[i]);
		}
		printf(&quot;\n&quot;);
	}

	return 0;
}

template &lt;typename T&gt; vector&lt;int&gt; mode(vector&lt;T&gt; &amp;data) {
	vector&lt;int&gt; tmp_vector;

	if(data.size() &gt; 0) {
		sort(data.begin(), data.end());
		vector&lt;int&gt;::iterator i;
		i = data.begin();

		int highest_mode = 0;
		int highest_mode_count = 0;
		int current_mode = 0;
		int current_count = 0;

		// Iterate through the vector
		while(i != data.end()) {
			int tmp = *i;

			if(current_count == 0) {
				current_mode = tmp;
			}

			if(tmp == current_mode) {
				current_count++;
			}
			else if(tmp &gt; current_mode) {

				// Check if the current mode is greater than the highest
				if(current_count &gt; highest_mode_count) {
					// Make the current mode the highest
					highest_mode = current_mode;
					highest_mode_count = current_count;

					// Clear the vector
					tmp_vector.clear();

					// Add the highest value to the vector
					tmp_vector.push_back(highest_mode);

					// Set current to tmp
					current_mode = tmp;
					current_count = 1;
				}

				// In case multiple modes
				else if(current_count == highest_mode_count) {
					// Set the highest mode to current
					highest_mode = current_mode;
					highest_mode_count = current_count;

					// Add the current mode to the vector
					tmp_vector.push_back(current_mode);

					current_mode = tmp;
					current_count = 1;
				}

				else {
					// Set tmp to current
					current_mode = tmp;
					current_count = 1;
				}
			}
			else {
				// Shouldn't need to do anything if tmp &lt; current_mode
			}

			i++;
		}
	}

	return tmp_vector;
}

template &lt;typename T&gt; float median(vector&lt;T&gt; &amp;data) {
	if(data.size() &gt; 0) {
		// Sort the data
		sort(data.begin(), data.end());

		// Handle the even cases
		if((data.size() % 2) == 0) {
			// To get the median value sum the 2 medians and get the average
			float sum = 0;

			sum += data[data.size()/2];
			sum += data[(data.size()/2) - 1];

			return (sum/2);
		}

		// Handle the odd cases
		else {
			return data[data.size()/2];
		}
	}

	return 0;
}

template &lt;typename T&gt; double mean(vector&lt;T&gt; &amp;data) {
	if(data.size() &gt; 0) {
		vector&lt;int&gt;::iterator i;
		double sum = 0;

		// Iterate through all of the elements in the vector and sum them
		for(i = data.begin(); i != data.end(); i++) {
			sum += *i;
		}

		return sum/data.size();
	}

	return 0;
}
</pre>
<p>Makefile:</p>
<pre class="brush: cpp; title: ; notranslate">
all: mean_median_mode

mean_median_mode: mean_median_mode.h mean_median_mode.cpp
	g++ -o mean_median_mode mean_median_mode.cpp

clean:
	rm mean_median_mode
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2010/10/16/mean-median-and-mode-in-c/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Verilog SyntaxHighlighter Brush</title>
		<link>http://www.hdelossantos.com/2010/05/20/verilog-syntaxhighlighter-brush/</link>
		<comments>http://www.hdelossantos.com/2010/05/20/verilog-syntaxhighlighter-brush/#comments</comments>
		<pubDate>Fri, 21 May 2010 00:40:27 +0000</pubDate>
		<dc:creator>Hanly</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[art]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[hanly de los santos]]></category>
		<category><![CDATA[hdelossantos]]></category>
		<category><![CDATA[hdelossantos.com]]></category>
		<category><![CDATA[highlighter]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[plug-in]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[syntaxhighlighter]]></category>
		<category><![CDATA[Verilog]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://www.hdelossantos.com/?p=570</guid>
		<description><![CDATA[I was trying to add some sample Verilog code on my website, but the code syntax highlighter I use did not have a brush. I made my own Verilog brush for Alex Gorbatchev&#8217;s SyntaxHighlighter. Feel free to modify and improve the code. The only thing that I ask is that you share the modifications. You [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to add some sample Verilog code on my website, but the code syntax highlighter I use did not have a brush. I made my own Verilog brush for Alex Gorbatchev&#8217;s<a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter"> SyntaxHighlighter</a>. Feel free to modify and improve the code. The only thing that I ask is that you share the modifications.<br />
<span id="more-570"></span></p>
<pre class="brush: jscript; title: ; notranslate">
/**
 * SyntaxHighlighter Verilog Brush
 * http://hdelossantos.com/
 *
 * SyntaxHighlighter is donationware. If you are using it, please donate.
 * http://alexgorbatchev.com/wiki/SyntaxHighlighter:Donate
 *
 * @version
 * 1.0.0 (May 20, 2010)
 *
 * @copyright
 * Copyright (C) 2010 Hanly De Los Santos.
 *
 * @license
 * This file is a SyntaxHighlighter brush and is licensed under
 * the same license as SyntaxHighlighter.
 *
 * SyntaxHighlighter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SyntaxHighlighter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SyntaxHighlighter.  If not, see &lt;http://www.gnu.org/copyleft/lesser.html&gt;.
 */
SyntaxHighlighter.brushes.Verilog = function() {
	var keywords = 'always end ifnone or rpmos tranif1 and endcase ' +
			  'initial output rtran tri assign endmodule inout ' +
			  'parameter rtranif0 tri0 begin endfunction input ' +
			  'pmos rtranif1 tri1 buf endprimitive integer ' +
			  'posedge scalared triand bufif0 endspecify join ' +
			  'primitive small trior bufif1 endtable large pull0 ' +
			  'specify trireg case endtask macromodule pull1 ' +
			  'specparam vectored casex event medium pullup ' +
			  'strong0 wait casez for module pulldown strong1 ' +
			  'wand cmos force nand rcmos supply0 weak0 deassign ' +
			  'forever negedge real supply1 weak1 default for ' +
			  'nmos realtime table while defparam function nor ' +
			  'reg task wire disable highz0 not release time wor ' +
			  'edge highz1 notif0 repeat tran xnor else if ' +
			  'notif1 rnmos tranif0 xor';
	var sysTasks = '$display $monitor $dumpall $dumpfile $dumpflush ' +
			  '$dumplimit $dumpoff $dumpon $dumpvars $fclose ' +
			  '$fdisplay $fopen $finish $fmonitor $fstrobe ' +
			  '$fwrite $fgetc $ungetc $fgets $fscanf $fread ' +
			  '$ftell $fseek $frewind $ferror $fflush $feof ' +
			  '$random $readmemb $readmemh $readmemx $signed ' +
			  '$stime $stop $strobe $time $unsigned $write';
	var macros = 'default-net define celldefine default_nettype ' +
			  'else elsif endcelldefine endif ifdef ifndef ' +
			  'include line nounconnected_drive resetall ' +
			  'timescale unconnected_drive undef';

	this.regexList = [
		{ regex: SyntaxHighlighter.regexLib.singleLineCComments,	css: 'comments' },
		{ regex: /\/\*([^\*][\s\S]*)?\*\//gm,						css: 'comments' },
		{ regex: /\/\*(?!\*\/)\*[\s\S]*?\*\//gm,					css: 'preprocessor' },
		{ regex: SyntaxHighlighter.regexLib.doubleQuotedString,		css: 'string' },
		{ regex: SyntaxHighlighter.regexLib.singleQuotedString,		css: 'string' },
		{ regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi,			css: 'value' },
		{ regex: /(?!\@interface\b)\@[\$\w]+\b/g,			css: 'color1' },
		{ regex: /\@interface\b/g,					css: 'color2' },
		{ regex: new RegExp(this.getKeywords(keywords), 'gm'),		css: 'keyword' },
		{ regex: new RegExp(this.getKeywords(macros), 'gm'),		css: 'keyword' },
		{ regex: new RegExp(this.getKeywords(sysTasks), 'gm'),		css: 'keyword' }
];

};

SyntaxHighlighter.brushes.Verilog.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Verilog.aliases = ['verilog', 'v'];
</pre>
<p>You can download the WordPress plugin below. You must have the SyntaxHighlighter plugin installed and active.</p>
<p>[ad#Google Adsense Text Ad Post]<br />
<a href="/school_content/sample_code/syntaxhighlighter-brush-verilog.zip"><img src="/images/download_now.png" alt="" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hdelossantos.com/2010/05/20/verilog-syntaxhighlighter-brush/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 1.340 seconds -->

