My name is Edward Tanguay. I'm an American software and web developer living and working in Berlin, Germany.


How to call an unknown function on an unknown class with unknown parameters The call_user_func_array function can help you build some pretty flexible framework code in PHP, here's the syntax to call a function on an existing object. ![]()
<?php $pm = new PresentationManager(); echo $pm->displayTest('the title', 'the footer', 5); $params = array( 'the title2', 'the footer2', 10); echo call_user_func_array(array($pm, 'displayTest'), $params); class PresentationManager { function displayTest($title, $footer, $numberOfItems = 0) { $r = ''; $r .= '<div>'.$title.'</div>'; for($index = 0; $index < $numberOfItems; $index++) { $r .= '<div>the text</div>'; } $r .= '<div>'.$footer.'</div>'; return $r; } } ?> |
How to setup JQuery intellisense in Microsoft Visual Web Developer 2010 Express If you are working on Windows, Visual Web Developer 2010 Express has very nice intellisense for Jquery, here's how.
|
Simple menu site with jQuery AJAX Simple example of using jQuery's $.get() to make a quick responding site that shows text in a display box based on menu selection. ![]() > > > Download Code > > > View Demo
<!DOCTYPE html> <html> <head> <title>JQuery AJAX Menu</title> <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script> <script type="text/javascript"> $(document).ready(function () { showText('welcome'); $('#buttonWelcome').click(function () { showText('welcome'); }); $('#buttonInfo').click(function () { showText('info'); }); $('#buttonHelp').click(function () { showText('help'); }); function showText(idCode) { $.get('content/' + idCode + '.txt', function (data) { $('#content').text(data); }); } }); </script> <style type="text/css"> button::-moz-focus-inner { border: 0; } button { background-color: beige; cursor: hand; cursor: pointer; } #content . { background-color: beige; border: 1px solid #555; height: 200px; width: 300px; margin-top: 10px; padding: 10px; } </style> </head> <body> <button id='buttonWelcome'> Welcome</button> <button id='buttonInfo'> Info</button> <button id='buttonHelp'> Help</button> <div id="content"> </div> </body> </html> |
A PHP function which returns the most frequently occuring item This function shows how you can get the most frequently occurring item out of an array using array_count_values() and arsort(). ![]()
<?php
//should return "paragraph" echo getMostFrequentlyOccurringItem(array('line', 'paragraph', 'paragraph')) . '<hr/>'; //should return "line" echo getMostFrequentlyOccurringItem(array('wholeNumber', 'date', 'date', 'line', 'line', 'line')) . '<hr/>'; //should return null echo getMostFrequentlyOccurringItem(array('wholeNumber', 'wholeNumber', 'paragraph', 'paragraph')) . '<hr/>'; //should return "wholeNumber" echo getMostFrequentlyOccurringItem(array('wholeNumber', '', '', '')) . '<hr/>'; function getMostFrequentlyOccurringItem($items) { //catch invalid entry if($items == null) { return null; } if(count($items) == 0) { return null; } //sort $groups = array_count_values($items); arsort($groups); //if there was a tie, then return null $groupAmounts = array_values($groups); if($groupAmounts[0] == $groupAmounts[1]) { return null; } //get most frequent $mostFrequentGroup = ''; foreach($groups as $group => $numberOfTimesOccurrred) { if(trim($group) != '') { $mostFrequentGroup = $group; break; } } return $mostFrequentGroup; } ?> |
How to create a singleton in PHP This example shows the syntax of creating a singleton in PHP. Note that the instance of the class is retrieved twice but its internal variable was set only once which shows that the same instance of the class is being retrieved and not being created again each time it is needed. Use this for any kind of global scope you need in your application, especially classes which have expensive initializations such as retrieving and parsing large amounts of data to be used by various classes in your application. ![]()
<?php echo 'printed at ' . qdat::getMilliseconds() . '<br/>'; $datapodManager = DatapodManager::getInstance(); echo $datapodManager->getTitle() . '<hr/>'; echo 'printed at ' . qdat::getMilliseconds() . '<br/>'; $datapodManager = DatapodManager::getInstance(); echo $datapodManager->getTitle() . '<hr/>'; class DatapodManager { protected $title; public function getTitle() { return $this->title; } private static $instance; private function __construct() { $this->title = 'title set internally at ' . qdat::getMilliseconds(); } public static function getInstance(){ if(!isset(self::$instance)) { self::$instance = new DatapodManager(); } return self::$instance; } } class qdat { public static function getMilliseconds() { $millisecondsParts = explode ( ' ', microtime () ); $fraction = $millisecondsParts[0]; $milliseconds = $fraction * 1000000; return $milliseconds; } } ?> |
Extension method to sort a generic collection of objects This example shows a method which randomizes any generic collection you give it. It is based on the Fisher Yates shuffle. ![]()
using System.Collections.Generic;
using System; namespace TestSort727272 { class Program { static void Main(string[] args) { List<MatchingItem> matchingItems = new List<MatchingItem>(); matchingItems.Add(new MatchingItem("one", "111")); matchingItems.Add(new MatchingItem("two", "222")); matchingItems.Add(new MatchingItem("three", "333")); matchingItems.Add(new MatchingItem("four", "444")); MatchingItem.Display(matchingItems); matchingItems.Shuffle(); MatchingItem.Display(matchingItems); matchingItems.Shuffle(); MatchingItem.Display(matchingItems); Console.ReadLine(); } } public class MatchingItem { public string LeftText { get; set; } public string RightText { get; set; } public MatchingItem(string leftText, string rightText) { LeftText = leftText; RightText = rightText; } public void Display() { Console.WriteLine(LeftText + " / " + RightText); } public static List<MatchingItem> ResortIntoRandomOrder(List<MatchingItem> matchingItems) { List<MatchingItem> newOrderItems = new List<MatchingItem>(); //...matchingItems.Sort(); return newOrderItems; } public static void Display(List<MatchingItem> matchingItems) { Console.WriteLine(""); Console.WriteLine("--DISPLAY:-------------------------"); foreach (var matchingItem in matchingItems) { matchingItem.Display(); } } } public static class Helpers { static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } } } |
A simple class that represents a matching quiz item This is a class that encapsulates matching items which can be displayed as a test with questions and answers and then shows the answer key. ![]()
using System.Collections.Generic;
using System; using System.Threading; namespace TestSort727272 { class Program { static void Main(string[] args) { MatchingItems matchingItems = new MatchingItems(); matchingItems.Add("one", "111"); matchingItems.Add("two", "222"); matchingItems.Add("three", "333"); matchingItems.Add("four", "444"); matchingItems.Setup(); matchingItems.DisplayTest(); matchingItems.DisplayAnswers(); Console.ReadLine(); } } public class MatchingItems { public List<MatchingItem> Collection { get; set; } public List<int> LeftDisplayIndexes { get; set; } public List<int> RightDisplayIndexes { get; set; } private char[] _numbers = { '1', '2', '3', '4', '5', '6', '7', '8' }; private char[] _letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; public MatchingItems() { Collection = new List<MatchingItem>(); LeftDisplayIndexes = new List<int>(); RightDisplayIndexes = new List<int>(); } public void Add(string leftText, string rightText) { MatchingItem matchingItem = new MatchingItem(leftText, rightText); Collection.Add(matchingItem); LeftDisplayIndexes.Add(Collection.Count - 1); RightDisplayIndexes.Add(Collection.Count - 1); } public void DisplayTest() { Console.WriteLine(""); Console.WriteLine("--TEST:-------------------------"); for (int i = 0; i < Collection.Count; i++) { int leftIndex = LeftDisplayIndexes[i]; int rightIndex = RightDisplayIndexes[i]; Console.WriteLine("{0}. {1,-12}{2}. {3}", _numbers[i], Collection[leftIndex].LeftText, _letters[i], Collection[rightIndex].RightText); } } public void DisplayAnswers() { Console.WriteLine(""); Console.WriteLine("--ANSWERS:-------------------------"); for (int i = 0; i < Collection.Count; i++) { string leftLabel = _numbers[i].ToString(); int leftIndex = LeftDisplayIndexes[i]; int rightIndex = RightDisplayIndexes.IndexOf(leftIndex); string answerLabel = _letters[rightIndex].ToString(); Console.WriteLine("{0}. {1}", leftLabel, answerLabel); } } public void Setup() { do { LeftDisplayIndexes.Shuffle(); Thread.Sleep(300); RightDisplayIndexes.Shuffle(); } while (SomeLinesAreMatched()); } private bool SomeLinesAreMatched() { for (int i = 0; i < LeftDisplayIndexes.Count; i++) { int leftIndex = LeftDisplayIndexes[i]; int rightIndex = RightDisplayIndexes[i]; if (leftIndex == rightIndex) return true; } return false; } public void DisplayAsAnswer(int numberedIndex) { Console.WriteLine(""); Console.WriteLine("--ANSWER TO {0}:-------------------------", _numbers[numberedIndex]); for (int i = 0; i < Collection.Count; i++) { int leftIndex = LeftDisplayIndexes[i]; int rightIndex = RightDisplayIndexes[i]; Console.WriteLine("{0}. {1,-12}{2}. {3}", _numbers[i], Collection[leftIndex].LeftText, _letters[i], Collection[rightIndex].RightText); } } } public class MatchingItem { public string LeftText { get; set; } public string RightText { get; set; } public MatchingItem(string leftText, string rightText) { LeftText = leftText; RightText = rightText; } } public static class Helpers { static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } } } |
Extension method for checking regex in one line This simple extension method allows you to check strings against regular expressions in one line. ![]()
using System;
using System.Text.RegularExpressions; using System.Collections.Generic; namespace TestRegex2342343 { class Program { static void Main(string[] args) { List<string> texts = new List<string>() { "233-2887", "2332887", "442-1121", "", null }; foreach (var text in texts) { if (text.MatchesRegex("^[0-9]{3}-[0-9]{4}$")) Console.WriteLine(text + " matches"); else Console.WriteLine(text + " does NOT match"); } Console.ReadLine(); } } public static class Helpers { public static bool MatchesRegex(this string text, string regex) { if (text == null || regex == null) return false; else { Match match = Regex.Match(text, regex); return match.Success; } } } } |
How to use a Dictionary<> with struct key to save a dynamic matrix of objects The following is an example of how you can save both a fixed matrix of objects and a dynamic matrix of objects (size determined at runtime) using first a multi-dimensional array and then a generic dictionary with a struct key. In both examples you can pick the object out of the map with the x/y coordinates. ![]()
using System; using System.Windows; using System.Windows.Controls; using System.Collections.Generic; namespace TestDoubarray { public partial class Window1 : Window { public Window1() { InitializeComponent(); StaticMatrixExampleWithArray(); DynamicMatrixExampleWithDictionary(10, 10); DynamicMatrixExampleWithDictionary(20, 20); } private void StaticMatrixExampleWithArray() { CheckBox[,] checkBoxes = new CheckBox[10, 10]; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { CheckBox cb = new CheckBox(); cb.Tag = String.Format("x={0}/y={1}", x, y); checkBoxes[x,y] = cb; } } CheckBox cbOut = checkBoxes[4, 8]; Message.Text += cbOut.Tag.ToString() + Environment.NewLine; } private void DynamicMatrixExampleWithDictionary(int xMax, int yMax) { Dictionary<MatrixCoordinates, CheckBox> checkboxes = new Dictionary<MatrixCoordinates, CheckBox>(); for (int x = 0; x < xMax; x++) { for (int y = 0; y < yMax; y++) { CheckBox cb = new CheckBox(); cb.Tag = String.Format("x={0}/y={1}", x, y); checkboxes.Add(new MatrixCoordinates { X = x, Y = y }, cb); } } CheckBox cbOut = checkboxes[new MatrixCoordinates { X = 4, Y = 8 }]; Message.Text += cbOut.Tag.ToString() + Environment.NewLine; } private struct MatrixCoordinates { public int X { get; set; } public int Y { get; set; } } } } |
A simple jquery search machine for a web page This example shows how easy it is with JQuery to put a little form on the page that allows a user to search for a keyword which highlights that keyword on the page. ![]()
<!DOCTYPE html>
<html> <head> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load('jquery', '1.4.2'); google.setOnLoadCallback(function() { $('#searchButton').click(function() { $('p').removeClass('highlight'); $('p:contains("' + $('#searchText').val() + '")').addClass('highlight'); }); }); </script> <style> p { color: brown; } p.highlight { background-color: orange; } body { background-color: beige; } </style> </head> <body> <input id="searchText" value="second" /> <button id="searchButton">Search</button> <p>This is the first entry.</p> <p>This is the second entry.</p> <p>This is the third entry.</p> <p>This is the fourth entry.</p> </body> </html> |