Friday, December 10, 2010

Curl pragma

Chris Barber's Zuzu Curl testing package is a sort of Curl goldmine.

Here is one snippet:

{getter public inline {size}:int

  {pragma suppress SyntaxRequiresInteger}
  {return {bit-count self.mask}}
  {pragma unsuppress SyntaxRequiresInteger}
}
There is very little documentation on pragmas in Curl other than the documentation page for pragma in the package CURL.LANGUAGE.PRAGMA

Here is a short exerpt:
This syntax allows the developer to specify directives in the source code to affect the behavior of advanced versions of the Curl IDE that support real-time error checking. Pragmas are ignored by the Curl RTE and have no effect on the runtime behavior of Curl programs.
That snippet is followed by the caveat that pragmas are only processed by the Curl plugin for Eclipse
One use that I think terrific is {pragma info|warning|error message}An example would be
{pragma info FIX_THIS really klunky and hard to test}

But how to keep these out of code commits (let there be no TODO in thy code escrow....) ?

hidden Curl

There are a few places where Curl code is documented as for internal use only*.  This will surely not be the case in open source Curl projects.

There are also some examples of the use of hidden as an access modifier such as this docs entry:
GenericIterator (class)

  hidden abstract GenericIterator
  Package: CURL.IO.STREAM
Another curious example is the parent of HVBox.

LengthBreadthBox (class)

  hidden abstract sealed LengthBreadthBox {inherits SequenceBox}
  Package: CURL.GUI.BASE

The documented 'hidden' is that for the hidden-package accessors in PackageNamespace and the field hiidden? in AliasedNameRef (which is itself internal-use only.)What makes this interesting is that SequenceBox is itself visible.
*example from Curl docs:
 seqnum-generator (field)
protected seqnum-generator:{proc-type {}:int}
Class: TableOptionItem
Package: CURL.GUI.BASE
... This item is unsupported and reserved for internal use.

Beautiful Curl

The Curl language can have a strange beauty: consider that when mixing positional and keyword arguments to a method or procedure that the positions of the former need only be in relative order and that duplicate keyword arguments are permitted.

With access to the Curl AST and the power of Curl macros - and the fact that the  Arguments object is still part of Curl - a fascinating avenue opens for unusual programming paradigms.

Just consider the bug-bear of any Prolog which is the fact that the serial order of clauses and facts is critical and drives the need for cut.  But just imagine the kind of quasi-forward-chaining that can be done by parsing Arguments based on relative positions: remember that the keyword arguments can be in any order and can be duplicated.  Not only that, rest arguments can be given a type at compile time such as anonymous func {proc-type} (but in that case ... may not contain keyword arguments.)

My first experiments are simply

  {clausal goal, 1, clause: procC, clause: procB, 2, clause: procA , asserted-working-mem}

