Skip navigation

Monthly Archives: May 2008

  • PHP fails gracefully. Java crashes and burns.

    Say variable var doesn’t exist yet. We have 2 lines of code:

    # php:
    $var = 230;
    
    // java
    var = 230;
    

    Undefined variable? In php the principle is . . if it doesn’t already exist. . php creates it. You don’t DECLARE variables in php. You just use them. Like in JavaScript.

    Java? STATUS 500. THIS PAGE HAS CRASHED AND BURNED, because of an undefined variable.

  • In php, you don’t have to restart tomcat. or whatever webserver you’re using. hardly ever.
  • there’s more……….
Advertisements

wow! that was fun.

This is how you do it, using Sara Golemon’s Extending and Embedding PHP as a reference (a fabulous book, by the way).

  1. create a folder on your c drive, like C:\PHPDEV
  2. download php 5.2.6 source from a mirror (this is the current php 5 version, time of this post). Save this tar.gz file into C:\PHPDEV. EXTRACT IT THERE.
  3. download php win32 build extras and save into C:\PHPDEV. EXTRACT IT THERE.
  4. Get pre-built binary packages for bison.exe and flex.exe. Put those on your desktop, or somewhere AWAY from C:\PHPDEV.

    Open both archives and go into their /bin directories. Take flex.exe from the flex archive and bison.exe from the bison archive and put THOSE into C:\PHPDEV.

  5. The next step can get twisted if you don’t have Visual Studio (any version?) installed.

    If you don’t have it, try the express editions, or take a look at ishouldbecoding.com article.

    Assuming you have Visual Studio 2008, FIRST, open C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\vsvars32.bat.

    The file is about 50 lines long full of @set type statements.

    Find the line that starts with

    @set PATH=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE;(goes on)

    Change that line to read

    @set PATH=C:\PHPDEV;C:\Program Files\Microsoft Visual Studio 8\Common7\IDE;(leave the rest exactly as it were)

    So all I did there was add C:\PHPDEV; just after the = sign. The reason I did that was so that flex.exe and bison.exe are part of the system path now.

    NOW, go to Start->Microsoft Visual Studio 2008->Visual Studio Tools->Visual Studio 2008 Command Prompt.

  6. switch to C:\PHPDEV\php-5.2.6
  7. type buildconf.bat
    What this does is scan all folders for .w32 files and creates configure.js for you
  8. type:
    cscript /nologo configure.js --without-xml --without-wddx --without-simplexml --without-dom --without-libxml --disable-zlib --without-sqlite --disable-odbc --disable-cgi --enable-cli --enable-debug --without-iconv --disable-ipv6
    

    **** COPY PASTE THE ABOVE LINE. ITS LONGER THAN IT LOOKS.

    what this does is modify configure.js for you. You can get the same effect I guess by going into configure.js and manually setting things to “yes” and “no”. Why disable all these things? Most of these aren’t included in the bundle you downloaded, so you’d get compile errors like “file not found” if you didn’t disable these.

    if you don’t have bison.exe, you’ll get:

    ERROR: bison is required

    If you don’t have flex.exe, you’ll get

    ERROR: flex is required

    so get bison and flex as explained above.

  9. Type

    nmake

  10. switch to c:\PHPDEV\php-5.2.6\Debug_TS
  11. Type something like

    php -r “$x = ‘hello’; echo($x);”

Sara, you are fantastic. The book is rich and explains things very clearly. I had to skim through some of the stuff about php life cycle and php variables, because I was anxious to build it, but there’s tons more to read here :). Seems to be fairly considerate to windows users. Thanks for writing that book, to begin with.

online guide
another article – ishouldbecoding.com
Elizabeth Smith

Q: how do i manually shut off my monitor in windows xp?

A: Reach for the switch. you know, the physical power switch?

Ah. But you want to do it PROGRAMMATICALLY. Well

// console application
#include <windows.h>

#define SCREENSAVER_START 1
#define MONITOR_OFF 2

int main( int argc, char** argv )
{
  int cmd = SCREENSAVER_START; // default when run
  // is to start screensaver.

  // if passed command line argument (no matter
  // what it is), just turn off the monitor instead.
  if( argc > 1 )
  {
    // could check argv,
    cmd = MONITOR_OFF;
  }

  switch( cmd )
  {
  case SCREENSAVER_START:
      SendMessage( HWND_TOPMOST,
                 WM_SYSCOMMAND,
                 SC_SCREENSAVE,
                 0 );  // send message to top most window
  // for screensaver to start.  that's just
  // how you programmatically start the screensaver
  // under windows!
                 break;

    case MONITOR_OFF:
        SendMessage( HWND_BROADCAST,
                 WM_SYSCOMMAND,
                 SC_MONITORPOWER,
                 (LPARAM)2 ); // turn off the monitor.
                 break;
  }
}


