Warning: include(/home/content/g/a/l/galassa/html/jQuery.php) [function.include]: failed to open stream: No such file or directory in /home/content/39/5543739/html/code_samples/index.php on line 72

Warning: include() [function.include]: Failed opening '/home/content/g/a/l/galassa/html/jQuery.php' for inclusion (include_path='.:/usr/local/php5_3/lib/php') in /home/content/39/5543739/html/code_samples/index.php on line 72

Warning: include(/home/content/g/a/l/galassa/html/googleAnalytics.php) [function.include]: failed to open stream: No such file or directory in /home/content/39/5543739/html/code_samples/index.php on line 128

Warning: include() [function.include]: Failed opening '/home/content/g/a/l/galassa/html/googleAnalytics.php' for inclusion (include_path='.:/usr/local/php5_3/lib/php') in /home/content/39/5543739/html/code_samples/index.php on line 128

Code Samples — by Scott Galas

Matlab script — Daylight_Temp_BuffaloNY.m show code


% Filename: Daylight_Temp_BuffaloNY.m
% - load temperature averages and daylight data for Buffalo, NY.
% - perform a Least-Squares fit and plot temp, daylight and
%   rates-of-change over a 12-month period (calendar year).

close all; clear all;



%Open/Load Data From File:
%=========================================================================%
%~~~~~~~~~~~~~~ Open Files ~~~~~~~~~~~~~~%
fdir = strcat(pwd, '\', 'Data', '\');
%~~~~~~~~~~~~~~~~~~~~~%
fname = 'Daylight-Duration-2009_Buffalo-NY.txt';
fname_M01 = 'Weather-Averages_January.tex';
fname_M02 = 'Weather-Averages_February.tex';
fname_M03 = 'Weather-Averages_March.tex';
fname_M04 = 'Weather-Averages_April.tex';
fname_M05 = 'Weather-Averages_May.tex';
fname_M06 = 'Weather-Averages_June.tex';
fname_M07 = 'Weather-Averages_July.tex';
fname_M08 = 'Weather-Averages_August.tex';
fname_M09 = 'Weather-Averages_September.tex';
fname_M10 = 'Weather-Averages_October.tex';
fname_M11 = 'Weather-Averages_November.tex';
fname_M12 = 'Weather-Averages_December.tex';
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%

% Retrieve Daylight data from file:
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
file_path = strcat(fdir, fname);
fid = fopen(file_path, 'r');
C = textscan(fid, '%d8 %5s %5s %5s %5s %5s %5s %5s %5s %5s %5s %5s %5s',...
    'headerlines', 9);
D = cell2struct(C, {'Day','M1','M2','M3','M4','M5','M6',...
                          'M7','M8','M9','M10','M11','M12'}, 2);
fclose(fid);
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%

% Retrieve Monthly Avg. Temp data:
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
for ii = 1:12
    fname = strcat('fname_M', num2str(ii,'%02u'));
    file_path = strcat(fdir, eval(fname));
    fid = fopen(file_path, 'r');
    Mdata_cell = textscan(fid, '%2s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s', 'headerlines', 1);
    Mdata = cell2struct(Mdata_cell, {'Day', 'garb1', 'garb2', 'garb3', 'garb4',...
                                     'AvgHigh', 'garb5', 'garb6', 'garb7',...
                                     'garb8', 'garb9', 'garb10'}, 2);
    Temp_AvgHighTemps = zeros(1,size(Mdata.AvgHigh,1));
    for jj = 1:size(Mdata.AvgHigh,1)
        Temp_AvgHighTemps(jj) = str2num(Mdata.AvgHigh{jj}(1:end-2));
    end
    if ii == 1
        AvgHighTemps = Temp_AvgHighTemps;
    else
        AvgHighTemps = [AvgHighTemps, Temp_AvgHighTemps];
    end
    fclose(fid);
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%=========================================================================%



% Organize data into hrs. daylight by month:
%=========================================================================%
Dat_hrs = zeros(31,12);
for jj = 1:12
    field_name = strcat('M',num2str(jj));
for ii = 1:31
    if (length(D.(field_name){ii}) > 4)
        Dat_hrs(ii,jj)  = str2double(D.(field_name){ii}(1:2)) + ...
                   (1/60)*str2double(D.(field_name){ii}(4:5));
    else
        Dat_hrs(ii,jj) = 0;
    end
end
end
%=========================================================================%



% Format data:
%=========================================================================%
% Reshape data into row-vector:
Dat_vect = reshape(Dat_hrs, 1, size(Dat_hrs,1)*size(Dat_hrs,2));
Dat_vect = Dat_vect(find(Dat_vect));

% Compute Daylight Rate-of-change:
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
Rate_vect = zeros(size(Dat_vect));
for ii = 2:length(Dat_vect)-1
    Rate_vect(ii) = (Dat_vect(ii+1) - Dat_vect(ii-1))/48;
end
Rate_vect(1) = (Dat_vect(2) - Dat_vect(365))/48;
Rate_vect(365) = (Dat_vect(1) - Dat_vect(364))/48;
Rate_vect = Rate_vect * (60*24);
% Smooth:
Rate_vect = smooth(Rate_vect);
Rate_vect = smooth(Rate_vect, 7);
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%

% Define x-axes:
for ii = 1:length(Dat_vect)
    X(ii) = ii;
end


%~~~~~~~~~~ Least-Squares Regression ~~~~~~~~~~%
% Fit: f(t) = A0 + A1*cos(w0*t)   + A2*sin(w0*t)
%                + A3*cos(2*w0*t) + A4*sin(2*w0*t) + ...
%
% Solving problem: Y(t) = Z(t)*A
%           where: Y(t) = observed values,
%                  Z(t) = basis fcns., A = coeffs.
%
% Thus:    Z*A = Y
%       Z'*Z*A = Z'*Y
%            A = inv(Z'*Z)*Z'*Y
%
% Then: f(t) = Z(t)*A
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
t = X'; % time [days]
w0 = (2*pi)/365; % fundamental frequency
Z = [ones(365,1), cos(1*w0*t), sin(1*w0*t),...
                  cos(2*w0*t), sin(2*w0*t),...
                  cos(3*w0*t), sin(3*w0*t),...
                  cos(4*w0*t), sin(4*w0*t),...
                  cos(5*w0*t), sin(5*w0*t)];
                      % size(t) = [365 x 1]
                      % size(Z) = [365 x n]
Y = Rate_vect;        % size(Y) = [365 x 1]
A = inv(Z'*Z)*Z'*Y;   % size(A) = [n x 1]
f = Z*A;              % size(f) = [365 x 1]
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%


% Least-Squares Regression for Temp data:
%----------------------------------------------%
% Fit: T_interp(t) = B0 + B1*cos(w0*t) + B2*sin(w0*t)
%
% Solving problem: Y(t) = Z(t)*B
%           where: Y(t) = observed values,
%                  Z(t) = basis fcns., B = coeffs.
%
% Thus:    Z*B = Y
%       Z'*Z*B = Z'*Y
%            B = inv(Z'*Z)*Z'*Y
%
% Then: T_interp(t) = Z(t)*B
%------------------------------------%
Z = [ones(365,1), cos(1*w0*t), sin(1*w0*t)];
Y = AvgHighTemps';
B = inv(Z'*Z)*Z'*Y;
T_interp = Z*B;
%----------------------------------------------%
%=========================================================================%



%Plot Results:
%=========================================================================%

% Plot Daylight w/ Rate-of-Change:
%-------------------------------------------------------%
f1 = figure;
[ax, h1, h2] = plotyy(X, Dat_vect, X, f);
set(h2, 'linestyle', 'none', 'marker', 'o', 'markerfacecolor', 'r',...
        'markeredgecolor', 'r', 'markersize', 4);
title('{\bf Daylight Hours and Rate of Change -- Buffalo, NY}');
set(get(ax(1), 'ylabel'), 'string', '{\bf Daylight Time} [Hrs.]');
set(ax(1), 'xlim', [0 365]);
set(get(ax(2), 'ylabel'), 'string', '{\bf Change in Daylight Time} [Min./Day]');
set(ax(2), 'xlim', [0 365]);
set(ax(2), 'ycolor', 'r'), set(ax(2), 'color', 'r'), set(ax(2), 'color', 'none');
set(ax(1), 'ytick', [8 9 10 11 12 13 14 15 16]);
set(ax(2), 'ytick', [-4 -3 -2 -1 0 1 2 3 4]);
grid on;
set(f1, 'position', [10 180 633 464]); % [left bottom width height] (from bottom left)
datetick('x', 'mmm');
datetick(ax(1), 'x', 'mmm');
datetick(ax(2), 'x', 'mmm');

% Added Text box to plot:
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
hold on;
day_of_year = today - 733773 - 3*365; % (added: -3*365 to make compliant with 2012)
today_sun = Dat_vect(day_of_year);
today_change = f(day_of_year); % formerly was: Rate_vect(day_of_year)
scatter(day_of_year, today_sun, 'markerfacecolor', 'b', 'markeredgecolor', 'k');
text(day_of_year + 7, today_sun, 'today',...
     'backgroundcolor', [1.0 0.85 0.85], 'edgecolor', 'k');
HrsSun = floor(today_sun);
MinSun = floor((today_sun - HrsSun)*60);
MinChng = floor(today_change);
SecChng = floor((today_change - MinChng)*60);
text(245, 15.32,...
    {['{\bfToday:} ', date];...
    ['{\bfDaylight:} ', num2str(HrsSun), ' Hrs. ', num2str(MinSun),  ' Min.'];...
    ['{\bfChange:}   ', num2str(MinChng),  ' Min. ', num2str(SecChng), ' Sec.']},...
    'backgroundcolor', [1.0 0.85 0.85], 'edgecolor', 'k');

% Plot Least-Squares Regression:
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
f2 = figure; hold on;
p2a = plot(X,Rate_vect, 'ro');
p2b = plot(X,f,'-k', 'linewidth', 3);
title({'{\bf Least-Squares Regression - using regression function f(t)}'; '';...
    ['{ontsize{9}f(t) = a_0 + a_1cos(w_0t) + a_2sin(w_0t) + a_3cos(2w_0t) ',...
          '+ a_4sin(2w_0t) + ... + a_9cos(5w_0t) + a_{10}sin(5w_0t)}']});
legend('Daylight Rate of Change', 'Least-Squares Fit: f(t)');
set(f2, 'position', [256 132 704 513]);
grid on;
set(f2, 'visible', 'off');
%-------------------------------------------------------%

% Compute Temp Rate-of-change:
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
TmpRate_vect = zeros(size(T_interp));
for ii = 2:length(T_interp)-1
    TmpRate_vect(ii) = (T_interp(ii+1) - T_interp(ii-1))/2;
end
TmpRate_vect(1) = (T_interp(2) - T_interp(365))/2;
TmpRate_vect(365) = (T_interp(1) - T_interp(364))/2;
% Smooth:
TmpRate_vect = smooth(TmpRate_vect);
TmpRate_vect = smooth(TmpRate_vect, 7);
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%


% Plot Avg. High temps w/ Rate-of-Change:
%-------------------------------------------------------%
AvgHighTemps = smooth(AvgHighTemps); % optionally smooth the charted temp data just before plotting
f3 = figure;
[ax, h1, h2] = plotyy(X, AvgHighTemps, X, TmpRate_vect); % OPTION #1 - use charted temp
%[ax, h1, h2] = plotyy(X, T_interp, X, TmpRate_vect); % OPTION #2 - use interpolated temp
set(h1, 'color', [0 .5 0], 'linestyle', '-', 'linewidth', 2.0);
set(h2, 'linestyle', 'none', 'marker', 'o', 'markerfacecolor', 'k',...
        'markeredgecolor', 'k', 'markersize', 2);
title('{\bf Average High Temp. and Rate of Change -- Buffalo, NY}');
set(get(ax(1), 'ylabel'), 'string', '{\bf Average High Temperature} [F]');
set(ax(1), 'xlim', [0 365],...
           'ylim', [25 85],...
           'ytick', [25 30 35 40 45 50 55 60 65 70 75 80 85],...
           'ycolor', [0 .5 0]);
set(get(ax(2), 'ylabel'), 'string', '{\bf Temp. Rate-of-Change} [degF/day]');
set(ax(2), 'xlim', [0 365]);
set(ax(2), 'ycolor', 'k'), set(ax(2), 'color', 'k'), set(ax(2), 'color', 'none');
grid on;
set(f3, 'position', [660 180 633 464]); % [left bottom width height] (from bottom left)
datetick('x', 'mmm');
datetick(ax(1), 'x', 'mmm');
datetick(ax(2), 'x', 'mmm');

% Added Text box to plot:
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
hold on;
today_sun = Dat_vect(day_of_year);
today_temp = AvgHighTemps(day_of_year); % OPTION #1 - use charted temp (must agree with above)
%today_temp = T_interp(day_of_year); % OPTION #2 - use interpolated temp (must agree with above)
today_tempchange = TmpRate_vect(day_of_year);
scatter(day_of_year, today_temp, 'markerfacecolor', [0 .5 0], 'markeredgecolor', 'k');
text(day_of_year + 7, today_temp, 'today',...
     'backgroundcolor', [0.85 0.85 1.0], 'edgecolor', 'k');
HrsSun = floor(today_sun);
MinSun = floor((today_sun - HrsSun)*60);
text(252, 80,...
    {['{\bfToday:} ', date];...
    ['{\bfAvg. High Temp.:} ', num2str(chop(today_temp,4)),  ' F'];...
    ['{\bfChange:} ', num2str(today_tempchange,3),  ' F/day']},...
    'backgroundcolor', [0.85 0.85 1.0], 'edgecolor', 'k');
%-------------------------------------------------------%
drawnow;   % flush all pending graphics objects
%=========================================================================%



% Display Data to Screen:
%=========================================================================%
Tmin  = min(AvgHighTemps);
Tmax  = max(AvgHighTemps);
Tmean = chop(mean(AvgHighTemps),3);
i_Tmin  = find(AvgHighTemps == Tmin);
i_Tmax  = find(AvgHighTemps == Tmax);
i_Tmean = find(AvgHighTemps >= Tmean);
date_min  = [datestr(i_Tmin(1), 'mmm-dd'), ' - ', datestr(i_Tmin(end), 'mmm-dd')];
date_max  = [datestr(i_Tmax(1), 'mmm-dd'), ' - ', datestr(i_Tmax(end), 'mmm-dd')];
date_mean = [datestr(i_Tmean(1), 'mmm-dd'), ' & ', datestr(i_Tmean(end), 'mmm-dd')];
disp({'                                                                       ';...
      ['Minimum Avg. High Temp. is: ', num2str(Tmin),  ' F   and occurs at ', date_min];...
      ['Maximum Avg. High Temp. is: ', num2str(Tmax),  ' F   and occurs at ', date_max];...
      ['   Mean Avg. High Temp. is: ', num2str(Tmean), ' F and occurs at ', date_mean];...
      '                                                                       '});

Tuser = 1;
while Tuser ~= 0
    Tuser = input('Select a specific temperature (F), [enter 0 to quit]: ');
    i_Tuser = find(AvgHighTemps >= Tuser);
    date_Tuser = [datestr(i_Tuser(1), 'mmm-dd'), ' & ', datestr(i_Tuser(end), 'mmm-dd')];
    Tuser_days = length(i_Tuser);
    tmp = Tuser_days/30.5;
    Tuser_months = floor(tmp) + 0.10*round(10*(tmp - floor(tmp)));
    if (Tuser ~= 0)
        disp({'                                                      ';...
            ['This temp. occurs on days ', date_Tuser];...
            ['There are ', num2str(Tuser_days), ' days (~',...
            num2str(Tuser_months), ' months) that meet or exceed this temp.'];...
            '                                                      '});
    end
end

set(f1, 'visible', 'on');
set(f3, 'visible', 'on');
%=========================================================================%

Sample output produced by Daylight_Temp_BuffaloNY.m sample output

Matlab function — findStringInFile.m show code


	function [filesMatched, filesSearched] = findStringInFile(searchString, searchDir)
	%
	% FINDSTRINGINFILE - search all m-files in a directory for a specific string.
	%     Return the files' names that contain one or more instances of the string,
	%     displaying the number of instances found in each matching file.
	%     Can also list the files that were searched. (Written by: Scott Galas)
	%
	%  ---Usage---
	%  [filesMatched, filesSearched] = findStringInFile(searchString, searchDir)
	%
	%  ---Inputs---
	%  searchString = string to search for (OPTIONAL).  If not provided, the user
	%                 will be prompted to enter a search term.
	%  searchDir = directory to search (OPTIONAL). If not provided, the current
	%              working directory will be searched.
	%
	%  ---Outputs---
	%  filesMatched = list of files containing "searchString".
	%  filesSearched = list of all the files searched.


	% set default values for the input arguments:
	%-------------------------------------------%
	if (nargin < 2)
		searchDir = './';
	end
	if (nargin < 1)
		searchString = input('Type the string you want to find in m-files: ', 's');
	end
	%-------------------------------------------%


	% validate input arguments:
	%---------------------------------------------------%
	% replace all occurrences of "\" in searchDir with "/" for consistency
	searchDir = strrep(searchDir, '\', '/');

	% check if searchDir ends with a slash; if not, provide one
	i_slash = strfind(searchDir, '/');
	if (~isempty(i_slash) && (i_slash(end) ~= length(searchDir)))
		searchDir = [searchDir, '/'];
	end

	% verify that searchDir is a real directory; if not, indicate error and abort
	if (~isdir(searchDir))
		error(['Unable to verify "', searchDir, '" as a real directory.']);
	end
	%---------------------------------------------------%


	% record number of "hits" of "searchString" found in each file:
	%---------------------------------------------------------------%
	mfiles = ls([searchDir, '*.m']); % m-by-n character array of filenames
	hits = zeros(size(mfiles,1),1);  % m-by-1 array of "hits" for each file

	for ii = 1:size(mfiles,1)
		
		fname = mfiles(ii,:); 
		fname = fname(~isspace(fname)); % current file name
		fpath = [searchDir, fname]; % current file path
		contents = fileread(fpath); % current file's contents
		indx = strfind(contents, searchString); % indices of all matches to "searchString"
		
		% add match counts to "hits" (if not searching THIS file)
		if (~isempty(indx) && isempty(strfind(fpath, 'findStringInFile.m')))
			hits(ii) = hits(ii) + length(indx);
		end
		
	end

	total_hits = sum(hits);
	%---------------------------------------------------------------%


	% display results to user:
	%------------------------------------------%
	disp(' ');
	disp(['Found ', num2str(total_hits), ' occurrences of "', searchString,...
		'" in directory "', searchDir, '".']);
	if (total_hits > 0)
		for ii = 1:size(mfiles,1)
			if (hits(ii) > 0)
				disp([' - ', strtrim(mfiles(ii,:)), ' has ',...
					num2str(hits(ii)), ' occurrences.']);
			end
		end
	end
	disp(' ');
	%------------------------------------------%


	% prepare output arguments:
	%------------------------------%
	filesSearched = mfiles;
	filesMatched = mfiles(find(hits>0),:);
	if (isempty(filesMatched)), filesMatched = []; end
	%------------------------------%


	end % End: findStringInFile()

Matlab function — backup_directory.m show code

	
	function backup_directory()
	%
	% BACKUP_DIRECTORY - copy the current directory's m-files into a zipped
	%   file in the parent directory (named after the current directory followed
	%   by an underscore and today's date).  If a zipped file already exists
	%   with the same name, a suffix of "a", "b", "c", etc. will be appended
	%   to the new file. **For use on Windows systems** (Written by: Scott Galas)
	

	% Establish a filename for new zip-file:
	%=========================================================================%
	% Date info.:
	tmp = datestr(now,2);
	todays_date = strcat(tmp(1:2),tmp(4:5),tmp(7:8));

	% Current Directory name:
	curr_dir = pwd;
	i_slash = find(curr_dir == '\');
	i_slash = i_slash(end);
	curr_dir = curr_dir(i_slash+1:end);

	% Define zip-file name:
	zipfile_name = strcat('..\', curr_dir, '_', todays_date, '.zip');
	%=========================================================================%


	% Create/Save zip-file:
	%=========================================================================%
	test = 0;
	count = 0;
	file_ext = 'abcdefghijklmnopqrstuvwxyz';

	while ~(test)
		
		if count == 0
			if exist(zipfile_name, 'file') == 2
				count = count+1;
			else
				zip(zipfile_name, '*.m');
				disp(['***** Backing up m-files to: ', zipfile_name,' *****']);
				test = 1;
			end
		else 
			zipfile_name = strcat('..\', curr_dir, '_', todays_date,...
								  num2str(file_ext(count)),'.zip');
			if ~(exist(zipfile_name, 'file') == 2)
				zip(zipfile_name, '*.m');
				disp(['***** Backing up m-files to: ', zipfile_name,' *****']);
				test = 1;
			else
				count = count+1;
			end
		end
		
	end

	disp('Directory is now zipped, written to new file.');

	delete *.asv; % Delete all auto-save (.asv) files in directory
	%=========================================================================%


	end % End: backup_directory()

JavaScript functions — array_functions.js show code


// This file is a collection of useful javascript functions/methods for manipulating arrays


/*
	- Add new method "multiSort" to javaScript "Array" object (used for sorting 2D arrays)
	- obtained from: http://www.webdeveloper.com/forum/archive/index.php/t-59157.html
	- modified/extended by me (to restore the original column order of the 2D array)
	- usage: 
		var testArray = [
			[1, 'nate', 'high school'],
			[3, 'dave', 'high school'],
			[2, 'seng', 'college']
		];
		testArray.multiSort(0); // sorts by 1st column
		testArray.multiSort(1); // sorts by 2nd column
		testArray.multiSort(2); // sorts by 3rd column
*/
Array.prototype.multiSort = function(index){

	var numRows = this.length;

    // loop through rows... (moving the sort-column to the front)
	for (var ii=0; ii<numRows; ii++) {
	
		// current row in the loop
		var currRow = this[ii];
	
        // remove one item from current row (at specified column "index")
		var temp = currRow.splice(index,1);
		
		// add the removed item to the front of the current row
        currRow.unshift(temp);
    }
	
	// sort the array alphabetically or numerically (if sort column contains numbers)
	var sortedArray;
	if ( isNaN(parseFloat(this[0][0])) ) {
		// array is not numeric, sort alphabetically
		sortedArray = this.sort();
	} else {
		// array is numeric, sort numerically
		sortedArray = this.sort(function(a,b){ return (parseFloat(a) - parseFloat(b)); });
	}
	
	// loop through rows... (restoring the original column order); save results in "reorderedArray"
	var reorderedArray = [];
	for (var ii=0; ii<numRows; ii++) {
	
		// current row in the loop
		var currRow = sortedArray[ii];
		
		// remove the 1st item from the current row
		var temp = currRow.shift();
		
		// add the removed item back to its original position (index)
		currRow.splice(index, 0, temp);
		
		reorderedArray[ii] = currRow;
	}
	
    return reorderedArray;
	
} // End: Array.prototype.multiSort()


// function to log a 2D array to console
function Log2DArrayToConsole(theArray) {

	var arrayText = "";
	
	for (var ii=0; ii<theArray.length; ii++) { // row loop
		
		for (var jj=0; jj<theArray[0].length; jj++) { // column loop
		
			if (jj == 0) {
				arrayText += "[" + theArray[ii][jj] + ", ";
			} else if (jj == theArray[0].length - 1) {
				arrayText += theArray[ii][jj] + "]\n";
			} else {
				arrayText += theArray[ii][jj] + ", ";
			}
		}
	}
	
	console.log(arrayText);

} // End: Log2DArrayToConsole()


// - function to convert a text string into an array (where the string is split 
//   on a specified 'splitSeparator')
// - default 'splitSeparator' is a blank space
function string2Array(textString, splitSeparator) {

	// if no 'splitSeparator' is provided, split the string on blank space
	if (arguments.length < 2) { splitSeparator = " "; }

	// break string into an array of substrings; return the array
	return textString.split(splitSeparator); 

} // End: string2Array()


// function to return an array of the unique values of another array
function getUniqueArray(textArray) {
	
	// eliminate duplicate entries in the "textArray" array
	var textListUnique = new Array(); // array containing unique values of textArray
	textListUnique[0] = textArray[0];
	
	var addValue, currVal;
	for (var ii=0; ii<textArray.length; ii++) {
	
		addValue = true;
		currVal = textArray[ii];
		
		for (var jj=0; jj<textListUnique.length; jj++) {
			if (currVal === textListUnique[jj]) {
				addValue = false;
				break;
			}
		}
		
		if (addValue){ 
			textListUnique = textListUnique.concat(currVal); 
		}
	}
	
	return textListUnique;
	
} // End: getUniqueArray()

JavaScript function (jQuery plugin) — simpleTooltip.js show code


/* 
 * - simpleTooltip jQuery plugin
 * - Written by: Scott Galas 
 * - based on: http://www.kriesi.at/archives/create-simple-tooltips-with-css-and-jquery
 *
 * - To add a "simpleTooltip" to an element:
 * (1) identify items with tooltips - e.g. var $itemToGiveTooltip = $('.hasTooltip');
 * (2) add the desired tooltip text to the element(s)'s "title" or "alt" attribute(s).
 * (3) call $itemToGiveTooltip.simpleTooltip(); after element exists in the DOM.
 *
 * - Can alternatively call: 
 *   $itemToGiveTooltip.simpleTooltip({tooltipClass:'tooltip', textSource:'title'}); 
 *   or override these defaults.
 * - Each time simple_tooltip() is called, all the tooltips with same "tooltipClass" 
 *   on the page will be removed and rebuilt.
 */
(function($) {

// - add new function property (the name of the plugin) to the jQuery.fn object.
// - within the immediate scope of the plugin, the "this" keyword refers to the 
//   jQuery object on which the plugin was invoked.
$.fn.simpleTooltip = function(options) {
			
	// Plugin options:
	/* --------------------------------------- */
	// default options (can be overwritten)
	var defaults = {
		tooltipClass : "tooltip",
		textSource : "title"
	};
	
	// merge default and user options  
	options = $.extend(defaults, options);
	
	var tooltipClass = options.tooltipClass,
		textSource = options.textSource.toLowerCase();
	/* --------------------------------------- */
			
	// Remove any pre-existing tooltip container div(s); will rebuild below
	$("." + tooltipClass).remove();
			
	// Append tooltip <div>'s to document <body>
	/* ----------------------------------------------------------------------- */
	var textToAppend = [];		
	textToAppend[0] = "\n";
	
	var ii = 1;
	this.each(function(indx){

		var toolTipText = "", 
			targetTitle = $(this).attr("title"), 
			targetAlt = $(this).attr("alt");

		if (textSource === "title" && typeof targetTitle === "string" && 
			targetTitle.length > 0) {

			// "title" is available, use it...
			toolTipText = targetTitle;

		} else if (textSource === "alt" && typeof targetAlt === "string" && 
			targetAlt.length > 0) {

			// "alt" is available, use it...
			toolTipText = targetAlt;
			
		} else {
			toolTipText = "";
		}

		// append html string (if exists) to array, then increment array 
		// (will join() into one string during append below)
		if (toolTipText.length > 0) {
			textToAppend[ii++] = "\n<div class='" + tooltipClass + "' id='" + 
				tooltipClass + indx + "'><p>" + toolTipText + "</p></div>";
		}

	}); // End: $.each() target

	// append new tooltip container to <body> (Note that append() is only called once!)
	textToAppend[ii] = "\n\n";
	$("body").append(textToAppend.join(""));
	/* ----------------------------------------------------------------------- */
			
	// Add CSS, event handlers, etc. to tooltips
	/* ----------------------------------------------------------------------------- */
	var $newTooltips = $("." + tooltipClass);
	
	if ($newTooltips.length > 0) {
	
		// add CSS to the tooltip divs
		$newTooltips.css({
			"display":"none",
			"position":"absolute",
			"z-index":"9999",
			"left":"-9999px",
			"background-color":"#dedede",
			"width":"auto",
			"opacity":"0.80",
			"padding":"4px",
			"border":"1px solid #fff"
		}).find("p").css({
			"color":"#ffffff",
			"background-color":"#222222",
			"font-size":"13px",
			"text-align":"center",
			"width":"auto",
			"min-width":"75px",
			"max-width":"95px",
			"margin":"0",
			"padding":"4px 5px 4px 5px"
		});
		
		this.each(function(indx) {

			// (1) Declare variables (all in one statement)
			var $this = $(this),
				myTitle, $my_tooltip, $my_tooltip_p, $myParent, myParentTitle,
				border_right, // right edge of viewport 
				tooltipWidth, // width of tooltip 
				tooltipHeight, // height of tooltip 
				offset = 15, // horizontal and vertical offset of tooltip 
				left_pos, // horizontal position of left edge of tooltip 
				top_pos, // vertical position of top edge of tooltip 
				tooltipShowing = false; // boolean to indicate if tooltip is already showing

			// (2) Store a copy of title (removed and replaced below)
			myTitle = .attr("title"); // value of target's title attribute (if it exists)

			// (3) Identify the tooltip (and inner <p>) belonging to current target
			$my_tooltip = $("#" + tooltipClass + indx);
			$my_tooltip_p = $my_tooltip.find("p");
			
			// (4) get target's parent and parent title
			$myParent = $this.parents("[title]").first(); // nearest parent with "title" attribute
			myParentTitle = $myParent.attr("title"); // save parent's title for reuse

			// (5) Unbind and rebind event handlers (using "tooltipEvents" namespace)
			$this.unbind(".tooltipEvents").bind("mouseenter.tooltipEvents", function(){

				$this.attr("title", ""); // blank target's title
				$myParent.attr("title", ""); // blank parent's title
				border_right = $(window).width(); // x-coord of right edge of viewport
				tooltipWidth = $my_tooltip.width(); // tooltip's width
				tooltipHeight = $my_tooltip.height(); // tooltip's height

			}).bind("mousemove.tooltipEvents", function(kmouse){

				// compute left_pos (variable tooltip position) - prevents tooltip 
				// from leaving viewport (horizontal direction)
				if ((border_right - (2*offset)) > (tooltipWidth + kmouse.pageX)) {
					left_pos = kmouse.pageX + offset; // normal position
				} else {
					left_pos = border_right - tooltipWidth - offset; // recalculated position
				}

				// compute top_pos
				top_pos = kmouse.pageY - tooltipHeight - offset;
				
				// reposition tooltip
				$my_tooltip.css({"left":left_pos, "top":top_pos});
				
				// display tooltip if not already showing
				if (!tooltipShowing) {
					$my_tooltip.fadeIn(250, function() {
						tooltipShowing = true;
					});						
				}

			}).bind("mouseleave.tooltipEvents click.tooltipEvents", function(){

				$my_tooltip.stop(true,true).css({"display":"none"}); // hide tooltip
				tooltipShowing = false;
				$this.attr("title", myTitle); // restore target's title
				$myParent.attr("title", myParentTitle); // restore parent's title

			}); // End: binding events to this target

			// (6) Add a safety-mechanism to remove any left-over tooltip on 
			//     mouseenter/mouseleave of tooltip itself
			$my_tooltip.unbind().bind("mouseenter mouseleave", function(){ 
				$(this).css({"display":"none"});
				tooltipShowing = false;
			});

		}); // End: $.each() target
		
	}
	/* ----------------------------------------------------------------------------- */
	
	// final step: allow jQuery chaining  
	return this;		
};
	
})(jQuery);

JavaScript/jQuery function — setupClickableTable.js show code


// This function styles odd table rows BG color and sets up event handler for 
// table row "click" event (i.e. highlights row).
function setupClickableTable($table) {

    try {
        // select all the rows inside the body of table
        var $tr = $table.find('tbody').find('tr');

        // Add classes "cursorPointer" and "odd" to modify cursor and lighten color 
		// of odd numbered table rows, respectively.
        $tr.addClass('cursorPointer').filter(':odd').addClass('odd');

        // - set up event handler for selecting an item from the table (by clicking on a table row)
		// - always use click(), not toggle()
        $tr.click(function(){
		
            if (!($(this).hasClass('selected'))) {
			
                // when clicking a row that is not already "selected" do the following...
                $(this).addClass('selected'); // indicate that this row is now selected
                var $trNotThis = $tr.not(this); // define jQuery selector for all other rows
                $trNotThis.removeClass('selected'); // remove ".selected" from all other rows
                console.log("The row you clicked is now selected (class 'selected' added).");
				
            } else {
			
                // when clicking a row that is "selected" do the following...
                $(this).removeClass('selected'); // indicate that row is no longer selected
                console.log("The row you clicked is no longer selected (class 'selected' removed).");
            }
			
        }); // End: click() event handler
		
    } catch(e) {
        console.log("Error in setupClickableTable() - " + e);
    }

} // End: setupClickableTable()

JavaScript/jQuery function — convertToSortableTable.js show code


// - This function convert a normal table into a sortable table (rearranges 
//   rows to alphabetize the sorted column).
// - typically invoked in the same situations as (and thus, immediately following) function 
//   setupClickableTable(), but preferably before scrollbars are added or updated (in case 
//   table header size changes due to the addition of sorting icons).
function convertToSortableTable($table) {


// define selectors for the table
var $tbody = $table.find("tbody");


// setup table sort icons
/*---------------------------------------------------------------------------------*/
$table.find("th").each(function(indxTH){

	// add .tableSortIcon to the visible <th> elements
	if ($(this).is(":visible")) {
		
		var titleText = "Sort Table by \"" + $(this).text() + "\"";
		
		$(this).append(
			"<img class='tableSortIcon hasTooltip unsorted' src='" + webRootDirectory + 
			"/images/icons/sort-ascending-gray_16x16.png'" + 
			" width='16' height='16' title='" + titleText + "' />"
		);
	}

	// setup a 'click' event handler for each .tableSortIcon in $table
	$(this).find(".tableSortIcon").unbind("click").bind("click", function(){

		console.log("You clicked a table sort icon.");

		if ($(this).hasClass("unsorted")) {

			// in unsorted state, switch to "sort_ascending" mode
			$(this).removeClass("unsorted sort_descending").addClass("sort_ascending")
				.attr("src", webRootDirectory + "/images/icons/sort-ascending-blue_16x16.png");

			resetOtherSortIcons($(this));
			sortTable($tbody, indxTH, "ascending");

		} else if ($(this).hasClass("sort_ascending")) {

			// in "sort_ascending" mode, switch to "sort_descending" mode
			$(this).removeClass("unsorted sort_ascending").addClass("sort_descending")
				.attr("src", webRootDirectory + "/images/icons/sort-descending-blue_16x16.png");

			resetOtherSortIcons($(this));
			sortTable($tbody, indxTH, "descending");

		} else if ($(this).hasClass("sort_descending")) {

			// in "sort_descending" mode, switch to "sort_ascending" mode
			$(this).removeClass("unsorted sort_descending").addClass("sort_ascending")
				.attr("src", webRootDirectory + "/images/icons/sort-ascending-blue_16x16.png");

			resetOtherSortIcons($(this));
			sortTable($tbody, indxTH, "ascending");

		} else {

			// unable to determine state; revert to "unsorted" mode
			$(this).removeClass("sort_ascending sort_descending").addClass("unsorted")
				.attr("src", webRootDirectory + "/images/icons/sort-ascending-gray_16x16.png");

			resetOtherSortIcons($(this));
			sortTable($tbody, indxTH, "unsorted");
		}

	}); // End: 'click' event handler

}); // End: $th.each()
/*---------------------------------------------------------------------------------*/


// define subfunction for sorting table
/*-----------------------------------------------------------------------------*/
function sortTable($tableBody, thisColNum, sortMethod) {

	var unsortedColText = [], sortedColText = [], sortOrder = [];

	/* **** (1) Get the unsorted text inside the current column **** */
	$tableBody.find("tr").each(function(indexTR){

		$(this).find("td").each(function(indexTD){
			if (indexTD == thisColNum) {

				// get the text immediately inside the <td> (not in sub-elements)
				var TDtext = $(this)
						.contents()
						.filter(function(){ return this.nodeType == 3; }) // filter returns text node only (not element or comment nodes)
						.text()
						.toLowerCase();

				TDtext = trimWhiteSpace(TDtext);
				
				// append "zzz" if TDtext is "---" (forces to bottom of sorted list)
				TDtext = (TDtext == "---" || TDtext.length == 0) ? "zzz" + TDtext : TDtext;

				unsortedColText.push( new Array(TDtext, indexTR) );
			}
		}); // End: $td.each()

	});  // End: $tr.each()

	console.log("sortTable(): \nThe unsorted text (and indices) of column #" + thisColNum + " is:\n" + unsortedColText);

	/* **** (2) Sort this column's text and record the new sort order **** */
	sortedColText = unsortedColText.multiSort(0); // sort by 1st column (2nd column contains the row numbers)
	
	if (sortMethod == "ascending") {
		// sort ascending
		for (var ii=0; ii<sortedColText.length; ii++) {
			sortOrder[ii] = sortedColText[ii][1];
		} 
	} else if (sortMethod == "descending") {
		// sort descending
		for (var ii=0; ii<sortedColText.length; ii++) {
			sortOrder[ii] = sortedColText[(sortedColText.length-1) - ii][1];
		} 
	} else {
		// maintain current sort order (unsorted)
		for (var ii=0; ii<sortedColText.length; ii++) {
			sortOrder[ii] = ii;
		} 
	}

	console.log("sortTable(): \nThe sorted text (and indices) of column #" + thisColNum + " (using sortMethod = \"" + 
			sortMethod + "\") is:\n" + sortedColText + "\n\n" + "The sort order is: " + sortOrder);

	/* **** (3) Reorder the table rows by appending them to <tbody> (noting that .append() MOVES them) **** */
	for (var jj=0; jj<sortOrder.length; jj++) {

		// move row # sortOrder[jj] to the end of $tableBody
		$tableBody.find("tr").eq(sortOrder[jj]).appendTo($tableBody); 

		// adjust remaining sequence in sortOrder to account for the row just moved
		for (var kk=jj+1; kk<sortOrder.length; kk++) {
			if(sortOrder[kk] > sortOrder[jj]) {sortOrder[kk] -= 1;} 
		}
	}

	/* *** (4) Reestablish which table rows are odd *** */
	$tableBody.find("tr").removeClass("odd").filter(":odd").addClass("odd");

} // End sub-function: sortTable()
/*-----------------------------------------------------------------------------*/


// define subfunction to reset the other (inactive) sort icons
/*--------------------------------------------------------------------*/
function resetOtherSortIcons($activeIcon) {

	var $otherIcons = $table.find("th .tableSortIcon").not($activeIcon);
	
	$otherIcons.removeClass("sort_ascending sort_descending").addClass("unsorted")
		.attr("src", webRootDirectory + "/images/icons/sort-ascending-gray_16x16.png");

} // End sub-function: resetOtherSortIcons()
/*--------------------------------------------------------------------*/


} // End: convertToSortableTable()

JavaScript/jQuery function — fancyAlertBox.js show code


// This function creates a fancy alert box based on jQuery UI's dialog box 
// - the dialog box is created and removed on-the-fly
// - to apply a width without a callback function, pass null as argument #3
// - to add/remove an OK button without a width, pass null as argument #4
function fancyAlertBox(titleText, alertText, myCallbackFcn, width, addOKButton, addCancelButton) {

    // I. Handle Missing Arguments (provide defaults)
    /* --------------------------------------------------------- */
    if (arguments.length < 6) { addCancelButton = false; }
    if (arguments.length < 5) { addOKButton = true; }
    if (arguments.length < 4 || width == null) { width = 325; }
    if (arguments.length < 3 || myCallbackFcn == null) { myCallbackFcn = function(){/*do nothing*/} }
    if (arguments.length < 2) { alertText = "This is an alert/dialog box.  No specific alert was specified."; }
    if (arguments.length < 1) { titleText = "Warning"; }
    /* --------------------------------------------------------- */

    // II. Options and initialization stuff
    /* ---------------------------------------------------- */
    // set options for jQuery UI's dialog box
    var dialogOptions = {title:titleText, show:"clip", hide:"clip", modal:true, width:width};

    // check if other "#myFancyAlertDialog" boxes are in the DOM; 'close' if exists (which triggers "remove") before creating new
    $('#myFancyAlertDialog').dialog("close");

    // create <div> to use as new dialog box
    var $myDialogBox = $("<div id='myFancyAlertDialog'>" + alertText + "</div>");

    // bind to 'dialogopen' event
    $myDialogBox.bind("dialogopen", function(event, ui){

        $('#myDialogOKbutton').blur(); // remove focus from "OK" button

    });
    /* ---------------------------------------------------- */

    // III. Optional buttons section
    /* -------------------------------------------------------- */
    //  optionally create "OK" button on-the-fly and append to dialog box
    var pressedOKButton = false; // default value
    if (addOKButton) {

        $myDialogBox.append("<br />");

        $("<button id='myDialogOKbutton' class='rounded-corners'>OK</button>") // html for the new button
                .bind('click', function(){ pressedOKButton=true; $myDialogBox.dialog("close"); }) // bind 'click' event handler to button to close dialog box
                .appendTo($myDialogBox) // append the button to $myDialogBox
                .button(); // convert into a jQueryUI button()
    }

    // optionally create "Cancel" button
    var pressedCancelButton = false; // default value
    if (addCancelButton) {

        $("<button id='myDialogCancelbutton' class='rounded-corners'>Cancel</button>")
                .bind('click', function() { pressedCancelButton=true; $myDialogBox.dialog("close"); }) // bind 'click' event handler to button to close dialog box
                .appendTo($myDialogBox) // append the button to $myDialogBox
                .button(); // convert into a jQueryUI button()
    }
    /* -------------------------------------------------------- */

    //console.log("Logging fancyAlert's dialogOptions to verify:\n" + showObjectProps(dialogOptions, "dialogOptions"));

    // IV. Instantiation and 'dialog' close event
    /* --------------------------------------------------------------------- */
    // instantiate dialog box; remove element from DOM when dialog box is closed, then optionally run a callback function
    $myDialogBox.dialog(dialogOptions).bind("dialogclose", function(event, ui){

        // run callback function under the following circumstances
        var ranCallbackFcn = false;
        if (addOKButton && addCancelButton) { // if "OK" and "Cancel" buttons both exist...

            if (pressedOKButton){ myCallbackFcn(); ranCallbackFcn=true;} // run callback fcn. only if "OK" was pressed

        } else { // if either or both of the "OK"/"Cancel" buttons do not exist...

            if (!pressedCancelButton){ myCallbackFcn(); ranCallbackFcn=true;} // always run callback fcn. unless "Cancel" was pressed
        }

        // log status of callback fcn to console
        console.log("fancyAlertBox(): the 'dialogclose' event " + (ranCallbackFcn?"DID":"DID NOT") + " run callback fcn.");

        // finally, remove (delete) the dialog box
        $(this).remove();

    }); // End: 'dialogclose' event handler
    /* --------------------------------------------------------------------- */

} // End: fancyAlertBox()

PHP/MySQL script — login_validate.php show code


<?php

// - This file (login_validate.php) is a sample login-validation script
// - It relies on a few MySQL utility functions defined in: mysql_util.php
//   as well as several variables/arrays defined in: php_vars.php
// - If the login is successful, the user is redirected to page: main.php
// - If the login fails, the user is redirected to page: login_failure.php
// - If this page was loaded without completing the login form, the user
//   will be returned to: login.php


// load main vars/fcns file
require_once($_SERVER['DOCUMENT_ROOT'] . '/myproject/include/php_vars.php');


// Get form variables from the login form
$login_user = $_POST['login_user'];
$login_password = $_POST['login_password'];


// Only continue if the login form was submitted properly...
if (isset($login_user) && isset($login_password)) {

	// start new session, or continue existing session
	session_start();
	
	// turn on output buffering (preventing all output except headers)
	ob_start();
	
	/* ----------------- check credentials here... ----------------- */
	// connect to database server
	$con = connect2dbserver($db_server, $myproject_db['username'], $myproject_db['password']);
	
	// select the database we wish to use
	mysql_select_db($myproject_db['database'], $con);
	
	$hashed_password = hash('sha1', $login_password);
	
	// formulate query
	$sql = sprintf("SELECT * FROM %s WHERE username='%s' and passwd='%s'",
				mysql_real_escape_string($myproject_db['valid_users']),
				mysql_real_escape_string($login_user),
				mysql_real_escape_string($hashed_password));
	
	// submit the query
	$result = run_query($sql, $con);
	
	// count the number of rows returned
	$count = mysql_num_rows($result); 
	
	// if result matched username and password, then number of rows returned s/b exactly one
	if ($count == 1) {
	
		/* ***** login successful ***** */
		
		// set session vars.
		$_SESSION['logged_in'] = true;
		$_SESSION['username'] = $login_user;
		
		// redirect to main.php
		header('Location: http://' . $_SERVER['HTTP_HOST'] . $main_dir . '/main.php');
		
		// prevent further code execution on this page
		exit;
		
	} else {
		
		/* ***** login failed ***** */
		
		// unset session vars.
		if (isset($_SESSION['logged_in'])) { unset($_SESSION['logged_in']); }
		if (isset($_SESSION['username'])) { unset($_SESSION['username']); }
		
		// destroy the current session
		session_destroy();
		
		// redirect to login_failure.php
		header('Location: http://' . $_SERVER['HTTP_HOST'] . $main_dir . '/auth/login_failure.php');
		
		// prevent further code execution on this page
		exit;
	}
	/* ------------------------------------------------------------- */
	
	// flush output buffer (safe to do here b/c headers should have already been sent)
	ob_end_flush();
	
} else {
	
	// someone attempted to load page without submitting the form
	// redirect back to login.php
	header('Location: http://' . $_SERVER['HTTP_HOST'] . $main_dir . '/auth/login.php');
	
}

?>



Warning: include(/home/content/g/a/l/galassa/html/footer.php) [function.include]: failed to open stream: No such file or directory in /home/content/39/5543739/html/code_samples/index.php on line 377

Warning: include() [function.include]: Failed opening '/home/content/g/a/l/galassa/html/footer.php' for inclusion (include_path='.:/usr/local/php5_3/lib/php') in /home/content/39/5543739/html/code_samples/index.php on line 377