where {clausal} is just
{define-proc {goal:{proc-type}, branch:int, leaf:int, ...}(result:bool, depth:int, breadth:int)
Notice that in my example the rest keyword arg clause: is preceding the positional leaf arg!  There is order relied upon - but it is our order in our code-as-data.

But {define-proc} is itself a Curl macro ... which makes implementing logic in Smalltalk look like really hard work in comparison ...

My convention above is (Goal, [guard-clauses],branch,[clauses],leaf,[clauses],WM)

Anonymous Curl functions close-over their context and are first-class, so I do not explicitly return a solution set.  And of course I can pass in a logic procedure.

What is remarkable is to inspect rest arguments and lo-and-behold there are the multiple keyword arguments.  The convention is that a Curl function cascades to take the last of the duplicate keyword arguments - but now we place our own macro in the body of our clausal proc and proceed to evaluate, parse, ...

Immediately someone says 'But look at the performance hit!'  But if your problem is hard and your solution is elegant, performance will not be the issue - better an answer in 90 seconds or 42 minutes than in 90 centuries or more.

The next nay-sayer: 'But we have a C library that does this!'  And the answer is that we needed a dynamic solution responsive to the user's hunches and advice.  And we wanted a useful, debuggable trace, not a trace that now needs to be parsed and even then may not be useful.  And we want it to be more readable than LISP.

My point is only this: I can get this richness out of the macro {define-proc} itself.  And thankfully Curl 7.0 retained its Arguments class - unlike the fate proposed for Arguments in a harmonized ECMAScript5+ as it moves to its rest arguments convention.  To quote as AS3 author
The catch is to remember that the ...(rest) keyword can be defined only after explicit parameters because required parameters must come before optional ones
Now where had we seen that before ...

Inspecting Global Variables in Pharo Smalltalk 1.1.1

I cannot resist posting this: it creates an interable collection of associations of all current global identifiers and their current types:

"A recipe from Squeak wiki at http://wiki.squeak.org/squeak/1824

Smalltalk keys select:
   [:k | ((Smalltalk at: k) isKindOf: Class) not]
     thenCollect:
        [:k | k -> (Smalltalk at: k) class]


"The code is in SystemDictionary's class comment."

Smalltalk implementations and VM's are evolving - but just compare what has to be done today in other dynamic languages to achieve the same ...

One notable exception is the Io Lobby object.  With a little care, the same result can be very succinct in Rebol 2.7.6. and even simpler in Rebol3.

Here is a node.js shell result on startup:
for (var s in process) { s}
'listeners'
In a Pharo One-Click I get an Array of 127 assocs.

Python does have dir(obj) which is hardly a Smalltalk inspection widget ...

in JavaScript there had been access to the Arguments object for a top-level function callee/caller to get into the activation/call object - But what will that kludge's fate be now that ECMAScript5 is here and Mozilla JavaScript 2.0 is coming?

In all fairness, in Smalltalk and Rebol the unwary traditionally can clobber anything.  But in Smalltalk you can inspect almost anything non-primitive - even during startup. And a bootstrapping JavaScript interpreter written in JavaScript achieves almost the same transparency.  See also: The avocado variant of Lively-Kernel.

see: JavaScript Function.call and Function.apply and ECMAScrip5 Function.prototype.bind

node.js REPL

I do like the node.js REPL.
The classic test is to enter 3 > 2 > 1

But consider this
/opt/curl/surge/8/bin/curl --shell
Entering 3 > 2 >1 gives a much better response.

Curl is an expression-based language - can you name another in which 42 > x > 0 evaluates to a success?

But let's stick to curl for now:  enter the string exit
Now that is a respectable result.  Douglas Crockford, applied science is not a popularity contest.

Simulate loosing your bearings for a moment and enter exit()

Are you convinced that JavaScript variables should always use var?  If so, enter
let answ:int = 42
Note the echo behavior is not annoyig.  To see answ enter answ or {value answ}
To change the value of answ, try
{set answ=65565}
So I such an
ln -s /opt/curl/surge/8/bin/curl xcurl
since the folks as curl.com failed to protect Curl from cURL.

And an icurl.sh gets you your rlwrap xcurl --shell

And to exit the REPL
{exit}
When Crockford talks about the origin of JavaScript and the involvement of SUN, he leaves out a few details.  His audience may not need to know about Self or Strongtalk.
But when Crockford lays out the weaknesses of JavaScript prior to ECMAScript5 he neglects to mention Curl.  Just as he neglects to mention Rebol or Io.  But at a GoogleTechTalk?  Were those talks intended to be misleading? Biased?

I do like JavaScript just as I do like Python (for my own needs.)  But Python is wrong for applications which must be tamper-proofed on the server-side.  Python dynamic objects in that regard are scary.  JavaScript is worse.  And Curl is (for now) absent on the server-side.

As for node.js, Curl has offered event loops in closures since forever.  and for generators, see RolledRandom at curl.com

Tuesday, December 7, 2010

The path to BFG: virtualenv bfgenv and _socket PYTHONHOME PYTHONPATH activate

The BFG python web framework folks pride themselves on their testing - but I can't say the same for virtualenv when installed under Windows.  And in this regard, the BFG web documentation is lacking (compared, say, to WebCore.)

First, the point of virtualenv is to be able to maintain a BFG server on a machine with python26 and python27 and python31  as we transition to python32 and beyond.  So they move a copy of some version of python.exe and pythonw.exe into a Scripts folder.  But they neglect to supply the respective python DLL. So copy that from your PYTHONHOME into that new bfgenv/Scripts directory.

The scripts will not work correctly if you do not first clean up your cmd environment by executing the following at that DOS shell prompt:
set PYTHONPATH=
but even then I have found that for my sanity I need to go into the new /bfgenv/Scripts and edit the activate.bat and deactivate.bat files to preserve and restore my %PYTHONPATH% as well %PYTHONHOME%

One symptom that there is a problem is having an install script complain about not finding a module which imports without problem in your 'normal' python environment.  In my case it was _socket

Sadly, I read advice on mail lists to reinstall Python.  "There must be something wrong with your Python install" as you will see by a web search on virtualenv _socket

Here is a set of steps which will work on Windows XP for Python 2.7 if \python27\Scripts is on your PATH
cd \python27
python ez_setup.py            (note: get this python script off the web for SetupTools)
easy_install virtualenv
set PYTHONPATH=
cd \
virtualenv --no-site-packages bfgenv
cd \bfgenv
Scripts\activate
Scripts\easy_install -i http://dist.repoze.org/bfg/current/simple repoze.bfg
cd Scripts
python test_bfg_port_28686.py   (note: this last is your test file - remember to choose a port)

Suppose PYTHONHOME had been conceived as a string such as
"27*c:\python27;31*i:\python312"
then this would not be an issue - so long as PYTHONPATH was not built by subst of %PYTHONHOME% or $PYTHONHOME

But that ship has sailed.

And take care when in \bfgenv to issue the command as
Scripts\activate.bat
because, like me, you may have more than one activate.bat in your path ... I mean, %PATH%.

Here is a 2009 blog post on using virtualenv: Chris Scott

The WebCore pages suggest using pip. And what could be simpler than
pip install CherryPy
PS
Of course, BFG on linux installed and ran like a charm ...
PPS
Check that %PYTHONHOME%\Scripts is on your PATH

Thursday, December 2, 2010

Curl web content on a CherryPy web server

Here are two snippets from a Python CherryPy web server test run:

    def index(self):
        cherrypy.response.headers['Content-Type'] = 'text/vnd.curl'
        return """{curl 7.0 applet}{br}{paragraph Test CherryPy}{br}"""
                   
    index.exposed = True
  
    def home(self):
        cherrypy.response.headers['Content-Type'] = 'text/vnd.curl'
        return """{curl 7.0 applet}{br}{paragraph Curl Test for CherryPy}{br}"""
  
    home.exposed = True

 It is also possible to specify a path to static Curl files and an index to that directory - in which cases files could appear with .CURL extensions.

In the two cases above, the working URL's are
http://localhost:18787/
http://localhost:18787/index
http://localhost:18787/home
and the Curl content displays as intended in linux (Ubuntu maverick) FireFox.

This test run was done using CherryPy 3.1.2 but it would only run on Python 2.6.6 as of today

The test daemon was launched from a local code folder using
sudo python /usr/local/lib/python2.6/dist-packages/cherrypy/cherryd -c ./curl/site.conf
That ./curl web app folder was modelled on the CherryPy3 scaffold folder in their python module distribution (which also includes a working ./tutorial for HTML content.)

Although I was setting a content-type globally for cherrypy.server I found that I still had to flip the MIME type in the individual 'page' methods as you see above in order to send a response with "text/vnd.curl".
Solution: tool decorator

@cherrypy.tools.response_headers([('Content-Type', 'text/vnd.curl')])
def curlHome(self): { // etcetc
//or
class Root:
  @mimetype("text/vnd.curl")
  def someView(self):
// using
def mimetype(type):
    def decorate(func):
        def wrapper(*args, **kwargs):
            cherrypy.response.headers['Content-Type'] = type
            return func(*args, **kwargs)
        return wrapper
    return decorate
// thanks to 
http://stackoverflow.com/users/11549/ddaa