I keep this executable in my start menu. I create 2 shortcuts:

One called “monitor off” that has target

C:\Documents and Settings\All Users\Start Menu\Programs\Monitor Control\MonitorControl.exe” off

The other is called “screensaver start” and has target:

C:\Documents and Settings\All Users\Start Menu\Programs\Monitor Control\MonitorControl.exe”

because running the executable with no arguments starts the screensaver.

I think the prototype docs are too brief. Stupidly brief, in fact.

Don’t get me wrong. The docs are generally well formatted and pretty complete. But when it wastes more than a couple of minutes of my time to figure out how to use a specific function, its just a little too brief. Stupidly brief.

Its stupidly brief because someone who already knows how to use it won’t need to refer to it, and someone who doesn’t won’t be able to understand it very quickly without being confused. Stupidly brief.

Element.insert

Yes, yes they beat msdn hands down by using clever looking uri’s like http://prototypejs.org/api/element/insert. This is appreciated. BUT they LOSE to msdn in that this entry in particular is just not good enough.

An example please?

Sheesh.

How to use prototype insert

How to add to the dom using prototype.

The problem with the docs is they’re not mentioning that there’s two classes of functions. There’s the FUNCTIONAL/PROCEDURAL set of classes, then there’s the object oriented approach.

This brief example illustrates the difference.

// include prototype
<script type="text/javascript">

// oo way
// probably preferred way
function goOO()
{

  var newI = new Element( 'i' );
  newI.update('I am the new element');

  // We're inserting INTO the element that has id='paragraph1'
  $('paragraph1').insert ({
        
         'after'  :  // WHERE to insert it.  Can be:
// 'before', 'after', 'top' or 'bottom'
         newI      // this is the item TO insert.

  } ); // closing curly and round braces

// A bit more about 'before', 'after', 'top', 'bottom':
// 'before':  insert newI as the PREVIOUS SIBLING of paragraph1 in the DOM
// 'after':  insert newI as the NEXT SIBLING of paragraph1 in the DOM
// 'top':  insert newI as the FIRST CHILD of paragraph1
// 'bottom':  insert newI as the LAST CHILD of paragraph1


/*
so it goes kind of like this:

$(domref_element_to_insert_after).insert(
  {'INSTRUCTION' : DOMREF_of_stuff_to_insert}
)

Where 'INSTRUCTION' is 'before', 'after', 'top' or 'bottom'

its actually a brilliant api
and remarkably easy to use
with good results.

its a shame the docs SUCK!!

*/
}

// demonstrates how to insert into dom
// using prototype's Element.insert() function.
function goProcedural()
{
  var newI = new Element( 'i' );
  newI.update('I am the new element');

  Element.insert( $('paragraph2'), // element to insert after
   {'after':newI} ); // { 'instruction':__actual content to insert__ }
}
</script>

<body>
  <p id="paragraph1">this is the first paragraph</p>
  <p id="paragraph2">this is the second paragraph</p>

  <input type="button" onclick="goOO();"
  value="go OO insert after paragraph 1" />
  <input type="button" onclick="goProcedural();"
  value="go procedural insert after paragraph 2" />
</body>

I LOVE this video

trisha walsh smith

you must watch it

I read about this game in a book

the game goes like this:

get 2 pennies and two dimes. or two loonies and two toonies. just get any TWO pairs of coins that have different colors.

draw FIVE circles on a page:

o
o
o
o
o

Put the dimes in the top two circles

dime
dime
o
o
o

put the pennies in the bottom two circles

dime
dime
o
penny
penny

NOW, SWAP the positions of the dimes and pennies IN LESS THAN 8 MOVES!!

so in the end, you will have:
penny
penny
o
dime
dime

Its harder than it looks!

so, you’re having problems finding equivalent statements for your mysql sql queries in ms-sql’s t-sql?

well, search no further than microsoft’s very own Transact-SQL Reference (with the root document aptly named “ms189826.aspx” – yeah, real easy to find there, microsoft.)

Anyway, here are some common mysql operations and their t-sql equivalents:

