Monday, May 31, 2010
utf8 in php5
utf8_encode() and utf8_decode() are awful, because they only operate in the ISO-8859-1 (latin1) charset portion of utf8. Also, for reference U+ff01, the ff01 is called the code point.
Lets say I have a unicode character U+4f60 or 你, and I want to echo it in php.
http://www.fileformat.info/info/unicode/char/4f60/index.htm
PHP is not very utf8 friendly, in order to get to work, you have to be using a computer with the right language packs installed, edit the source file in utf8, make sure every page sends out header('Content-type: text/html; charset=utf-8'); and you may still need to echo the utf8 meta tag. And for good measure make sure the file is saved with a utf8 byte order mark. But how do you echo unicode if your source file can only be in the latin1 character set?
One way is to echo the code point. In java "\u4f60" represents the character 你. Not so in php. The best you can do is these:
<?php echo json_decode('"\u4f60"');?>
<?php echo html_entity_decode("你",ENT_QUOTES,"UTF-8");?>
<?php echo "\xE4\xBD\xA0";?> //already encoded in utf8
but there is another way, with 2 basic functions:
function utf8($num)
{
if($num<=0x7F) return chr($num);
if($num<=0x7FF) return chr(($num>>6)+192).chr(($num&63)+128);
if($num<=0xFFFF) return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
if($num<=0x1FFFF) return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128).chr(($num&63)+128);
return '';
}
function uniord($c)
{
$ord0 = ord($c{0}); if ($ord0>=0 && $ord0<=127) return $ord0;
$ord1 = ord($c{1}); if ($ord0>=192 && $ord0<=223) return ($ord0-192)*64 + ($ord1-128);
$ord2 = ord($c{2}); if ($ord0>=224 && $ord0<=239) return ($ord0-224)*4096 + ($ord1-128)*64 + ($ord2-128);
$ord3 = ord($c{3}); if ($ord0>=240 && $ord0<=247) return ($ord0-240)*262144 + ($ord1-128)*4096 + ($ord2-128)*64 + ($ord3-128);
return false;
}
<?php echo utf8(0x4f60);?>
你
or you can convert back
<?php echo dechex(uniord(utf8(0x4f60)));?>
4f60
Also helpful:
function is_utf8($string)
{
// From http://w3.org/International/questions/qa-forms-utf-8.html
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}
Sunday, May 09, 2010
VirtualBox fullscreen
VBoxSDL -fullscreen -vm XP_mini
Saturday, April 03, 2010
php upload script
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//echo ini_get('post_max_size');
//echo ini_get('upload_max_filesize');
//echo ini_get('max_input_time');
//echo ini_get('max_execution_time');
//echo ini_get('max_file_uploads');
//echo ini_get('file_uploads');
$errors = array(
UPLOAD_ERR_OK =>'There is no error, the file uploaded with success.',
UPLOAD_ERR_INI_SIZE =>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
UPLOAD_ERR_FORM_SIZE =>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
UPLOAD_ERR_PARTIAL =>'The uploaded file was only partially uploaded.',
UPLOAD_ERR_NO_FILE =>'No file was uploaded.',
UPLOAD_ERR_NO_TMP_DIR =>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
UPLOAD_ERR_CANT_WRITE =>'Failed to write file to disk. Introduced in PHP 5.1.0.',
UPLOAD_ERR_EXTENSION =>'A PHP extension stopped the file upload',
);
if ($_FILES['userfile']['error']==UPLOAD_ERR_OK)
{
$uploads_dir = '/srv/www/htdocs/files/';
$tmp_name = $_FILES["userfile"]["tmp_name"];
$name = $_FILES["userfile"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
die("complete");
}
else
{
die($errors[$_FILES['userfile']['error']]);
}
}
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo 200*1024*1024;?>" />
<input name="userfile" type="file" />
<input type="submit" value="Upload" />
</form>
Friday, April 02, 2010
php header for xml utf8
header('Content-Type: text/xml; charset=UTF-8');
source(s): http://www.source.com
Tuesday, March 23, 2010
List Installed Packages (with file sizes) - Ubuntu
dpkg --get-selections | awk '{printf("echo \"%s:\"`sudo aptitude show %s |grep \"Uncompressed Size:\"` \n", $1, $1 );}' >output.sh
sh output.sh| awk -F: '{printf("%s:%s\n",$1,$3);}' >list.txt
rm output.sh
Monday, February 22, 2010
ubuntu hamachi
1. Go to http://code.google.com/p/quamachi/
2. download hamachi and quamachi, ex:
http://quamachi.googlecode.com/files/quamachi-0.4.1-1.package
http://quamachi.googlecode.com/files/hamachi-0.9.9.9-20.package
3. sudo apt-get install python libqt4-core python-qt4 pyqt4-dev-tools upx-ucl grep bash make
4. chmod 777 hamachi-0.9.9.9-20.package
5. chmod 777 quamachi-0.4.1-1.package
6. sudo ./hamachi-0.9.9.9-20.package
7. sudo ./quamachi-0.4.1-1.package
Monday, January 25, 2010
VirtualBox - Start up Virtual Machine without gui
VBoxManage startvm "windows xp" --type headless
VBoxManage controlvm "windows xp" poweroff
Tuesday, January 19, 2010
virtualbox - convert img file to vdi
VBoxManage convertfromraw -format VDI [filename].img [filename].vdi
source(s): http://mdm-adph.blogspot.com/2009/05/using-img-files-with-virtualbox-to-test.html
Monday, January 18, 2010
mysql - get rid of pipe delimiter, and auto escaping
> select '\\';
\\
When using IO redirection, mysql commandline automatically enters --silent or --batch mode, and auto escapes the output. -r (--raw) is the fix.
mysql -r --silent
> select '\\';
\
mysql -r -D digicert_com < somequery.txt > Desktop/r-queries.txt
source(s): http://bugs.mysql.com/bug.php?id=35122
Tuesday, January 12, 2010
VirtualBox copy harddrive to new uuid
source(s): http://www.brianjester.us/blog/index.php?entry=entry080720-165143
Saturday, November 28, 2009
wxWidgets ubuntu linux compile unicode
sudo apt-get install wx-headers libwxbase2.8-0 libwxbase2.8-dev
g++ main.cpp `wx-config --libs` `wx-config --cxxflags`
Friday, November 27, 2009
wxWidgets Sample vcproj file | Unicode
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="utf8_basic"
ProjectGUID="{2FA27B9E-AB18-4225-BF22-3D6042C2D6B6}"
RootNamespace="utf8_basic"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories=""C:\Server\wxWidgets-2.8.10\include\msvc";"C:\Server\wxWidgets-2.8.10\include""
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;WINVER=0x0400;__WXMSW__ ;_WINDOWS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="comctl32.lib rpcrt4.lib winmm.lib advapi32.lib wsock32.lib wxbase28ud.lib wxmsw28ud_core.lib"
LinkIncremental="2"
AdditionalLibraryDirectories=""C:\Server\wxWidgets-2.8.10\lib\vc_lib""
GenerateDebugInformation="true"
SubSystem="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
AdditionalIncludeDirectories=""C:\Server\wxWidgets-2.8.10\include\msvc";"C:\Server\wxWidgets-2.8.10\include""
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;WINVER=0x0400;__WXMSW__ ;_WINDOWS"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="comctl32.lib rpcrt4.lib winmm.lib advapi32.lib wsock32.lib wxbase28u.lib wxmsw28u_core.lib"
LinkIncremental="1"
AdditionalLibraryDirectories=""C:\Server\wxWidgets-2.8.10\lib\vc_lib""
GenerateDebugInformation="true"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\main.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
wxWidgets | Hello World | Unicode | Visual Studio Express 2008
//Project Properties:
//http://wiki.wxwidgets.org/Microsoft_Visual_CPP_Guide
//General>Charset: Use Unicode Character Set (or ansi:not set)
//Include: "C:\Server\wxWidgets-2.8.10\include\msvc";"C:\Server\wxWidgets-2.8.10\include"
//Library: "C:\Server\wxWidgets-2.8.10\lib\vc_lib"
//[preprocessor defines:] WINVER=0x0400;__WXMSW__ ;_WINDOWS
//[linker system subsystem:] Windows (/SUBSYSTEM:WINDOWS)
//[linker libraries (all ):] comctl32.lib rpcrt4.lib winmm.lib advapi32.lib wsock32.lib
//[linker libraries (debug ):] wxbase28ud.lib wxmsw28ud_core.lib
//[linker libraries (release):] wxbase28u.lib wxmsw28u_core.lib
//File > Advanced Save Options > UTF8 with signature, CRLF
#include <wx/wx.h>
class MyApp : public wxApp
{
public:
virtual bool OnInit();
};
IMPLEMENT_APP(MyApp)
bool MyApp::OnInit()
{
wxFrame *simple = new wxFrame(NULL, wxID_ANY, wxT("你好"), wxDefaultPosition, wxSize(250, 150));
simple->Centre();
simple->Show(true);
return true;
}
wxWidgets 2.8 for windows lib files
[ansi] wxexpatd.lib wxexpat.lib wxjpegd.lib wxjpeg.lib wxpngd.lib wxpng.lib wxtiffd.lib wxtiff.lib wxzlibd.lib wxzlib.lib wxregexd.lib wxregex.lib wxbase28d.lib wxbase28.lib wxbase28d_odbc.lib wxbase28_odbc.lib wxbase28d_net.lib wxbase28_net.lib wxbase28d_xml.lib wxbase28_xml.lib wxmsw28d_adv.lib wxmsw28_adv.lib wxmsw28d_aui.lib wxmsw28_aui.lib wxmsw28d_core.lib wxmsw28_core.lib wxmsw28d_dbgrid.lib wxmsw28_dbgrid.lib wxmsw28d_gl.lib wxmsw28_gl.lib wxmsw28d_html.lib wxmsw28_html.lib wxmsw28d_media.lib wxmsw28_media.lib wxmsw28d_qa.lib wxmsw28_qa.lib wxmsw28d_richtext.lib wxmsw28_richtext.lib wxmsw28d_xrc.lib wxmsw28_xrc.lib [unicode] wxregexud.lib wxregexu.lib wxbase28ud.lib wxbase28u.lib wxbase28ud_odbc.lib wxbase28u_odbc.lib wxbase28ud_net.lib wxbase28u_net.lib wxbase28ud_xml.lib wxbase28u_xml.lib wxmsw28ud_adv.lib wxmsw28u_adv.lib wxmsw28ud_aui.lib wxmsw28u_aui.lib wxmsw28ud_core.lib wxmsw28u_core.lib wxmsw28ud_dbgrid.lib wxmsw28u_dbgrid.lib wxmsw28ud_gl.lib wxmsw28u_gl.lib wxmsw28ud_html.lib wxmsw28u_html.lib wxmsw28ud_media.lib wxmsw28u_media.lib wxmsw28ud_qa.lib wxmsw28u_qa.lib wxmsw28ud_richtext.lib wxmsw28u_richtext.lib wxmsw28ud_xrc.lib wxmsw28u_xrc.lib
Wednesday, November 18, 2009
golang setup
export GOROOT=$HOME/go
export GOARCH=386
export GOOS=linux
export GOBIN=~/bin/
export PATH=$PATH:~/bin/
then follow
http://golang.org/doc/install.html
Wednesday, October 28, 2009
ubuntu firewall
sudo apt-get denyhosts
sudo apt-get install ufw
sudo apt-get install gufw
sudo ufw status
sudo ufw enable
sudo ufw limit ssh/tcp
sudo ufw allow proto tcp from 192.168.1.0/24 to any port 22
Tuesday, October 20, 2009
Tuesday, October 13, 2009
wxwidgets screenshot
wxWidgets wxMemoryDC
wxScreenDC dcScreen;
wxCoord screenWidth, screenHeight;
dcScreen.GetSize(&screenWidth, &screenHeight);
wxBitmap screenshot(screenWidth, screenHeight,-1);
wxMemoryDC memDC;
memDC.SelectObject(screenshot);
memDC.Blit( 0, 0, screenWidth, screenHeight, &dcScreen, 0, 0);
memDC.SelectObject(wxNullBitmap);
http://trac.wxwidgets.org/ticket/11007
source(s): http://www.source.com
vaccum a firefox sqlite database
in the firefox profiles folder. look for: *.sqlite
Friday, September 11, 2009
rsync -C or --cvs-exclude
--include=*.exe
Which filetypes does cvs ignore? Then.. which filetypes does rsync ignore ontop of the cvs ignores. From man pages (man rsync):
-C, --cvs-exclude
This is a useful shorthand for excluding a broad range of files that you often don’t want to transfer between systems. It uses a similar algorithm to CVS to determine if a file should be ignored.
The exclude list is initialized to exclude the following items (these initial items are marked as perishable — see the FILTER RULES section):
RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS .make.state .nse_depinfo *~ #* .#* ,* _$* *$ *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb *.o *.obj *.so *.exe *.Z *.elc *.ln core .svn/ .git/ .bzr
then, files listed in a $HOME/.cvsignore are added to the list and any files listed in the CVSIGNORE environment variable (all cvsignore names are delimited by whitespace).
Finally, any file is ignored if it is in the same directory as a .cvsignore file and matches one of the patterns listed therein. Unlike rsync’s filter/exclude files, these patterns are split on whitespace. See the cvs(1) manual for more information.
If you’re combining -C with your own --filter rules, you should note that these CVS excludes are appended at the end of your own rules, regardless of where the -C was placed on the command-line. This makes them a lower priority than any rules you specified explicitly. If you want to control where these CVS excludes get inserted into your filter rules, you should omit the -C as a command-line option and use a combination of --filter=:C and --filter=-C (either on your command-line or by putting the “:C” and “-C” rules into a filter file with your other rules). The first option turns on the per-directory scanning for the .cvsignore file. The second option does a one-time import of the CVS excludes mentioned above.
Thursday, September 03, 2009
modification to zetcode tutorial
http://zetcode.com/tutorials/wxwidgetstutorial/menustoolbars/
has the line
I get the error in a windows compiler
"failed in wxToolbar::Realize(): invalid tool button bitmap"
the fix:
replace that line with
wxBitmap exit(exitimage);
note:
don't forget to include #include
and call wxInitAllImageHandlers(); in your app init
wx widgets icon for your app
aaaaaaaaaaaaaaaa ICON "application_icon.ico"
application_icon ICON "application_icon.ico"
#define wxUSE_NO_MANIFEST 1
// set this to 1 if you don't want to
// use manifest resource (manifest resource
// is needed to enable visual styles on
// Windows XP - see docs/msw/winxp.txt
// for more information)
#include <wx/msw/wx.rc>
the windows compiler sets the first icon to be the .exe icon... and the 2nd is referenced in the code:
Then in your Frame constructor
#if !defined(__WXMSW__) && !defined(__WXPM__)
#include "application_icon.xpm"
#endif
SimpleMenu::SimpleMenu(const wxString& title)
: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(280, 180))
{
SetIcon( wxICON( application_icon ) );
...
you can use gimp to build your xpm and and ico files. If you rename your xpm file at all... edit it with a text editor and make sure the c string in it reads:
application_icon_xpm if the filename is application_icon.xpm
wxWidgets - rc file "wx/msw/wx.rc" not found
with an .rc file that has:
#include "wx/msw/wx.rc"
Error: "wx/msw/wx.rc" not found
the fix:
wxWidgets - No Image Handler Defined
Error: No Image Handler Defined
the fix:
wxInitAllImageHandlers();
Friday, August 21, 2009
use array_map to select 1 column out of rowset of php rows
$arr = array();
$arr[] = array('first'=>'jack','last'=>'smith');
$arr[] = array('first'=>'john','last'=>'williams');
$arr[] = array('first'=>'mark','last'=>'jesperson');
$arr[] = array('first'=>'vlad','last'=>'shuttleworth');
$f = array_map(create_function('$a', 'return $a["first"];') , $arr);
echo implode(",", $f);
//outputs:
//jack,john,mark,vlad
Friday, July 31, 2009
numbers from 001 to 999
echo "<?php for(\$i=1; \$i<=999; \$i++){ echo sprintf('%03d',\$i).chr(10);} ?>"|php
The \ has to go before the $ character because $i can refer to the command line environment variable $i, so we escape it with \$i in order to pass it straight through to the php parser.
Thursday, July 30, 2009
output formatting like command line sql
$sql = '';
$sql.="SELECT fieldtype, count(1) as count ";
$sql.="FROM mytable ";
$sql.="GROUP BY fieldtype ";
$sql.="ORDER BY fieldtype ";
echo report_append("summary of data", $sql);--output1---------
|fieldtype|count|
|0 |9 |
|1 |397 |
|2 |965 |
|3 |554 |
|4 |683 |
|5 |1352 |
|6 |1390 |
|7 |237 |
|8 |1372 |--usage2----------
$q='';
$q.="SELECT
(case
when fieldtype=1 then 'Apple'
when fieldtype=2 then 'Banana'
when fieldtype=3 then 'Blackberry'
when fieldtype=4 then 'Cherry'
when fieldtype=5 then 'Grape'
when fieldtype=6 then 'Orange'
when fieldtype=7 then 'Peach'
when fieldtype=8 then 'Pear'
else '' end) as typename, fieldtype, count(1) as count
FROM mytable d GROUP BY fieldtype ORDER by fieldtyped;
";
report_append("summary of data", $q);--output2---------
|typename |fieldtype|count|
| |0 |9 |
|Apple |1 |397 |
|Banana |2 |965 |
|Blackberry|3 |554 |
|Cherry |4 |683 |
|Grape |5 |1352 |
|Orange |6 |1390 |
|Peach |7 |237 |
|Pear |8 |1372 |--code------------
function select_all($sql)
{
$rows = array();
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
$rows[] = $row;
return $rows;
}
function report_append($title,$sql)
{
$rows = select_all($sql);
$headersize=array();
$header=array();
foreach($rows[0] as $colname=>$col)
$header[]=$colname;
foreach($rows[0] as $colname=>$col)
$headersize[] = strlen($colname);
foreach($rows as $row)
foreach($headersize as $colnum=>$col)
$headersize[$colnum] = max( $headersize[$colnum] , strlen($row[$header[$colnum]]) );
$h='';
foreach($header as $colnum=>$colname)
$h.="|".sprintf("%-".$headersize[$colnum]."s", $colname);
$h.= "|\n";
foreach($rows as $row)
{
foreach($headersize as $colnum=>$col)
$h.="|".sprintf("%-".$col."s", $row[$header[$colnum]]);
$h.= "|\n";
}
$return='';
$return.="---------------------------------------------------------\n";
$return.="$title\n";
$return.="---------------------------------------------------------\n";
$return.=$h;
return $return;
}Monday, July 20, 2009
Crontab daily gui app launcher, and taskkill
8 10 * * 1-5 if ! ps -C pidgin > /dev/null; then export DISPLAY=:0 && pidgin; fi
Friday, July 10, 2009
common pitfalls when going from html to xhtml
common pitfalls when going from html to xhtml
-------------------------------------------------
<img /><br /><input /> #good, bad: <img><br><input>
<i><b>hi</b></i> #good, bad: <b><i>hi</b></i>
<a href=""></a> #good, bad: <a href=''></a>
<a href="a=b&c=d"></a> #good, bad: <a href="a=b&c=d"></a>
  #good, bad: Saturday, July 04, 2009
Friday, June 12, 2009
Monday, June 08, 2009
smbfs smbmount are deprecated, use cifs
mount -t cifs -o username=guest \\\\192.168.0.97\\share /home/share-buff/
Friday, June 05, 2009
postgres age function
select dob,extract(year from AGE(dob )) from dob_table limit 1;
select dob,extract(year from AGE(now(), dob )) from dob_table limit 1;
select dob,extract(year from AGE(current_timestamp,dob)) from dob_table limit 1;
select dob,extract(year from AGE('2009-09-10', dob )) from dob_table limit 1;
select dob,to_char(AGE(dob),'YYYY')::integer from dob_table limit 1;
select dob,substr(AGE(dob)::text,1,3) from dob_table limit 1;
Tuesday, June 02, 2009
Cross Browser Compatible Javascript DOMelement function
//------------
a.setAttribute('class','myclass');
a.setAttribute('id','id_mydiv');
document.getElementById('otherdiv').appendChild(a);
//------------
to create a dom element... and it only worked in firefox. to get one that works in internet explorer you have to do:
//------------
try {
a = document.createElement('<div class=myclass id=id_mydiv>');
}
catch(e) {
a = document.createElement('div');
a.setAttribute('class','myclass');
a.setAttribute('id','id_mydiv');
}
document.getElementById('otherdiv').appendChild(a);
//------------
include the function below, and it will work in both browsers:
//------------
document.getElementById('otherdiv').appendChild(a);
//------------
{
var htmlspecial = function(tmp_str){
var histogram = {"&":"&","'":"'", "\"":""","<":"<",">":">"};
for (symbol in histogram)
tmp_str = tmp_str.split(symbol).join(histogram[symbol]);
return tmp_str;
}
var element;
try{
var attribute_str = '';
for(attribute_name in attributes)
if (attribute_name!='text')
attribute_str+= attribute_name+"='"+htmlspecial(o.attributes[attribute_name])+"'";
element = document.createElement("<"+elementname+" "+attribute_str + ">");//IE
}catch (e){
element = document.createElement( elementname );
for(attribute_name in attributes)
if (attribute_name!='text')
element.setAttribute( attribute_name , attributes[attribute_name] );
}
if (attributes && attributes['text'])
element.innerHTML = attributes['text'];
return element;
}
Thursday, May 28, 2009
iPod Touch

Accessories:
However to use skype you need a microphone for your ipod touch. The charger that comes with it charges off of your computer so if you go on vacation you will need a wall and/or car charger. You will also want to get an audio/video cable set so you can project videos onto your tv set.
JVC Everio
It is offering a JVC Everio GZ-MS100 model right now for $180, which is really nice, considering that flash memory will continue to get cheaper. So instead of paying $350 for a hard drive camcorder... get a flash based one, and get a 2GB SD card. In a few years 8GB and 16GB SDHC cards will be cheap, and you can just use that for your camcorder.

For accessories it might be a good idea to get an extra JVC Everio battery. Because even if you have space to record 4 hours of video on your SD card, it doesn't mean your video camera battery will last that long
Tuesday, May 26, 2009
nohup command
nohup ./myscript.sh>log_myscript.log 2>&1 &
tail -f log_myscript.log
nohup ./myscript.sh>log_myscript_`date +%Y%m%d`.log 2>&1 &
tail -f log_myscript_`date +%Y%m%d`.log
`date +%Y%m%d` - grabs current date, inserts it into filename
nohup - script run even after terminal/ssh session ends
>log_myscri... - captures output to log file named log_myscr..
2>&1 - outputs stderr to stdout
& - makes it run in the background
tail -f - watches log, CTRL-C will not stop script
Sunday, May 24, 2009
rsync windows to linux
1. compile cygwin... use the following, place them in your path
(c:\windows\system32 or c:\server\bin\)
rsync.exe
ssh.exe
ssh-keygen.exe
cygcrypto-0.9.8.dll
cygiconv-2.dll
cygintl-8.dll
cygminires.dll
cygpopt-0.dll
cygwin1.dll
cygz.dll
2. on the windows machine, run ssh-keygen at the command promptit will create a file
C:\Documents and Settings\user\.ssh\id_dsa.pub
3. copy C:\Documents and Settings\user\.ssh\id_dsa.pub to the linux machine... then authorize it:
mkdir ~/.ssh
cat id_dsa.pub >>~/.ssh/authorized_keys2
mkdir ~/backups
4. If you want to rsync F:\apps\myfolder then save the following as... backup.bat
-----------
F:
cd \apps
"c:\server\bin\rsync.exe" -arv -e "c:\server\bin\ssh.exe" myfolder user@linux:/home/user/backups/
-----------
Tuesday, May 19, 2009
gpg crontab
2. --batch is necessary for crontabs because it tells gpg there is no user to interact with
3. 2>&1 is useful because it redirects stderr to stdout so you can better debug any errors you may be having
4. -d is for decrypt. in this case we are decrypting on a cron job
Monday, April 20, 2009
Curl HTTP Authentication
$url = "http://www.example.com/protected/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
source(s): http://devzone.zend.com/article/1081-Using-cURL-and-libcurl-with-PHP
Sunday, April 19, 2009
FLTK in Visual C++ Express 2008
1. Download fltk-1.1.9-source.zip
2. Unzip to C:\Server\fltk-1.1.9\
3. Your include folder is C:\Server\fltk-1.1.9\FL\
4. Your lib folder is C:\Server\fltk-1.1.9\include\
5. Go into C:\Server\fltk-1.1.9\vc2005\
6. Open fltk.sln
7. Compile as Debug
8. Compile as Release
9. Build your hello world.
(http://www.fltk.org/documentation.php/doc-1.1/basics.html)
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
int main(int argc, char **argv) {
Fl_Window *window = new Fl_Window(300,180);
Fl_Box *box = new Fl_Box(20,40,260,100,"Hello, World!");
box->box(FL_UP_BOX);
box->labelsize(36);
box->labelfont(FL_BOLD+FL_ITALIC);
box->labeltype(FL_SHADOW_LABEL);
window->end();
window->show(argc, argv);
return Fl::run();
}
10. Configure the following in your project in Visual C++ Express 2008:
Tools > Options > Projects and Solutions > VC++ Directories >
INCLUDE: C:\Server\fltk-1.1.9
LIB: C:\Server\fltk-1.1.9\lib
Project > Project Properties > [Debug and Release] > Linker
> Input > Additional Dependencies
wsock32.lib fltk.lib comctl32.lib
Thursday, April 02, 2009
setup vnc server on fedora
# assume we are setting it up to vnc as bsmith
su -
# as root: verify current ip address
ifconfig
# as root: install if needed
yum install vnc-server
# as root: uncomment out 2 lines, replace myusername with bsmith
vim /etc/sysconfig/vncservers
# as bsmith: set vnc password
vncpasswd
# as root: generates ~/.vnc/xstartup
service vncserver start
# as root: sets service to startup with machine
chkconfig vncserver on
# as root: uncomment out line 4 and 5
vim /bsmith/.vnc/xstartup
# as root: applies settings
service vncserver start
# as root: open up port in firewall, note vnc is insecure by protocol
vim /etc/sysconfig/iptables
# as root: apply firewall changes, vnc=insecure so better to use over lan
service iptables restart
Thursday, March 26, 2009
C/C++ win32 programming tutorials and open source projects
http://sourceforge.net/projects/cinputbox/
http://sourceforge.net/projects/win32net/
http://sourceforge.net/projects/notepad-plus/
http://sourceforge.net/projects/smartwin/
http://sourceforge.net/projects/radcpp/
http://sourceforge.net/projects/pwrgrid/
http://sourceforge.net/projects/gettext/
http://sourceforge.net/projects/gqview-win/
http://sourceforge.net/projects/win32gui/
http://sourceforge.net/projects/big3dsol/
http://sourceforge.net/projects/bhwindow/
http://sourceforge.net/projects/mancalacpp/
http://sourceforge.net/projects/win32-framework/
http://winprog.org/tutorial/
http://www.winprog.org/tutorial/msvc.html
http://www.relisoft.com/win32/index.htm
http://www.suite101.com/blog/leckyt/win32_programming_tutorial
http://www.functionx.com/win32/index.htm
http://www.functionx.com/win32/Lesson01.htm
http://www.nullterminator.net/opengl32.html
http://www.zetcode.com/tutorials/winapi/
http://www.vczx.com/tutorial/win32-tutorial/index.html
http://www.tenouk.com/cnwin32tutorials.html
http://www.sgi.com/products/software/opengl/examples/win32_tutorial/
http://www.geocities.com/Heartland/Meadows/9818/win32tut/index.html
http://www.relisoft.com/Win32/winnie.html
Monday, March 23, 2009
sunspider benchmark ie8, ff3.5, safari4, chrome
Total: 52562.6ms +/- 1.8%
IE8
Total: 8459.8ms +/- 0.3%
Safari4
Total: 1411.2ms +/- 0.6%
Chrome1
Total: 1783.6ms +/- 6.5%
Firefox
Total: 4727.8ms +/- 0.6%
FF3.0
Total: 4831.0ms +/- 3.6%
FF3.5
Total: 2551.4ms +/- 11.5%
Sunday, March 22, 2009
php - decutf8 decimal to utf8 entity
echo decutf8(632);//prints ɸ which has htmlentity ɸ
{
$bin = decbin($str);
$out = 127;
if (strlen($bin)<=7)
{
$bin=sprintf("%08d", $bin);
$out=bindec($bin);
}
else if (strlen($bin)<=11)
{
$bin=sprintf("%011d", $bin);
$out=bindec("110".substr($bin,0,5)."10".substr($bin,5,6));
}
else if (strlen($bin)<=16)
{
$bin=sprintf("%016d", $bin);
$out=bindec("1110".substr($bin,0,4)."10".substr($bin,4,6)."10".substr($bin,4,6));
}
else if (strlen($bin)<=21)
{
$bin=sprintf("%021d", $bin);
$out=bindec("11110".substr($bin,0,3)."10".substr($bin,3,6)."10".substr($bin,9,6)."10".substr($bin,15,6));
}
if ($out <=255)
return chr($out);
else if ($out <=(255 * 256) )
return chr($out/256).chr($out%256);
else if ($out <=(255 * 256 * 256) )
return chr($out/256).chr($out/256).chr($out%256);
else if ($out <=(255 * 256 * 256 * 256) )
return chr($out/256).chr($out/256).chr($out/256).chr($out%256);
}
Saturday, March 14, 2009
articles - dont store images in a mysql database
Wednesday, March 11, 2009
javascript debugging in ie
There are 3 ways to debug javascript in ie:
1. microsoft script debugger
2. visual studio .net
3. microsoft script editor (comes with office xp/2003)
Seeing as [2] and [3] both involve handing money over to micro$oft. We are left with [1]. The microsoft script debugger is no way related to the Internet Explorer Developer Toolbar
The Script Debugger is pretty sad but at least you can visually see what line of code your IE breaks on. It can still leave you scratching your head as to 'why' though. To enable it go to your "internet options" menu and hit uncheck the "Disable Script Debugging (Internet Explorer)" option.
Note to self: This breaks in IE7
var a = { width: 100, height :200 , };
While invalid syntax, IE7 should not be so delicate it gets tripped up by this. Allowing an extra comma in an array or dynamic object allows for cleaner code when generating javascript from another language.
debug ie6
Thursday, February 26, 2009
please mount the unreal tournament play disc cdrom - ut2004 on ubuntu fix
"please mount the unreal tournament play disc cdrom"
I think because ubuntu auto-mounts volumes, it mounts them in multiple places, somehow confusing the installer. The answer is to umount it... then manually mount it below as shown.
sudo apt-get install libgtk1.2
umount /media/cdrom
sudo mount /dev/cdrom /media/cdrom
export SETUP_CDROM=/media/cdrom
/media/cdrom/linux-installer.sh
... let it install ...
umount -f /media/cdromNote: installing libgtk1.2 is just to have a gui installer instead of console/ascii looking installer
it worked for me.
linux bash xargs cut convert usage
ls *.psd | cut -d . -f 1 | xargs -L1 -i convert {}.psd {}.pngThursday, February 12, 2009
geoip lookup
data available from:
http://www.maxmind.com/app/geolitecountry
http://www.maxmind.com/app/geolitecity
Wednesday, February 11, 2009
echo tabs in bash
Wednesday, January 28, 2009
How to add mdbg search for firefox search bar
on windows: C:\Program Files\Mozilla Firefox\searchplugins
mdbg.xml
<ShortName>MDBG</ShortName>
<Description>MDBG Character Lookup</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16">data:image/x-icon;base64,AAABAAIAEBAQAAAAAAAoAQAAJgAAACAgEAAAAAAA6AIAAE4BAAAoAAAAEAAAACAAAAABAAQAAAAAAIAAAAAAAAAAAAAAABAAAAAQAAAAAAAAAAAAgAAAgAAAAICAAIAAAACAAIAAgIAAAICAgADAwMAAAAD/AAD/AAAA//8A/wAAAP8A/wD//wAA////APAAAP//AA//8P//D/D/8P/w//8PD///D/D//w8P/wAP8AAADw/////w//8PD///D/D//w/w//D/8AAA//8AD//w/w/w8AAP//D/D/Dw//D/8PDw8PD//w/w8PDw8P//D/Dw8PDw//8P8A//APD//w/wD/8A8P/w//D///DwAA//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAgAAAAQAAAAAEABAAAAAAAAAIAAAAAAAAAAAAAEAAAABAAAAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAgICAAMDAwAAAAP8AAP8AAAD//wD/AAAA/wD/AP//AAD///8A//////////////////////8AAAAAAP////8AAAD/////AAAAAAAP//8AAAAAAP///wAP//8AAP/wAA//8AAP//8AD///8AD/8AD///8AD///AA////AA/wAP////AA///wAP//8AAP8AD//wAAAP//8AAAAAAA//AA//8AAAD///AAAAAAD//wAP/////////wAP//8AD/8AD/////////8AD///AA//AA////8AD///AA///wAP//AA///wAP///wAP//8AD//wAA//AAD///8AAAAAAA///wAAAAAP////AAAAAA//////AAAA////////////////////////////////////////////////AA//AP/wAP8AAAAAD////wAP8AAP8AD/AAAAAAD///8AD/AAD/AA/wAP//AAD///AA/wAA/wAP8AD///AA///wAP8AAP8AD/AA////AA//8ADwAAAPAA/wAP///wAP//AA8A/wDwAP8AD///8AD//wAPAP8A8AD/AA////AA//8ADwD/APAA/wAP///wAP//AAAA/wAAAP8AD///8AD//wAAD//wAAD/AA///wAP//8AAA//8AAA/wAP//AAD///AAAP//AAAP8AAAAAAP///wAAD///AAD/AAAAAA////////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==</Image>
<Url type="text/html" method="GET" template="http://www.mdbg.net/chindict/chindict.php?page=chardict&cdcanoce=0&cdqchi={searchTerms}&cddmtm=1&cddytm=0"/>
<SearchForm>http://mdbg.com/</SearchForm>
</SearchPlugin>
Saturday, January 24, 2009
Friday, January 23, 2009
Saturday, January 10, 2009
How to mount an iso in linux
1. make some folder
2. as root...mount it
Friday, January 09, 2009
A8V-VM SE sound on linux
in opensuse 11.1 set 'model' option to 3stack in yast2
Tuesday, December 16, 2008
Sunday, December 14, 2008
replace notepad with notepad2
replacenotepad2.bat
copy notepad2.exe C:\WINDOWS\system32\notepad.exe
copy notepad2.exe C:\WINDOWS\ServicePackFiles\i386\notepad.exe
copy notepad2.exe C:\WINDOWS\system32\dllcache\notepad.exe
Monday, December 08, 2008
Friday, December 05, 2008
mount a samba fileshare in linux
edit /etc/fstab, add the line:
replace host with [host]
/shared/ with the folder shared
/home/shar/ with where you want to mount it
u with the samba username
p with the samba password
(when complete, 'mount -a' should apply the fstab changes).
Thursday, November 27, 2008
MySQL: Load CSV into db
CREATE TABLE `digitalsignage`.`tmp_directory` (
`f1` varchar(255) NULL,
`f2` varchar(255) NULL,
`f3` varchar(255) NULL,
`f4` varchar(255) NULL,
`f5` varchar(255) NULL,
`f6` varchar(255) NULL,
`f7` varchar(255) NULL,
`f8` varchar(255) NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
LOAD DATA INFILE 'Book2.csv'
INTO TABLE `tmp_table`
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
Thursday, November 20, 2008
Wednesday, November 19, 2008
Wednesday, November 12, 2008
linux sort
sort -t$'\t' +1 -2 export_1612.txt>sorted.txt
Friday, November 07, 2008
BASH - Time Your Bash Script
time_start=`date +%s`
sleep 63
time_end=`date +%s`
time_elapsed=$((time_end - time_start))
echo $(( time_elapsed / 60 ))m $(( time_elapsed % 60 ))s
Tuesday, November 04, 2008
VMWare on supporting 64 bit guest OSes
Later I tried this all again but on an intel 32 bit box, and it didn't work.
I just found a link that describes under exactly what conditions 64 bit guest OSes will and won't work:[kb.vmware.com].
Tuesday, October 28, 2008
PgSQL: random notes
postgres, allow localhost with no password
/var/lib/pgsql/pg_hba.conf
on line: with host all all 127.0.0.1/32 md5
change md5 to trust
postgres, set new password
[user@server ~]psql -U postgres -h localhost -d postgres
ALTER USER postgres WITH PASSWORD 'newpass';
#where postgres is the dbname
pgsql -U postgres -d dbname
# (at pgsql prompt) this will give the schema of the table
dbname=# \d tablename
# (at pgsql prompt) view autoincrement expression for field
dbname=# \d tablename
# (at pgsql prompt) how to view next autoincrement number
dbname=# select nextval('tablename_fieldname_seq');
# (at pgsql prompt) how to set autoincrement number
dbname=# select setval('tablename_fieldname_seq', 50);
source(s): http://www.source.com
Thursday, October 16, 2008
Linux - New set of Notes
this is a system startup script kind of like the old autoexec.bat
/etc/rc.local
this is a bash startup script for that user, also an .sh
/home/username/.bash_profile
defaults for new users
/etc/skel/.bash_profile
CTRL-ALT-D
show desktop
FC8:
System > Preferences > Personal > Keyboard Shortcuts
CTRL-ALT <arrow> (l,r,u,d) to navigate between desktops
Monday, September 22, 2008
Skype: Belkin Skype Phone
Skype is a DIY voip service. They offer a skype out unlimited subscription for canada and the usa (unlimited outgoing calling from your computer to landlines and cellphones) for $30. If you choose you can also get a phone number in whatever USA area code you want for another $30. I am sad that there still are no numbers available in canada. Because skype online numbers are available in over 20 countries at the time of this writing, i wouldn't be surprised if canada has extra red tape, which is preventing this.
So for the cost of $5 computer speakers, $5 computer microphone, an internet connection and $60/year ($5/month) you can scrap your $30/month landline. Don't forget to read the fine print, skype wants you to know that you can't use it for 911 calling, because the 911 operators have no idea where you are calling from. You could be online in europe and still take skype calls at your 801 usa area code through your internet connection. So... it is important to keep an old cell phone around. Even deactivated/non-sim card cell phones are required by law to be able to call 911.
My wife doesn't like using the computer for calling much, plus we don't want to leave it on 24/7 to take calls so we were thinking of getting the belkin skype desktop phone. This phone is a no computer required phone. It seems a little pricey considering it is just a phone... but understood what the skype phone really is, its pretty much an $80 computer with built-in microphone and speakers.
There are a lot of items for sale which replace your microphone and speakers... some usb phones, some cordless phones (comp req'd), other cordless phones (comp not req'd), and even wifi phones. Wifi is great... if you get a wifi hotspot anywhere you can make or take calls. I have heard the battery life on them isn't great yet... because it just like a minilaptop- but you can't turn the wifi network card off for power saving mode!
Thursday, September 11, 2008
C++ : How to Launch a Background in Windows Program
./app_to_launch &In windows there is no easy command line suffix which will launch your program in the background. However it is relatively easy to code one up. If you install Visual C++ Express 2005, and the Microsoft Platform SDK (see configuration below) just compile this application as BKLAUNCH.exe and you will soon be able launch apps in the background from batch files.
I created an empty win32 project named BKLAUNCH, no precompiled header, and compiled the following code.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <windows.h>
#include <shellapi.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
if (argc!=2)
{
printf("Usage:\n");
printf(" BKLAUNCH.EXE [apptolaunch]\n");
printf(" BKLAUNCH.EXE notepad.exe\n");
exit(0);
}
ShellExecute(NULL, TEXT("open"), argv[1], NULL, NULL, SW_SHOW);
return 0;
}Once BKLAUNCH has successfully compiled, place it in a folder that is in the PATH. Now, go to Start > Run > cmd.exe [OK], and enter the following:
BKLAUNCH notepad.exeYou will notice notepad.exe is launched in the background, perfect for batch files.
Troubleshooting
If you are like me and use default settings, look under
Project > Project Properties > Linker > Input > Additional Dependencies
it will will have only kernel32.lib. When you compile there will be linker errors.
Because of the #include <windows.h> and #include <shellapi.h>
you need to add the following to your Additional Dependencies
kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib in order to resolve the linker errors.
Microsoft Platform SDK Config
In order to use the MS Platform SDK in Visual C++ Express 2005, you have make the platform SDK visible to the compiler.
Go to
Tools > Options > Projects and Solutions > VC++ Directories > Platform=Win32 > Show Directories for=include files
Add to the list,
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Include
(or wherever you installed the MS Platform SDK\Include)
Now, go to
Tools > Options > Projects and Solutions > VC++ Directories > Platform=Win32 > Show Directories for=library files
Add to the list,
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Lib
(or wherever you installed the MS Platform SDK\Lib)
Tuesday, September 09, 2008
BASH: bad interpreter: No such file or directory
-bash: ./execute.sh: /usr/bash^M: bad interpreter: No such file or directoryDos text files use \r\n (0xD 0xA) as their end of line characters. Unix text files use \n (0xA) as their end of line character. What happened here is I had a file in dos text format, and tried to execute it in bash. the ^M you see above is saying "It wasn't expecting the \r character".
Solution:
use dos2unix
[user@linux1 ~] dos2unix execute.sh
dos2unix: converting files execute.sh to UNIX format...Monday, September 08, 2008
C++: Simple Makefile Example
Assuming you have the files
./Makefile
./include/file1.h
./include/file2.h
./include/file3.h
./src/file1.cpp
./src/file2.cpp
./src/file3.cpp
and all obj files go in ./obj/
and your target executable is ./execfile
Makefile
CC =g++
CFLAGS =-c -Wall
LDFLAGS =
INCLUDE =-I./include
OBJDIR =obj/
OBJLIST = file1.o file2.o file3.o
OBJECTS = $(addprefix $(OBJDIR), $(OBJLIST) )
all:execfile
execfile: $(OBJECTS)
[TAB]$(CC) $(LDFLAGS) $(OBJECTS) -o $@
$(OBJECTS): obj/%.o: src/%.cpp
[TAB]$(CC) $(CFLAGS) $? -o $@ $(INCLUDE)
clean:
[TAB]rm -rf obj/*.oThursday, June 19, 2008
PHP: Web Bug Script
The problem with their web bug script is it requires the php-gd2 extension, it results in 95 byte output, and uses php gd code allocating memory... deallocating memory when its not necessary. This script when scaled up 100,000x has too large a footprint. It can be optimized into 3 lines as follows (with a 43 byte output):
<?php
//saves ip address and timestamp
file_put_contents("ip_list.txt", date("Y-m-d H:i:s") . ": ". $_SERVER['REMOTE_ADDR'] . "\n", FILE_APPEND);
header("content-type: image/gif");
//43byte 1x1 transparent pixel gif
echo base64_decode("R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
?>
Thursday, January 31, 2008
PHP: Calculate PHP Page Load Time
$s_mt = explode(" ",microtime());
//put this at the end of your php script
$e_mt = explode(" ",microtime());
$s = (($e_mt[1] + $e_mt[0]) - ($s_mt[1] + $s_mt[0]));
echo "Page created in ".$s." seconds";
