Tuesday, October 06, 2015

[mLite] Convert to Binary Notation

A short diversion: the Standard ML dialect called mLite is where I go for the intellectual challenge of thinking in a functional programming way. Kudos to Nils M. Holm for developing it. mLite is one of the languages I use to solve RosettaCode tasks, in this case, Binary Digits.

This turned out to be a fairly simple task and only took me a few minutes to solve. Granted, I reused some code from the logarithm calculator of a few postings ago, but that was just for the conversion of a list of numbers to their printable form.
fun binary
   (0, []) = "0"
 | (0, x) = implode ` map (fn x = if int x then chr (x + 48) else x) x
 | (n, b) = binary (n div 2, n mod 2 :: b)
 | n = binary (n, [])
; 
The gist of that is
  • pass in a number and recurse with the number and an empty list.
  • With a number that isn't zero recurse with the number divved by 2 and the list prepended with the number modded by 2.
  • Keep going until the number is zero. At that point, convert the answer's digits to string representation and implode them into a single string.
  • If the number is zero and there are no digits, return "0"
Might get back to some VB6 next. Or javascript.
© Copyright Bruce M. Axtens, 2015

Sunday, October 04, 2015

[VB6] Map and Reduce

Following on from a previous posting about Fluent VB6 we look now at two routines which pop up a lot these days: Map and Reduce. On offer here is one way of implementing these two functional programming stalwarts. They are presented here as part of a FluentVB6 object, but could just as easily be declared and used separately.

I'm implementing these using the
MSScript object which also appeared in the aforementioned posting. This makes available to the programmer, out of the box, the functionality of two scripting languages, VBScript and JScript. Other languages are available within the Windows Scripting Host environment and these could also be used (e.g. PerlScript as per the link.)

The code below tests the Map and Reduce functions. After this the implementation will be discussed.
Dim words As New Collection
    words.Add "cat"
    words.Add "dog"
    words.Add "cow"
    words.Add "wolf"
    words.Add "rat"
    
    Dim F As New FunctionalObject
    
    Dim upperwords As New Collection
    Set upperwords = F.WorkingWith(words).Map("UCase(Value)").AsCollection()
    
    Dim concatenated As Variant
    F.Reset
    concatenated = F.WorkingWith(upperwords).Reduce(vbNullString, "InitValue = InitValue & Value").asValue()
    
    Dim counted As Variant
    counted = F.Reset().WorkingWith(upperwords).Reduce(0, "initValue = initValue + Len(Value)").asValue()
For the sake of simplicity, I'm limiting things to Collections in, Collections and Variants out. The code could be readily changed to handle Arrays, Dictionaries and other data structures.

The class is called FunctionalObject and it begins with
Option Explicit

Private workingCollection As Collection
Private incomingCollection As Collection
Private workingValue As Variant
Private SC As ScriptControl

Private Sub Class_Initialize()
    Set workingCollection = New Collection
    Set incomingCollection = New Collection
    workingValue = vbEmpty
    Set SC = New ScriptControl
End Sub
No surprises there. Again, the ScriptControl object is the OCX added via the Project menu as a Reference rather than as a Component. One could late-bind with CreateObject but there's not much point in this case.

Next the public function to receive the incoming collection
Public Function WorkingWith(inCol As Collection) As FunctionalObject
    Set incomingCollection = inCol
    Set WorkingWith = Me
End Function
Reset clears the workingCollection (in the event that you reuse the currently instantiation of the FunctionalObject rather than instantiate another one.)
Public Function Reset() As FunctionalObject
    Dim i As Integer
    For i = 1 To workingCollection.Count
        workingCollection.Remove 1
    Next
    workingValue = vbEmpty
    Set Reset = Me
End Function
wrapText you'll seen before from the previous posting. It just makes the incoming collection's value palatable to VBScript.
Private Function wrapItem(v As Variant) As String
    If VarType(v) = vbString Then
        wrapItem = Chr$(34) & v & Chr$(34)
    Else
        wrapItem = CStr(v)
    End If
End Function
Next the Map function. The ScriptControl language is set to VBScript and the "safe subset" of script language functions is selected. Then the code iterates through each element of the incoming collection, and sets a VBScript place-holder variable called Value to that element. Next the map script is evaluated in the context of Value, the result being added to the working collection.

The example at the top of page has the map script as "UCase(Value)", so the value stored in the working collection is the uppercase of the value in the incoming collection.
Public Function Map(Optional script As String = "Value") As FunctionalObject
    SC.Language = "VBScript"
    SC.UseSafeSubset = True
    Dim i As Integer
    For i = 1 To incomingCollection.Count
        SC.ExecuteStatement "Value = " & wrapItem(incomingCollection.Item(i))
        workingCollection.Add SC.Eval(script)
    Next
    Set Map = Me
End Function
Reduce works in a similar manner except the result is a variant. There is the expectation that the reduce script will somehow work toward deriving a single value from the incoming collection, thus the use of an second place-holder called InitValue. The first parameter of the Reduce call is stored in InitValue with the expectation that the reduce script will refer to it and to the Value place-holder.

For example, one of the examples from the first code block reads, in part,
Reduce(0, "initValue = initValue + Len(Value)").
This reduces the collection to a value accruing the lengths of the strings assumed to be in the incoming collection.

Both parameters to Reduce are marked as optional. If neither is specified, the Reduce does nothing except set Value to InitValue, effectively filling the working collection with as many zeroes as there are items in the incoming collection.
Public Function Reduce(Optional initval As Variant = 0, Optional script As String = "Value = InitValue") As Variant
    SC.Language = "VBScript"
    SC.UseSafeSubset = True
    Dim vAnswer As Variant
    Dim vItem As Variant
    Dim vResult As Variant
    Dim i As Integer
    SC.ExecuteStatement "InitValue = " & wrapItem(initval)
    For i = 1 To incomingCollection.Count
        vItem = incomingCollection.Item(i)
        SC.ExecuteStatement "Value = " & wrapItem(vItem)
        SC.ExecuteStatement script
    Next
    workingValue = SC.Eval("InitValue")
    Set Reduce = Me
End Function
Finally the two output functions, asCollection and asValue. The former copies the working collection to an answer collection and returns that to the caller. asValue returns the working value from the Reduce.
Public Function AsCollection() As Collection
    Dim answerCollection As New Collection
    Dim i As Integer
    For i = 1 To workingCollection.Count
        answerCollection.Add workingCollection.Item(i)
    Next
    Set AsCollection = answerCollection
End Function

Public Function asValue() As Variant
    asValue = workingValue
End Function
I will make the sources available on Github in the near future.

© Copyright Bruce M. Axtens, 2015

Friday, October 02, 2015

[VB6] What about Me a.k.a. Method Chaining a.k.a. Fluent VB6

This is nothing to do with Shannon Noll's song, What about Me. No, it's about Method Chaining, the mechanism described in Fluent Javascript and making that same mechanism available to the VB6 programmer.

But first, kudos. I am grateful to Vidar Løvbrekke Sømme. On his zbz5.net blog, he posted an article called
Bending Vb6 in the functional direction. In that article, he gives his take on method chaining. What follows is my take on the subject.

Having found a way to get
VB6 running without emulation in 64bit Windows 10, I've been encouraged to get back into it and revisit some of my older projects.

So what's this got to do "What about Me"? Well, the thing that makes method chaining possible in JavaScript is the this keyword. The VB6 equivalent keyword is Me.

The challenge is to create a mechanism which allows something like Vidar's
concatenated = List.From(originalCollection).SelectProperty("Property").Concat(",")

— But this isn't too bad, is it?

What I've done doesn't use Map or Reduce (I have implemented those but differently and I'll deal with both in a subsequent post.)

First, launch the VB6 IDE, create a new project and remove the default form. Next create a class and call it SelectorObject. In the code editor for the class enter class variables, viz
Dim cWorking As Collection
Dim dWorking As Dictionary
Dim aWorking() As Variant
Dim iWorking As Integer
Dim cOriginal As Collection
Dim dOriginal As Dictionary
Dim aOriginal() As Variant
Dim sPattern As String
Dim bPatternDefined As Boolean
Dim oScript As ScriptControl

Private Enum FROMS
    FromCollection = 1
    FromDictionary = 2
    FromArray = 3
    Fromstring = 4
End Enum

Dim source As FROMS
The above is out of my own project so there's extra stuff in there that goes beyond Vidar's original. Ultimately I'd like to be able to hand a Collection, Dictionary, Array or String to the class and be able to pull out of it a Collection, Dictionary, Array or String. The code you'll see is part way to realising that.

Notice also the Dim oScript As ScriptControl. To make an element selection mechanism, I'm calling in the
MSScript OCX object (as a Project Reference).

Next comes the class initialisation
Private Sub Class_Initialize()
    Set cWorking = New Collection
    Set dWorking = New Dictionary
    sPattern = vbNullString
    bPatternDefined = False
    iWorking = -1
    Set oScript = New ScriptControl
    oScript.Language = "VBScript"
    oScript.UseSafeSubset = True
End Sub
Next the first public function Selecting which will introduce the selection statement. I'd love to be able to use Select, but that's a VB6 reserved word. Notice the use of the Me keyword. Because it's an object, it has to be assigned to the function name (as a return value) using Set.
Public Function Selecting() As SelectorObject
    Set Selecting = Me
End Function
Next the From public function. This ascertains the type of the incoming variable and assigns it to a relevant worker object. An enum takes care of letting the class know what was passed in.
Public Function From(c As Variant) As SelectorObject
    If TypeName(c) = "Collection" Then
        Set cOriginal = c
        source = FromCollection
    ElseIf TypeName(c) = "Dictionary" Then
        Set dOriginal = c
        source = FromDictionary
    Else
        If VarType(c) = vbArray Then
            aOriginal = c
            source = FromArray
        Else
            aOriginal = Split(c, "")
            source = Fromstring
        End If
    End If
    Set From = Me
End Function
Next comes the Where function. Rather that doing any further processing, the Where simply accepts the 'where' text (a script fragment for MSScript to use later) and a flag to say we have it is set.
Public Function Where(pattern As String) As SelectorObject
    sPattern = pattern
    bPatternDefined = True
    Set Where = Me
End Function
Next a helper function which puts double quotes around strings and leaves other data types undecorated. This exists because the current element in the Collection/Dictionary/Array/String is assigned to a VBScript variable before the Where script is evaluated. Being a VBScript assignment statement, double quotes need to be around strings. At this point there is no special handling for booleans and dates etc.
Private Function WrapData(data As Variant) As String
    If VarType(data) = vbString Then
        WrapData = Chr$(34) & data & Chr$(34)
    Else
        WrapData = CStr(data)
    End If
End Function
Finally, one of the three output routines. This is where all the hard work is done. Notice that these functions don't specify SelectorObject as the return type. In this first case, a Collection is returned. The Dictionary output routine has not been written.

Notice also that, if a Where clause has been specified, the current item is set as a variable to the MSScript engine, and then the 'where' text is evaluated by MSScript, using the VBScript language. The result is interpreted as a boolean to decide whether or not to include the current item in the output collection. Otherwise, everything that went in comes out.
Public Function asCollection() As Collection
    Dim i As Integer
    Dim b As Boolean
    For i = 1 To cOriginal.Count
        If bPatternDefined Then
            oScript.ExecuteStatement "Value = " & WrapData(cOriginal.Item(i))
            b = CBool(oScript.Eval(sPattern))
            If b Then
                cWorking.Add cOriginal.Item(i)
            End If
        Else
            cWorking.Add cOriginal.Item(i)
        End If
    Next
    Set asCollection = cWorking
End Function
Next, a string output routine, with an optional argument to supply an inter-item separator.
Public Function asStringSeparatedBy(Optional separator As String = vbNullString) As String
    Dim i As Integer
    Dim b As Boolean
    Dim answer As String
    For i = 1 To cOriginal.Count
        If bPatternDefined Then
            oScript.ExecuteStatement "Value = " & WrapData(cOriginal.Item(i))
            b = CBool(oScript.Eval(sPattern))
            If b Then
                answer = answer & cOriginal.Item(i)
                If i < cOriginal.Count Then
                    answer = answer & separator
                End If
            End If
        Else
            cWorking.Add cOriginal.Item(i)
            If i < cOriginal.Count Then
                answer = answer & separator
            End If
        End If
    Next
    
    If bPatternDefined And Right$(answer, 1) = separator Then
        answer = Mid$(answer, 1, Len(answer) - 1)
    End If
    
    asStringSeparatedBy = answer
End Function
And finally, an output routine returning an array. The array element variable, iWorking, was initialised as -1, thus the pre-increment. Perhaps something else could be done about array initialisation to make things more efficient than a ReDim Preserve for each element.
Public Function asArray() As Variant
    Dim i As Integer
    Dim b As Boolean
    For i = 1 To cOriginal.Count
        If bPatternDefined Then
            oScript.ExecuteStatement "Value = " & WrapData(cOriginal.Item(i))
            b = CBool(oScript.Eval(sPattern))
            If b Then
                iWorking = iWorking + 1
                ReDim Preserve aWorking(iWorking)
                aWorking(iWorking) = cOriginal.Item(i)
            End If
        Else
            iWorking = iWorking + 1
            ReDim Preserve aWorking(iWorking)
            aWorking(iWorking) = cOriginal.Item(i)
        End If
    Next
    asArray = aWorking
End Function
That's all that's currently in the SelectorObject.

Now, out in the main module, in the Main subroutine, a couple of tests.
Dim words As New Collection
    words.Add "cat"
    words.Add "dog"
    words.Add "cow"
    words.Add "wolf"
    words.Add "rat"

    Dim S As New SelectorObject

    Debug.Print S.Selecting().From(words).Where("instr(Value,""o"") > 0").asStringSeparatedBy(",")
    Debug.Print Join(S.Selecting().From(words).Where("instr(Value,""a"") > 0").asArray(), "|")
The output being
dog,cow,wolf
cat|rat
So that's my take on Fluent VB6.

In my experimentations I have used this technique to re-implement Google Adwords SOAP request code that I originally wrote in JScript, viz
Dim pred As String
    Dim sele As String
    Dim campaignID As Long
    campaignID = 1000222

    Dim OPE As New OperationObject
    Dim PRE As New PredicateObject
    Dim SEL As New SelectObject
 
    pred = PRE.Field("CampaignId").Operator("=").Value(campaignID).toXML()
    sele = SEL.Fields("BudgetId").Fields("Amount").Predicates(pred).toXML()
    'sele = SEL.Fields("BudgetId").Fields("Amount").Predicates(PRE.Field("CampaignId").Operator("=").Value(campaignID).toXML()).toXML()

    Dim bid As Long
    bid = 2199199
    Dim amt As Long
    amt = 1000000
    Dim oper As String
    oper = OPE.Operator("SET").Field("budgetId").Value(bid).Amount(amt).toXML()

    Debug.Print pred
    Debug.Print sele
    Debug.Print oper
outputting
<field>CampaignId</field><operator>EQUALS</operator><values>1000222</values>
 <fields>BudgetId</fields><fields>Amount</fields><predicates><field>CampaignId</field><operator>EQUALS</operator><values>1000222</values></predicates>
 <operations><operator>SET</operator><operand><budgetId>2199199</budgetId><amount><microAmount>1000000</microAmount></amount></operand></operations>
Okay, that's it. A long-winded posting, this one. If you have any questions, use the comments.

Enjoy!


© Copyright Bruce M. Axtens, 2015

Monday, September 28, 2015

[JScript] jQuery without IE

For those who looked, this is mod of plasticgrammer's post. Most of the comments are Google Translates attempts at the original programmer's Japanese.

The single biggest difference from the previous posting is that Internet Explorer is not called into to manage jQuery. Instead the htmlfile object is used.

jQuery expects a few global symbols (it is after all a browser library), so the beginning of the code declares them: document, window etc. Then the jQuery file is dragged across the internet and eval'd in the context of the script.

You'll notice that the jQuery version is quite ancient. This is another problem with this approach. I imagine that it's just a case of declaring some more public symbols. If anyone tries this, please let me know how recent you can go before things break. And if you succeed in using more recent jQuery libraries, please do let me know what modifications were required.
// To prepare, such as window or document to the global name space
(function (url) {
  if ("undefined" === typeof document)
    document = new ActiveXObject("htmlfile");
  document.write("<" + "html" + ">" + "<" + "/html>"); // this important
  if ("undefined" === typeof window)
    window = document.parentWindow;
  if ("undefined" === typeof alert)
    alert = function (s) {
      return window.alert(s);
    };
  if ("undefined" === typeof confirm)
    confirm = function (s) {
      return window.confirm(s)
    };
  if ("undefined" === typeof location)
    location = window.location;
  if ("undefined" === typeof navigator)
    navigator = window.navigator;
  if ("undefined" === typeof window.ActiveXObject)
    window.ActiveXObject = ActiveXObject;

  var XMLHttpRequest = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
  var o = XMLHttpRequest.open("GET", url, false);
  var s = XMLHttpRequest.send();
  eval(XMLHttpRequest.ResponseText);
  return true;
})("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js");
Now a bit of demo code. Notice how we tell JScript what $ means. Possibly that could go in the earlier block of code as yet another global.
var $ = window.$;

// Operation example of a simple jQuery object
WScript.Echo($("<" + "div" + ">").attr("a", "fo").get(0).outerHTML);

// Course alert even I can use.
alert($("<" + "div" + ">").attr("a", "fo").get(0).outerHTML);
(Blogspot didn't like seeing div etc as markup, thus the odd syntax).

© Copyright Bruce M. Axtens, 2015

[JScript] Using jQuery in IE

IE is the browser we all love to hate. It's also scriptable and so inevitably ends up being considered for various tasks.

The following fragment demonstrates the first of two mechanisms I've found for instantiating jQuery in an IE session under script control.
var oIE;
  try {
    oIE = new ActiveXObject("InternetExplorer.Application");
  } catch (errIE) {
    WScript.Quit();
  }
  oIE.Visible = false;

  oIE.Navigate("http://www.example.com");
  while (oIE.Busy) {
    WScript.Sleep(100);
  }

  WScript.Sleep(1000); // could be less

  var DOM = oIE.Document;
  var scr = DOM.createElement('script');
  scr.src = "https://code.jquery.com/jquery-2.1.4.min.js";
  DOM.head.appendChild(scr);

  var $ = DOM.parentWindow.jQuery;
The above code is sliced out of a current project. We navigate to the target, create a script tag, point it at jquery's CDN, and append it to the document's head. Then we define a $ to point to oIE.Document.parentWindow.jQuery.

The same technique can be applied to any page, really. I have a bookmark in my browser that has a name of InjectjQuery and an address of
javascript:var script = document.createElement('script');script.src = "https://code.jquery.com/jquery-2.1.4.min.js"; document.head.appendChild(script);

The second method for instantiating jQuery in IE can be found at plasticgrammer. I had difficulty with it, but got it working. It has some good things which I'll discuss in the next posting.

© Copyright Bruce M. Axtens, 2015

Sunday, September 27, 2015

[VB6] Installation in Windows 10

I'm running Windows 10 Home, 64bit. We have legacy code that needs to be modified and recompiled. Folk who find such discussions unpalatable should read no further.

I found help for this process in two places:Forty Pound Head's
Install VB6 on Windows 8 and CodeProject's How to install Visual Studio 6 on Windows 7 professional 64bit

(There's another blurb at
SoftwareOK that I'm hanging on to just in case I meet any unforseen gotchas.)

In my case, the creation of the zero length file, MSJAVA.DLL, had to be done in C:\Windows\System32 rather than C:\Windows. I had put it in the latter and ended up with, for a while, the looping install scenario described by fortypoundhead.

The recommendation
Ensure Data access components is deselected. If it's not deselected, setup will hang!

— fortypoundhead

was interesting because the Enterprise installer asserted that the data access tools are required. However, I went with the recommendation as the thought of a hanging setup didn't appeal.

I turned off SourceSafe, FoxPro and InterDev as well. I opted to have environment vars stored in VCVARS32.BAT rather than have them registered: I feared mayhem might occur given the pre-existing Visual Studio Community 2013 and Community 2015 installs.

The install was very speedy.

The installer insisted on a reboot at the end. But before I said yes to that, I set the relevant Compatibility Settings for VB6.EXE as per fortypoundhead, started VB6.EXE, wrote a quick button on a form app, compiled it to EXE and then ran it from outside VB6. No problems at all!

Now I will have to run the various updaters and install some helper apps. But so far it looks like we could get another 17 years out of VB6.


© Copyright Bruce M. Axtens, 2015

Saturday, September 26, 2015

[mLite] Arbitrary Precision Integers and Logarithms

Yeah yeah, there's something 'bout you baby I like

-- Status Quo, 1981.

It's a bit worrisome when I quote musicians from last century, but I do like mLite. Granted, I don't dream about it, but it's fun to figure out how to do things in a functional way.

In this case I was wanting to solve the RosettaCode challenge
Arbitrary-precision integers (included) which has one calculate 5^4^3^2, find out how many digits there are and then display the top 20 digits and bottom 20 digits. Bignums weren't a challenge, as they are supported natively in mLite. No, the biggest challenge was figuring out how many digits. 5^4^3^2 is an extremely large number, with 183231 digits and all of my first attempts did not complete even after running for a day.

mLite's creator,
Nils M. Holm, suggested I use logarithms. However, logarithms aren't built in to mLite yet, so I had to cook up my own logarithm library. So how do you calculate logarithms by hand? I dug around a bit and found an article on Quora entitled How can we calculate the logarithms by hand without using any calculator?. Harald Overbeek's description formed the basis for the mLite code below.
fun ntol (0, x) = if len x < 1 then [0] else x
       | (n, x) = ntol (n div 10, (n mod 10) :: x)
       | n      = ntol (n, [])
;
ntol converts a number to a list.
fun powers_of_10 9 = 1000000000
               | 8 = 100000000
               | 7 = 10000000
               | 6 = 1000000
               | 5 = 100000
               | 4 = 10000
               | 3 = 1000
               | 2 = 100
               | 1 = 10
               | 0 = 1
;
powers_of_10 is a precomputation of all the powers I knew I'd encounter during the calculation. This alone sped up the code a lot.
fun size (c, 0) = c
       | (c, n > 9999999999) = size (c + 10, trunc (n / 10000000000))
       | (c, n)              = size (c +  1, trunc (n / 10))
       | n                   = size (     0, trunc (n / 10))
;
size works out the number of digits by keeping track of how many calculations it takes to divide the number by 10 until the remainder is zero.
fun makeVisible L = map (fn x = if int x then chr (x + 48) else x) L
makeVisible turns an array of digits into a string, with handling for non-numeric elements
fun log10 (n, 0, x) = ston  implode  makeVisible ` rev x
        | (n, decimals, x) =
            let val n' = n^10;
              val size_n' = size n'
            in 
              log10 (n' / powers_of_10 size_n', decimals - 1, size_n' :: x)
   end
        | (n, decimals) =
            let
              val size_n = size n
            in
              log10 (n / 10^size_n, decimals, #"." :: rev (ntol size_n) @ [])
            end
;
Then log10 ties it all together. The second parameter specifies the number of digits precision. Below I've specified 6.

Being somewhat mathematically challenged, I still had to figure out how to use the library I had made to calculate the digits. Thankfully, there's a
mathematics community on StackExchange. They helped me out a lot. Now I could work out the number of digits in the number by rounding up the result of log10(5) * 4^9 (seeing as 3^2 is 9).

Thus I ended up with
val fourThreeTwo = 4^3^2;
val fiveFourThreeTwo = 5^fourThreeTwo;

val digitCount = trunc (log10(5,6) * fourThreeTwo + 0.5);
print "Count  = "; println digitCount;

val end20 = fiveFourThreeTwo mod (10^20);
print "End 20 = "; println end20;

val top20 = fiveFourThreeTwo div (10^(digitCount - 20)); 
print "Top 20 = "; println top20;
Which, after 1 hour and 9 minutes on an AMD A6 cpu, gave
>mlite -f 5p4p3p2.m
 Count = 183231
 End 20 = 92256259918212890625
 Top 20 = 62060698786608744707 
A nice change from my day job which centres around JavaScript, Peloton, HTML, PHP and the odd bit of T-SQL. Enjoy!

© Copyright Bruce M. Axtens, 2015

Monday, September 21, 2015

[Sound] Using SOX to convert WAV to MP3

I was sent a rather large WAV file today: a delightful composition by Ivodne Galatea called 'Ingenious Pursuits'. She's also sent me the score so I can learn to play it myself.

At 91MB I thought I might have a go at converting the WAV to MP3. Enter
Sound eXchange which very comfortably converted the WAV using the following extremely simple command:
sox "Ingeniuous Pursuits automated.wav" Ingeniuous.mp3
SoX can do way more than this with sound files. The above barely scratches the surface of the amazing power of this tool.

Having said that, the Windows installer did not include a copy of the LAME (Lame Aint an MP3 Encoder) DLL (libmp3lame.dll). I had to go hunting for that and even when I found it I had to rename it, as every ZIP I downloaded called the dll lame_enc.dll (I found downloads at
spaghetticode.org and buanzo.org). After that everything worked fine.

SoX is great. Highly recommended. I don't know the author and no one paid me to write this.


© Copyright Bruce M. Axtens, 2015

Friday, September 18, 2015

[CMD] PUSHD to path in clipboard

I use WinClip to get things in and out of the clipboard when doing stuff on the command line. (I grew up on CP/M, MP/M II and VAX VMS, so command line is usually where it's at for me.)

Occasionally, I have a path in the clipboard that I want to use as the target for a CD (or, more often, a PUSHD). I just cooked up the following .CMD script using WinClip. It uses the /F qualifier on the FOR command to iterate through the stdout of winclip -p and PUSHD to what it finds.

So what happens, you may ask, if the clipboard contains more than one line? If the paths are fully qualified then you end up in the folder defined by the last line. Otherwise, you end up in the folder defined by the first line and you see a pile of error messages about not being able to find the subsequent folders.
@echo off
 :: PUSHCLIP.CMD
 for /f "delims==" %%f in ('winclip -p') do pushd %%f
Enjoy! If you want to amplify the script to better handle unforeseen inputs, go right ahead. Share the result here if you feel so inclined.

© Copyright Bruce M. Axtens, 2015

Thursday, September 17, 2015

[JavaScript] SQLServer Date to jsDateTime

I forgot to include in the last posting the reverse function that takes a SQLServer Epoch value and converts it to a JavaScript datetime number.
function SQLServerDateTojsDateTime(a) {
  return Math.ceil((a * 86400 - 2208988800) * 1000);
 }
An example of its use (from a jscli session):
> d = new Date()
 Thu Sep 17 12:03:58 UTC+0800 2015
 > d.valueOf()
 1442462638627
 > n = jsDateTimeToSQLServerDateTime(d)
 42262.169428553236
 > m = SQLServerDateTojsDateTime(n)
 1442462638627
 > new Date(m)
 Thu Sep 17 12:03:58 UTC+0800 2015
Enjoy!

© Copyright Bruce M. Axtens, 2015

Wednesday, September 16, 2015

[JavaScript] Converting JavaScript DateTime to SQLServer DateTime

I've had the need occasionally to convert JavaScript datetime to SQLServer datetime numeric Epoch value. The following two routines do the job. In both cases I'm assuming that UTC is being used as taking timezones into consideration is a bit more work.

First jsDateTimeToSQLServerDate which takes a JavaScript Date object and forms a SQLServer Epoch integer.

   function jsDateTimeToSQLServerDate(d) {

      var SQLServerEpoch = 2208988800;
      var dMilli = d.valueOf();
      var dSec = dMilli / 1000;
      var nEpoch = SQLServerEpoch + dSec;
      var nEpochDays = nEpoch / 86400;
      var nEpochDate = Math.ceil(nEpochDays);
      return nEpochDate;
    }
The second also takes a JavaScript Date object but this time includes the time returning an Epoch floating point number.
   function jsDateTimeToSQLServerDateTime(d) {
      var SQLServerEpoch = 2208988800;
      var dMilli = d.valueOf();
      var dSec = dMilli / 1000;
      var nEpoch = SQLServerEpoch + dSec;
      var nEpochDays = nEpoch / 86400;
      var nEpochDate = Math.ceil(nEpochDays);
      return nEpochDays;
    }
The Closure compiler abbreviates those routines signficantly, as below. You may want to use this code in preference as the above was done to demonstrate the relationships in the conversion process.
   function jsDateTimeToSQLServerDate(a) {
      return Math.ceil((2208988800 + a.valueOf() / 1E3) / 86400);
    }
    function jsDateTimeToSQLServerDateTime(a) {
      a = (2208988800 + a.valueOf() / 1E3) / 86400;
      Math.ceil(a);
      return a;
    }
    ;
An example invocation:
   var now = new Date();
    // now currently
    // Wed Sep 16 22:52:09 UTC+0800 2015
    jsDateTimeToSQLServerDate(now);
    // gives
    // 42262
    jsDateTimeToSQLServerDateTime(now);
    // gives
    // 42261.61955061343
I hope this helps. I may be back here myself next time I need this routine.

© Copyright Bruce M. Axtens, 2015

[PHP] Spread camel case

My work has me doing Wordpress plugins from time to time. The following snippets comes from one of those projects. It's text a camel-case string and inserts spaces in front of capitals and numbers, turning the item into some more human-readable.
function spreadCamel($txt) 
 {
  $temp = substr($txt,0,1);
  for ($i = 1; $i < strlen($txt); $i++) {
   $c = substr($txt, $i, 1);
   if (ctype_upper($c) || ctype_digit($c)) {
    $temp = $temp . " ";
   }
   $temp = $temp . $c;
  }
  return $temp;
 } 
An example invocation:
echo spreadCamel("MyDogHasFleasAbout1Million");
the result of that being
My Dog Has Fleas About 1 Million
I hope that helps someone. There may be a better/faster/more efficient way of doing it. If there is, please post in the comments.

© Copyright Bruce M. Axtens, 2015

Wednesday, October 29, 2014

[mLite] 99 bottles of beer

99 bottles of beer is often the first thing I try to do in a (new for me) programming language. Here is an mLite implementation (which can also be found now on RosettaCode.)
val NL = implode [#"newline"]

fun itone 1 = "it" 
        | n = "one"

fun plural (s, 0) = ("no " @ s @ "s") 
                    | (s, 1) = ("1 " @ s) 
                    | (s, n) = (ntos n @ " " @ s @ "s")

fun verse 0 = "no bottles of beer on the wall" @ NL @ 
              "no bottles of beer" @ NL @ 
              "go to the store and buy some more" @ NL @ 
              "99 bottles of beer on the wall" @ NL @ NL 
        | x = plural ("bottle",x) @ " of beer on the wall" @ NL @ 
              plural ("bottle",x) @ " of beer" @ NL @ 
              "take " @ (itone x) @ " down and pass it round" @ NL @ 
              plural ("bottle", (x-1)) @ " of beer on the wall" @ NL @ NL

fun bottles x = map (print o verse) (rev (0 :: iota (1, x)))

fun default (false, y) = y | (x, _) = x

;
bottles (ston (default (argv 0, "99")))
This code allows one to specify how many bottles on the command line (e.g.
mlite -f 99bob.m 4
), defaulting to the usual 99.

© Copyright Bruce M. Axtens, 2014

Tuesday, October 28, 2014

[mLite] Learning an ML dialect

I've tried to get my head into functional languages for some time. This time I'm having a go at mLite, which the author, Nils M Holm, describes as "a lightweight (and slightly odd) inhabitant of the ML universe ... Much like ML, but with dynamic typingguards, and a Haskell-style apply operator."

I've created a presence on RosettaCode for mLite and solved the Ackermann function challenge.

© Bruce M. Axtens, 2014.

Saturday, March 08, 2014

[TCL] Love that Tool Command Language

TCL is just so cool and concise …
cd CSV
set target "snap-[clock format [clock add [clock seconds] -1 hours] -format %Y-%m-%d-%H -gmt 1]"
if {![file exists $target.rar]} then {
    set cmd [list c:/program\ files/winrar/rar.exe m -m5 -s ${target}.rar ${target}-utc.csv]
        exec -- {*}$cmd
}
That goes to the log (called CSV) folder and compresses the previous hour’s worth of log. I run that from a scheduler.

I really like the conciseness of Tcl: clock add [clock seconds] -1 hours, which subtracts an hour from the current time and clock format which takes that and renders it as GMT.

© Copyright Bruce M. Axtens, 2014

Thursday, February 27, 2014

[VBScript] Boosting myself to HIGH process priority

The script gets its own name, then looks through the Win32_Processes for a match with CSCRIPT.EXE and a CommandLine containing that name. Any matches (should be only one, but could be more) are boosted to HIGH process priority.

This demonstrates WMI calls from both VBScript and JScript. Note the need to explicitly define an Enumerator in the JScript version.
Option Explicit

Dim sName
Dim sComputer
Dim oWMI
Dim cProcesses
Dim oProcess

Const HIGH = 256
sComputer = "."
Set oWMI = GetObject("winmgmts:\\" & sComputer & "\root\cimv2")
sName = WScript.ScriptName

Set cProcesses = oWMI.ExecQuery("Select * from Win32_Process Where Name = 'cscript.exe' And CommandLine LIKE '%" & sName & "%'")
For Each oProcess In cProcesses
  oProcess.SetPriority(HIGH) 
  WScript.Echo "Boosted myself"
Next
And in JScript
var HIGH = 256;
var sComputer = ".";
var sName = WScript.ScriptName;    

var query = GetObject("winmgmts:\\\\" + sComputer + "\\root\\cimv2")
    .ExecQuery("Select * from Win32_Process " + 
    "Where Name = 'cscript.exe' And CommandLine LIKE '%" + sName + "%'")

// Enumerate WMI objects
var cProcesses = new Enumerator(query);

for ( ; !cProcesses.atEnd(); cProcesses.moveNext()) { 
    var oProcess = cProcesses.item()
    oProcess.Priority = HIGH
    WScript.Echo( "Boosted myself")
}
© Copyright Bruce M. Axtens, 2014

Tuesday, February 25, 2014

[VBScript] How can I display 64 bit double number using VBScript on 32 Bit OS?

"How can I display 64 bit double number using VBScript on 32 Bit OS?" That was the question on StackOverflow back at the end of 2012. And nobody had answered it. What a challenge!

I assumed a pure-VBScript solution was needed, and set about finding and implementing a Very Large Integer class with which I could then implement a Hex64 to integer function. A workable candidate function was found on Rosetta Code in the
Liberty BASIC solution to the Long Multiplication task.

The code for the class is as follows. It's pretty much the same as the original.

Option Explicit
Class VeryLongInteger
  'http://rosettacode.org/wiki/Long_Multiplication#Liberty_BASIC
  Public Function MULTIPLY(Str_A, Str_B)
    Dim signA, signB, sResult, Str_Shift, i, d, Str_T
    signA = 1
    If Left(Str_A,1) = "-" Then 
      Str_A = Mid(Str_A,2)
      signA = -1
    End If
    signB = 1
    If Left(Str_B,1) = "-" Then 
      Str_B = Mid(Str_B,2)
      signB = -1
    End If
    sResult = vbNullString
    Str_T = vbNullString
    Str_shift = vbNullString
    For i = Len(Str_A) To 1 Step -1
      d = CInt(Mid(Str_A,i,1))
      Str_T = MULTBYDIGIT(Str_B, d)
      sResult = ADD(sResult, Str_T & Str_shift)
      Str_shift = Str_shift & "0"
      'print d, Str_T, sResult 
    Next
    If signA * signB < 0 Then sResult = "-" + sResult
    'print sResult
    MULTIPLY = sResult
  End Function
  
  Private Function MULTBYDIGIT(Str_A, d)
    Dim sResult, carry, i, a, c
    'multiply Str_A by digit d
    sResult = vbNullString
    carry = 0
    For i = Len(Str_A) To 1 Step -1
      a = CInt(Mid(Str_A,i,1))
      c = a * d + carry
      carry = c \ 10
      c = c Mod 10
      'print a, c
      sResult = CStr(c) & sResult 
    Next
    If carry > 0 Then sResult = CStr(carry) & sResult
    'print sResult
    MULTBYDIGIT = sResult
  End Function
  
  Public Function ADD(Str_A, Str_B)
    Dim L, sResult, carry, i, a, b, c
    'add Str_A + Str_B, for now only positive
    l = MAX(Len(Str_A), Len(Str_B))
    Str_A=PAD(Str_A,l)
    Str_B=PAD(Str_B,l)
    sResult = vbNullString 'result
    carry = 0
    For i = l To 1 Step -1
      a = CInt(Mid(Str_A,i,1))
      b = CInt(Mid(Str_B,i,1))
      c = a + b + carry
      carry = Int(c/10)
      c = c Mod 10
      'print a, b, c
      sResult = CStr(c) & sResult
    Next
    If carry>0 Then sResult = CStr(carry) & sResult
    'print sResult
    ADD = sResult
  End Function
  
  Private Function Max(a,b)
    If a > b Then
      Max = a
    Else
      Max = b
    End If
  End Function
  
  Private Function pad(a,n)  'pad from right with 0 to length n
    Dim sResult
    sResult = a
    While Len(sResult) < n
      sResult = "0" & sResult
    Wend
    pad = sResult
  End Function
End Class
With that defined I have now all I need to implement a Hex64 function. This I did in two forms:

* A memoized version which precomputes all the relevant powers of 16

Function PrecomputedFromHex64(sHex)
  Dim VLI
  Set VLI = New VeryLongInteger
  
  Dim Sixteen(16)
  Sixteen(0) = "1"
  Sixteen(1) = "16"
  Sixteen(2) = VLI.MULTIPLY(Sixteen(1),"16")
  Sixteen(3) = VLI.MULTIPLY(Sixteen(2),"16")
  Sixteen(4) = VLI.MULTIPLY(Sixteen(3),"16")
  Sixteen(5) = VLI.MULTIPLY(Sixteen(4),"16")
  Sixteen(6) = VLI.MULTIPLY(Sixteen(5),"16")
  Sixteen(7) = VLI.MULTIPLY(Sixteen(6),"16")
  Sixteen(8) = VLI.MULTIPLY(Sixteen(7),"16")
  Sixteen(9) = VLI.MULTIPLY(Sixteen(8),"16")
  Sixteen(10) = VLI.MULTIPLY(Sixteen(9),"16")
  Sixteen(11) = VLI.MULTIPLY(Sixteen(10),"16")
  Sixteen(12) = VLI.MULTIPLY(Sixteen(11),"16")
  Sixteen(13) = VLI.MULTIPLY(Sixteen(12),"16")
  Sixteen(14) = VLI.MULTIPLY(Sixteen(13),"16")
  Sixteen(15) = VLI.MULTIPLY(Sixteen(14),"16")
  
  Dim theAnswer, i, theDigit, theMultiplier, thePower, aPower
  theAnswer = "0"
  aPower = 0
  For i = Len(sHex) To 1 Step -1
    theDigit = UCase(Mid(sHex,i,1))
    theMultiplier = InStr("0123456789ABCDEF",theDigit)-1
    thePower = Sixteen(aPower)
    thePower = VLI.MULTIPLY(CStr(theMultiplier),thePower)
    theAnswer = VLI.ADD(theAnswer,thePower )
    aPower = aPower + 1
  Next
  PrecomputedFromHex64 = theAnswer
End Function
* A non-memoized version which computes the relevant power when it is needed.
Function FromHex64(sHex)
  Dim VLI
  Set VLI = New VeryLongInteger       
  Dim theAnswer, i, theDigit, theMultiplier, thePower, aPower
  theAnswer = "0"
  thePower = "1"
  For i = Len(sHex) To 1 Step -1
    theDigit = UCase(Mid(sHex,i,1))
    theMultiplier = InStr("0123456789ABCDEF",theDigit)-1
    theAnswer = VLI.ADD(theAnswer,VLI.MULTIPLY(thePower,theMultiplier))
    thePower = VLI.MULTIPLY(thePower,"16")
  Next
  FromHex64 = theAnswer
End Function
The memoized version is slightly faster than the non-memoized, despite the overhead of the memoization. If the class/function pair were to be used a lot in a script, one might consider making both the VLI instantiation and the Sixteen() array global and precomputing the array at the beginning of the script rather than on each invocation.

A rough test of the code follows:

Const test = "FFFFFFFFFFFFFFFF" '"41417724EBA8953E"
Dim t, I, S
t=Timer
For I = 1 To 100
  S = FromHex64(test)
Next
WScript.Echo "No memoization", Timer-t

t=Timer
For I = 1 To 100
  S = PrecomputedFromHex64(test)
Next
WScript.Echo "Memoized each time",Timer-t

Function GlobalMemoFromHex64(sHex)  
  Dim theAnswer, i, theDigit, theMultiplier, thePower, aPower
  theAnswer = "0"
  aPower = 0
  For i = Len(sHex) To 1 Step -1
    theDigit = UCase(Mid(sHex,i,1))
    theMultiplier = InStr("0123456789ABCDEF",theDigit)-1
    thePower = Sixteen(aPower)
    thePower = VLI.MULTIPLY(CStr(theMultiplier),thePower)
    theAnswer = VLI.ADD(theAnswer,thePower )
    aPower = aPower + 1
  Next
  GlobalMemoFromHex64 = theAnswer
End Function

Dim VLI
Set VLI = New VeryLongInteger

Dim Sixteen(16)
Sixteen(0) = "1"
Sixteen(1) = "16"
Sixteen(2) = VLI.MULTIPLY(Sixteen(1),"16")
Sixteen(3) = VLI.MULTIPLY(Sixteen(2),"16")
Sixteen(4) = VLI.MULTIPLY(Sixteen(3),"16")
Sixteen(5) = VLI.MULTIPLY(Sixteen(4),"16")
Sixteen(6) = VLI.MULTIPLY(Sixteen(5),"16")
Sixteen(7) = VLI.MULTIPLY(Sixteen(6),"16")
Sixteen(8) = VLI.MULTIPLY(Sixteen(7),"16")
Sixteen(9) = VLI.MULTIPLY(Sixteen(8),"16")
Sixteen(10) = VLI.MULTIPLY(Sixteen(9),"16")
Sixteen(11) = VLI.MULTIPLY(Sixteen(10),"16")
Sixteen(12) = VLI.MULTIPLY(Sixteen(11),"16")
Sixteen(13) = VLI.MULTIPLY(Sixteen(12),"16")
Sixteen(14) = VLI.MULTIPLY(Sixteen(13),"16")
Sixteen(15) = VLI.MULTIPLY(Sixteen(14),"16")

t=Timer
For I = 1 To 100
  S = GlobalMemoFromHex64(test)
Next
WScript.Echo "Global memo",Timer-t
Running the above in VBSEdit a few times under varying conditions gave the following results:
No memoization 2.632813
Memoized each time 1.023438
Global memo 0.328125

No memoization 1.667969
Memoized each time 0.8867188
Global memo 0.2695313

No memoization 1.488281
Memoized each time 0.9335938
Global memo 0.3046875
The global precomputation of the memo array is fastest technique, but if you're only using the function once you'll get by with the non-memo version.

Further optimisations are possible. Compilation, of course, would make it even faster.

Enjoy!
© Copyright Bruce M. Axtens, 2014

Wednesday, September 11, 2013

[Open Source] Github and Bitbucket

The blog's been very quiet lately. Too quiet. But I've been busy.

I got started on
Github, but the only thing I have there is a failed attempt at building a JSON library for the Euphoria programming language.

Most of the more recent stuff is happening on Bitbucket where I have various implementations (javascript v1 and javascript v2 (minimal), euphoria, vb6, php, and c#) of Steve Skiena's integer bignums library and a few other bits and bobs, namely:


All projects are in varying stages of completeness, and looking for users and improvers.


© Copyright Bruce M. Axtens, 2013

Friday, June 21, 2013

[JScript.NET --> C#.NET] Goodbye JScript.NET; Hello C#.NET

I'd better make it official: I've given up on JScript.NET (and to a lesser extent, JScript Classic.) There's just not enough support for it in current tools and IDEs.

So for the past couple of months I've been converting all my server-side javascripts (predominantly in JScript Classic) to C#.

I've also had one of my periodic clean-outs. Am trying to limit myself to a smaller set of programming languages for work and for play. That, and try to catch up on some of the things I've promised to others, like how to do web-scripting in Lhogho.


© Bruce M. Axtens, 2013

Friday, September 21, 2012

[JScript] Another Config library


I've been doing a fair bit of JScript of late, and as I find working with Registry for runtime configuration a bit tiresome, I've cooked up a Config object. It's defined using the prototype approach to object definition. Config files are, in this case, ANSI or Unicode (UTF16LE) files, in the form
key=value
Creating an instance of the object involves passing in the name of the config file. I've hit upon the following technique for tying the config file to the script, using the FileSystemObject and the WScript object.
var oFSO = new ActiveXObject("Scripting.FileSystemObject"),
    sHere = oFSO.GetParentFolderName(WScript.ScriptFullName),
    sConfig = oFSO.BuildPath(sHere, 
        oFSO.GetBaseName(WScript.ScriptName) + ".config");
That way one may always be sure that (for example) Melchizedek.js will have a Melchizedek.config next to it.

First, the main function

function Config(sFile) {
    this.kind = "";
    this.oFSO = new ActiveXObject("Scripting.FileSystemObject");
    this.text = "";
    var resp = [];
    this.file = sFile;
    if (this.oFSO.FileExists(sFile)) {
        resp = function(oFSO, sFilename) {
            var forReading = 1;
            var asUnicode = -1;
            var asANSI = 0;
            var resp = [];
            if (oFSO.FileExists(sFilename)) {
                var handle = oFSO.OpenTextFile(sFilename, forReading, false,
                        asANSI);
                var BOM = handle.Read(2);
                handle.Close();
                if (BOM.charCodeAt(0) == 0xFF && BOM.charCodeAt(1) == 0xFE) {
                    handle = oFSO.OpenTextFile(sFilename, forReading, false,
                            asUnicode);
                    resp[0] = "unicode";
                } else {
                    handle = oFSO.OpenTextFile(sFilename, forReading, false,
                            asANSI);
                    resp[0] = "ansi";
                }
                resp[1] = handle.ReadAll();
                handle.Close();
                return resp;
            } else {
                return resp;
            }
        }(this.oFSO, sFile);
        this.kind = resp[0];
        this.text = resp[1];
        this.name = sFile;
        this.filefound = true;
    } else {
        this.filefound = false;
    }
    return this.filefound;
}
Note that the code, in an attempt to deal appropriately with config files being in ANSI or UTF-16LE format, reads the first two bytes of the config file. If the UTF16LE BOM is there, it reads the file as Unicode. Otherwise, it reads as ANSI.

A few other things are set so that the other methods will work, namely for exists, name and kind.

Config.prototype.name = function() {
        return this.name;
};

Config.prototype.exists = function() {
        return this.filefound;
};

Config.prototype.kind = function () {
        return this.kind;
};
Next come the main workhorses of the object: define, retrieve and save.
Config.prototype.retrieve = function(sName) {
        if (arguments.length > 1) {
                var sDefault = arguments[1];
        } else {
                sDefault = null;
        }

        var re = new RegExp("^" + sName + "=(.*?)$", "m");
        var arr = re.exec(this.text);
        if (arr === null) {
                return sDefault;
        } else {
                return RegExp.$1;
        }
};

Config.prototype.define = function(sName, sValue) {
        var sNew = sName + "=" + sValue;
        var re = new RegExp("^" + sName + "=(.*?)$", "m");
        var arr = re.exec(this.text);
        if (arr === null) {
                this.text = this.text + "\n" + sNew;
        } else {
                this.text = this.text.replace(re, sNew);
        }
};

Config.prototype.save = function() {
        var sFile = "";
        var handle = "";
        // allow for save to a different file
        if (arguments.length > 0) {
                sFile = arguments[0];
        } else {
                sFile = this.file;
        }
        if (this.kind === "ansi") {
                handle = this.oFSO.CreateTextFile(sFile, true, false);
        } else {
                handle = this.oFSO.CreateTextFile(sFile, true, true);                
        }
        handle.Write(this.text);
        handle.Close();
};
retrieve accepts two parameters: the key in the config store, and the default (in the event that the key is not found.) Rather than using a Scripting.Dictionary, the config data is stored as a string, and regular expressions are used to extract and update it.

define accepts two parameters: the key in the config file, and the value to be associated with it. If the key is not found in the stored keys and values, it is appended to it.

save accepts one optional parameter: the name of the file into which to write the stored string of keys and values. If no name is given, the filename given when Config() was first called is used.

The code may be used as follows:

var c = new Config("dog.cfg");
'the define() will either add or update the store to 
'    sound=bark
c.define("sound","bark");
'the save() will write the store to dog.cfg
c.save();

'Config reloads dog.cfg
var c = new Config("dog.cfg");
'if "sound" is a key in dog.cfg, the associated value will be displayed
'otherwise the default.
WScript.Echo(c.retrieve("sound","woof"));

'display the kind (ansi or unicode)
WScript.Echo(c.kind);
'... whether the file exists
WScript.Echo(c.exists());
'... and what its name is
WScript.Echo(c.name);
The result of running the above code (from within SciTE):
>cscript /nologo Config.js
 bark
 unicode
 -1
 dog.cfg
 >Exit code: 0
I have recently pushed this code through Google's Closure Compiler and the difference in code size is significant -- the result is about 50% smaller than the original. I expect it runs faster too, though I haven't bothered to check it out thoroughly.
function Config(a) {
  this.kind = "";
  this.oFSO = new ActiveXObject("Scripting.FileSystemObject");
  this.text = "";
  var b = [];
  this.file = a;
  if(this.oFSO.FileExists(a)) {
    var b = this.oFSO, d = [];
    if(b.FileExists(a)) {
      var c = b.OpenTextFile(a, 1, !1, 0), e = c.Read(2);
      c.Close();
      255 == e.charCodeAt(0) && 254 == e.charCodeAt(1) ? (c = b.OpenTextFile(a, 1, !1, -1), d[0] = "unicode") : (c = b.OpenTextFile(a, 1, !1, 0), d[0] = "ansi");
      d[1] = c.ReadAll();
      c.Close()
    }
    b = d;
    this.kind = b[0];
    this.text = b[1];
    this.name = a;
    this.filefound = !0
  }else {
    this.filefound = !1
  }
  return this.filefound
}
Config.prototype.name = function() {
  return this.name
};
Config.prototype.exists = function() {
  return this.filefound
};
Config.prototype.kind = function() {
  return this.kind
};
Config.prototype.retrieve = function(a) {
  var b = 1 < arguments.length ? arguments[1] : null;
  return null === RegExp("^" + a + "=(.*?)$", "m").exec(this.text) ? b : RegExp.$1
};
Config.prototype.define = function(a, b) {
  var d = a + "=" + b, c = RegExp("^" + a + "=(.*?)$", "m");
  this.text = null === c.exec(this.text) ? this.text + "\n" + d : this.text.replace(c, d)
};
Config.prototype.save = function() {
  var a = "", a = "", a = 0 < arguments.length ? arguments[0] : this.file, a = "ansi" === this.kind ? this.oFSO.CreateTextFile(a, !0, !1) : this.oFSO.CreateTextFile(a, !0, !0);
  a.Write(this.text);
  a.Close()
};

Enjoy!
© Copyright Bruce M. Axtens, 2012