MySQL multiple row insert statement

insert into users
  ( firstname, lastname )
VALUES
  ('bobo', 'bobo'),
  ('john', 'hopkins') ;

T-SQL Multiple row insert statement

-- usual t-sql way is to
-- just write multiple insert
-- statements
insert into users( firstname, lastname )
  VALUES ('bobo', 'bobo') ;

insert into users( firstname, lastname )
  VALUES ('john', 'hopkins') ;

OR (as inspired by pinaldave you can use this weird UNION ALL syntax:

insert into users( firstname, lastname )

SELECT 'bobo', 'bobo'

UNION ALL

SELECT 'john', 'hopkins' ;

Kind of like copying from another table, only not.

Setting the value of an auto_incremented (‘identity’) field in T-SQL

In MySQL, this is easy. If you have a MySQL table with a definition like:

CREATE TABLE users (
  id int primary key not null auto_increment,
  name varchar( 255 ) not null
);

You can always easily specify values for the id column (EVEN THOUGH it is auto_incremented) by just writing MySQL SQL statements like:

insert into users( id, name )
VALUES (1, 'bobo') ;

Now, that doesn’t work in T-SQL. Of course, Microsoft’s version requires you to set some setting, turn some knob, tweak some dial to get the behavior you want.

First of all, the equivalent T-SQL table is:

CREATE TABLE users (
  id int primary key not null identity, -- identity is like mysql's auto_increment
  name varchar( 255 ) not null
);

So if you tried to write a T-SQL statement like:

insert into users( id, name )
VALUES( 1, 'bobo' );

You’d see an error like:


Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table ‘users’ when IDENTITY_INSERT is set to OFF.

Uh, k, so what do we do?

We set IDENTITY_INSERT to ON! Right.

SET IDENTITY_INSERT users ON; -- make it so
-- we can specify actual values for columns
-- in T-SQL table

insert into users( id, name )
VALUES( 1, 'bobo' );

SET IDENTITY_INSERT users OFF; -- turn it off again

byah.

you’d think it’d tell you.

Launching an executable from a Java program on win32 using lines like:

public class TestExecutable {
public static void main( String args[] )
{ 
System.out.println("about to launch javac.exe...");
Runtime rt = Runtime.getRuntime();
Process proc = null;
String cmd;
try
{
  cmd = "C:\\program files\\java\\jdk1.5.0_15\\bin\\javac.exe";
  proc = rt.exec( cmd );

  // now, I want to wait until the compilation of the java program is
  // complete!

  proc.waitFor();  // block until execution is complete
}
catch(Exception e)
{
  System.out.println("whoops...");
  e.printStackTrace();
}

System.out.println("Finish");
}//main
}//class

but it hangs!!

How stupid. Nobody told you that you have to pull anything out of the error stream or else proc.waitFor() will hang forever.

Anyway:

class TestExecutable {
public static void main(String[] args)
{
  System.out.println("about to launch javac.exe...");
  Runtime rt = Runtime.getRuntime();
  Process proc = null;
  String cmd;
  try
  {
    cmd = "C:\\program files\\java\\jdk1.5.0_15\\bin\\javac.exe";
    proc = rt.exec( cmd );

    // now, I want to wait until the compilation 
    // of the java program is complete!
    
    // WAIT!!! waitFor() will HANG IF THERE IS ANYTHING
    // AT ALL IN THE STDERR OUTPUT BUFFER!!
    
    // So, we have to grab the standard error output
    // and check to see if there's anything in it,
    // before we said waitFor().
	    
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isrErr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isrErr);
    String line = null;
        
    while ( (line = br.readLine()) != null)
    {
      System.out.println("Err stream says: " + line);
    }
    proc.waitFor();  // block until execution is complete
  }
  catch(Exception e)
  {
    System.out.println("whoops...");
    e.printStackTrace();
  }

System.out.println("Finish");
}//main
}//class

IT WORKS!!

But wait. I have another program that STILL HANGS WHEN I LAUNCH IT USING Runtime.getRuntime().exec(). WHY???

Because it will hang as long as STDOUT had something to say.

public class TestExecutable{
public static void main(String[] args)
{
  System.out.println("about to launch someprogram.exe...");
  Runtime rt = Runtime.getRuntime();
  Process proc = null;
	  
  try
  {
    cmd = "C:\\program.exe";
    proc = rt.exec( cmd );

    // now, I want to wait until the compilation 
    // of the java program is complete!
	    
    // WAIT!!! waitFor() will HANG IF THERE IS ANYTHING
    // AT ALL IN THE STDERR ___OR___ STDOUT OUTPUT BUFFERS!!!!
	    
    // So, we have to grab the standard error output
    // OR JUST THE PLAIN OLD STANDARD OUT OUTPUT,
    // and check to see if there's anything in it,
    // before we said waitFor().
	    
    // stuff to connect to and read from stderr
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isrErr = new InputStreamReader(stderr);
    BufferedReader brErr = new BufferedReader(isrErr);
	
    // stuff to connect to and read from stdout
    InputStream stdout = proc.getInputStream();
    InputStreamReader isrStd = new InputStreamReader(stdout);
    BufferedReader brStd = new BufferedReader(isrStd);
		
    String line = null;
    if( brErr.ready() )
    {
      // The error stream has something to say!!
      // You had better listen, or proc.waitFor()
      // will hang forever!!!
      while ( (line = brErr.readLine()) != null)
      {
        System.out.println("Err stream says: " + line);
      }
    }
        
    if( brStd.ready() )
    {
      while ( (line = brStd.readLine()) != null)
      {
         System.out.println("stdout says: " + line);
      }
    }
      
     int exitVal = proc.waitFor();    // block until execution is complete
     System.out.println("Process exitValue: " + exitVal);
  }
  catch(Exception e)
  {
    System.out.println("whoops...");
    e.printStackTrace();
  }

  System.out.println("Finish");
}
}

this is still a bad solution

This program will STILL hang if you try to read from stderr or stdout, and NEITHER has anything to say (will hang at readLine())

I think what you want to do is, create a separate thread that polls brStd.ready() and brErr.ready() and pull data from each of those streams if / when there is data available.

Byah. I’ll post something like that later.

In any modern web app, you probably want to have really cool and simple URLs like how WordPress does for your permalinks. E.g., the permalink for this posting is

https://bobobobo.wordpress.com/2008/05/04/how-do-i-design-a-simple-front-controller/

MUCH better than the typical MSDN type urls:

http://msdn.microsoft.com/en-us/library/52cs05fz.aspx
http://msdn.microsoft.com/en-us/library/d06h2x6e.aspx
http://msdn.microsoft.com/en-us/library/bb385954.aspx

Do you think when I complete this posting and publish it, WordPress will ACTUALLY PUT A FILE at https://bobobobo.wordpress.com/2008/05/04/how-do-i-design-a-simple-front-controller/?

NO you dummy!!

Anytime you see REALLY simple urls like http://www.website.com/PersonsUsername/ most likely what is happening there is the web application is using something called REQUEST MAPPING. You do REQUEST MAPPING using what is called a FRONT CONTROLLER.

The FRONT CONTROLLER works to INTERPRET requests for specific URI’s AS requests to OTHER pages, engines, and so on.

Give this a watch.

First, NOTICE how simple that uri is? In case you didn’t follow the link through, its http://cakephp.org/screencasts/view/3.

So CakePHP a front controller to do “request mapping!” WATCH THE VIDEO to get an idea, dude.

ANYWAY, how do you create a really simple front-controller and do request mapping from a Java servlet?

Just create a regular servlet, then make the web.xml entry for it something like this:

<servlet>
  <servlet-name>member</servlet-name>
  <servlet-class>member</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>member</servlet-name>
  <url-pattern>/member/*</url-pattern>
</servlet-mapping>

NOTICE the /member/* for the <url-pattern>? THAT means that ANY requests that come in with the pattern http://www.my.server.com/member/WHATEVER will AUTOMATICALLY be mapped down into the “member” servlet.

So the “member” servlet class might look something like this:

public class member extends HttpServlet
{
  protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    String requestURI = request.getRequestURI();  // if the user hit
    // http://www.my.site.com/member/BOB then the REQUEST URI looks like
    // /member/BOB
    // All I'm going to do now is get everything after the last slash,
    // and that is what will tell me which member profile is desired:
    String desiredUserProfile = requestURI.substring( requestURI.lastIndexOf("/") + 1 );

    // work with desiredUserProfile to produce page output, whatever.
  }
}

Get the idea?

See also:

Java:
http://java.sun.com/blueprints/corej2eepatterns/Patterns/FrontController.html

PHP:
http://www.phpwact.org/pattern/front_controller

Apache Server:

mod_rewrite