Wednesday, July 17, 2019

[Scraping] Do I really want to write a Google Keep tool?

After writing so many wrappers and so many scraping tools over the last few years, I'm now asking myself: "Do I really want to write tools for Google Keep?" There's been a few folk calling for a Google Keep API but nothing has materialized as yet (AFAICT.)

I do use Keep a lot as a general catchall for interesting web content. Mind you, I use Pocket as well. And PearlTrees. And Zim.

Fiddling with my Keep collection in Firefox Developer sees me trying to spot some structures that could be targeted in Selenium. One item of interest is via document.querySelectorAll(".RNfche"). At this point I don't know if the RNfche class is specific to my collection or to everyone's, but it's on every containing DIV. The number of results of the querySelectAll() increases as one scrolls down the page. Thus, to find every one of them one would have to script Selenium to scroll right down to the bottom of the collection before pulling up the list of RNfche-class elements.

Can I really be bothered?

Please note: this blog post was originally published at Dev.to on 2019-07-17.

Tuesday, July 16, 2019

[Google Apps Script] ScriptProperties Gotcha in Google Apps Script

For reasons of insanity I have wrapped the ScriptProperties of the PropertiesService in a object with get, set, forget and getKeys methods, viz:

function ScptProps() {
  this.scriptProperties = PropertiesService.getScriptProperties();
}

ScptProps.prototype.get = function (name) {
  return this.scriptProperties.getProperty(name);
};

ScptProps.prototype.set = function (name, value) {
  return this.scriptProperties.setProperty(name, value);
};

ScptProps.prototype.forget = function (name) {
  return this.scriptProperties.deleteProperty(name);
};

ScptProps.prototype.getKeys = function () {
  return this.scriptProperties.getKeys();
};

Using the REPL from my previous posting, I issued the following commands:
 
(new ScptProps).set('goose',58);
typeof (new ScptProps).get('goose');
(new ScptProps).forget('goose');

Goose is me and 58 my age for those interested.

And the gotcha? Well, I was a little taken aback recently, while debugging a number to number comparison issue, to discover that when I store a number I don't get one back. I get a string back and have to do a parseInt() on it to get its original value. The result of typeof (new ScptProps).get('goose'); is, you guessed it, string!

Please note: this blog posting was originally published in Dev.to on 2019-07-16

Thursday, July 11, 2019

[Google Apps Script] REP and almost L in Google Apps Script

It's been quite a while since I blogged about computing (I usually blog about baking) but here goes.

Lately I've been climbing a steep learning curve, trying to get my head around Google Apps Script (GAS). Now a few spreadsheets later, I'm on a trajectory that should see me crash-land on Planet Add-On in a month or two.

REPL (read-evaluate-print-loop) has been a big thing for a long time with all manner of programming languages. So why not GAS? (Okay, it's more REP than REPL as the looping doesn't happen, but it's close.)

In my Code.gs I have the following (among other things)

function onOpen() { 
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Debugging')
  .addItem('REPL', 'REPL')
  .addToUi();  
}

This adds a custom menu to the menubar and populates it with one entry, namely 'REPL' which, when selected, runs a function called 'REPL'.
 
function REPL() {
  var code = Browser.inputBox('code');
  if (code !== 'cancel') {
    Browser.msgBox(eval(code));
  }
}

Also in there, for demonstration purposes, is a function that totals the ASCII values of the characters in the parameter string.
 
function TotalAscii(str) {
  return str.split("").reduce(function (result, item, index) {
    return result + item.charCodeAt(0)
  }, 0)
}
 
Visually there we are selecting the REPL option from the Debugging menu

 

entering something to be evaluated and getting a response.



I'd like at some stage to put together an HTML form with a TEXTAREA. Maybe after I crawl out of the crater.

Please note: This blog posting was first published at Dev.to on 2019-07-11

Monday, December 24, 2018

[tbas] Chinese Year of the ...

The author of tbas, Antonio Maschio, loves DATA and READ statements, and after putting together a Chinese Zodiac submission for RosettaCode, I can see why. And then there's TAB() which is also very helpful.

DATA "甲","乙","丙","丁","戊","己","庚","辛","壬","癸"
 DECLARE celestial$(10)
 MAT READ celestial$
 
 DATA "子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"
 DECLARE terrestrial$(12)
 MAT READ terrestrial$
 
 DATA "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"
 DECLARE animals$(12)
 MAT READ animals$
 
        DATA "Wood","Fire","Earth","Metal","Water"
 DECLARE elements$(5)
 MAT READ elements$
 
 DATA "yang","yin"
 DECLARE aspects$(2)
 MAT READ aspects$
 
 DATA "jiă","yĭ","bĭng","dīng","wù","jĭ","gēng","xīn","rén","gŭi"
 DATA "zĭ","chŏu","yín","măo","chén","sì","wŭ","wèi","shēn","yŏu","xū","hài"
 DECLARE celestialpinyin$(UBOUND(celestial$(),1))
 DECLARE terrestrialpinyin$(UBOUND(terrestrial$(),1))
 MAT READ celestialpinyin$
 MAT READ terrestrialpinyin$
 
 DATA 1935,1938,1931,1961,1963,1991,1993,1996,2001
 DECLARE years(9)
 MAT READ years
 
 DECLARE _base = 4  
 DECLARE _year 
 DECLARE cycleyear 
 DECLARE stemnumber 
 DECLARE stemhan$    
 DECLARE stempinyin$ 
 DECLARE elementnumber 
 DECLARE element$       
 DECLARE branchnumber 
 DECLARE branchhan$    
 DECLARE branchpinyin$ 
 DECLARE animal$       
 DECLARE aspectnumber 
 DECLARE aspect$       
 DECLARE index 
 
 DECLARE i 
 DECLARE top = UBOUND(years(),1)
 FOR i = 1 TO top
  _year = years(i)
  cycleyear = _year - _base
  stemnumber = MOD(cycleyear, 10) 
  stemhan$    = celestial$(stemnumber + 1)
  stempinyin$ = celestialpinyin$(stemnumber + 1)
  elementnumber = div(stemnumber, 2) + 1
  element$       = elements$(elementnumber)
  branchnumber = MOD(cycleyear, 12)  
  branchhan$    = terrestrial$(branchnumber + 1)
  branchpinyin$ = terrestrialpinyin$(branchnumber + 1)
  animal$       = animals$(branchnumber + 1)
  aspectnumber = MOD(cycleyear, 2)
  aspect$       = aspects$(aspectnumber + 1)
  index = MOD(cycleyear, 60) + 1  
  PRINT _year; 
  PRINT TAB(5);stemhan$+branchhan$;
  PRINT TAB(12);stempinyin$;"-";branchpinyin$;
  PRINT TAB(25);element$;" ";animal$;" ("+aspect$+")";
  PRINT TAB(50);"year";index;"of the cycle"  
 NEXT
Running the program gives
$ tbas chinZod.bas
 1935 乙亥 yĭ-hài     Wood Pig (yin)           year 12 of the cycle
 1938 戊寅 wù-yín     Earth Tiger (yang)       year 15 of the cycle
 1931 辛未 xīn-wèi    Metal Goat (yin)         year 8 of the cycle
 1961 辛丑 xīn-chŏu   Metal Ox (yin)           year 38 of the cycle
 1963 癸卯 gŭi-măo    Water Rabbit (yin)       year 40 of the cycle
 1991 辛未 xīn-wèi    Metal Goat (yin)         year 8 of the cycle
 1993 癸酉 gŭi-yŏu    Water Rooster (yin)      year 10 of the cycle
 1996 丙子 bĭng-zĭ    Fire Rat (yang)          year 13 of the cycle
 2001 辛巳 xīn-sì     Metal Snake (yin)        year 18 of the cycle
© Copyright Bruce M. Axtens, 2018

Thursday, March 15, 2018

[PHP] Include a data structure once

Today's job at work was to get some data into GravityForms, a forms tool for WordPress.

So one page has a postcode entry, and the next page has some hidden postcode-specific fields that are used to calculate values later in the form-set, in this case freight costs on goods delivered by
TNT (no relation to the song by AC/DC).

The documentation for GravityForms suggests putting code into functions.php in the active theme. I'm a little wary of doing that given that changes there can work or not work in a rather catastrophic way.

Nevertheless, I ended up coding against the gform_field_input hook
add_filter('gform_field_input', 'update_hidden', 10, 5);
function update_hidden($input, $field, $value, $lead_id, $form_id)
{
}
So then the was the issue of how to include the postcode-to-charges array (PCA) (stored in an external php file) once rather than each time gform_field_input fired, which is once per control. With the PCA being just shy of a megabyte in length, I wasn't particularly interested in having it load repeatedly.

The PCA looks like this
<?php
return array(
 '0221' => array(
  'BasicChrg' => 9.982, 
  'KgChrg' => 0.5405, 
  'MinChrg' => 15.3755, 
  'RemotAreaChrg' => 0, 
  'ResidChrg' => 5, 
  '0to15Chrg' => 0, 
  '15to199Chrg' => 10, 
  '200to299Chrg' => 30, 
  '300to399Chrg' => 40, 
  '400to499Chrg' => 150, 
  '500to599Chrg' => 250, 
  '600plusChrg' => 300, 
  'FuelSurchrg' => 0.07)
  ...
);
StackOverflow did offer a suggestion on how to deal with this but I had no joy with it. So I went with using include_once. That, however, also had problems. According to the documentation, include_once returns a boolean true when it gets called the second time for the same file. So one must use a temporary variable to hold the result rather than committing it immediately to your PCA variable.

So the code I have ended up with is (some omitted for brevity's sake):
function update_hidden($input, $field, $value, $lead_id, $form_id)
{
 global $TNTFreightPrices, $PostCode;

 $path = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/tntfreightprices/TNTFreightPrices.php';
 $tmp = include_once $path;
 if (gettype($tmp) == "array") {
  $TNTFreightPrices = $tmp;
  $PostCode = rgpost('input_52');
 }

 if ($form_id == 8) {
  $BasicChrg = $TNTFreightPrices[$PostCode]['BasicChrg'];
  
  ...

  $fid = $field['id'];
  
  if ($fid == 53) {
   $input = "<input id='input_8_53' class='gform_hidden' name='input_53' aria-invalid='false' value='$BasicChrg' type='hidden'>";
  }
  ...
 }
}
It remains to be seen whether I stay with $TNTFreightPrices and $PostCode in global space as that's a carryover from other experiments.

It was part fun and part hairloss but at least we're closer to a solution. Probably there are better ways. WooCommerce?


© Copyright Bruce M. Axtens., 2018

Monday, February 12, 2018

[dotnet] core, standard and framework

Riiiiiight, now I get it ... maybe.

Check the original posting on StackOverflow for the full description.

© Copyright Bruce M. Axtens, 2018

Friday, February 09, 2018

[JavaScript] String.prototype

Back in 2011, I started learning JavaScript. I'm still learning but haven't moved beyond ES3, largely because that's the dialect I'm using for most of my server-side scripting. In other words, Microsoft JScript (gasp, shock, horrors, gevalt etc.)

Most of the rest of what I do at the moment is using C#. A while back I went looking for a way to extend my C# programs with scripting and found
ClearScript. I've been using it to great effect for the last 3 years in the vast majority of my work projects. I've even written a JScript-on-steroids which exposes large chunks of C# to JScript and permits the writing of some very powerful scripts.

In the next few postings I'll be discussing some of the interesting things I've discovered. For a lot of folk, it'll be old hat ... so old that mice are living in it. But, who knows, maybe someone will find a use for some of it, or be able to adapt it to newer dialects.

toProperCase()

String.prototype.toProperCase = function () {
  return this.replace(/\w\S*/g, function (txt) {
    return String(txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
  });
};
I found this on StackOverflow. It attempts to proper-case (title-case) every word in a string. I don't use it often but it was an interesting find.

after
()
String.prototype.after = function (a, including) {
  including = including || false;
  a = this.indexOf(a);
  return -1 === a ? String(this) : String(this.substr(a + (including ? 0 : 1)));
};
A staple, this gives whatever is after a substring in a string. The substring can be included or excluded for the result.

before
()
String.prototype.before = function (a, including) {
  including = including || false;
  a = this.indexOf(a);
  return -1 === a ? String(this) : String(this.substr(0, a + (including ? 1 : 0)));
};
Another staple, this gives whatever is before a substring in a string. Again, the substring can be included or excluded for the result.

stripChars
()
String.prototype.stripChars = function (chars, cnt) {
  var i,
  j;
  cnt = cnt || 0;
  var answer = this;
  for (i = 0; i < chars.length; i++) {
    var chr = chars.charAt(i);
    if (cnt === 0) {
      var pat = new RegExp(chr, "g");
      answer = answer.replace(pat, "");
    } else {
      for (j = 0; j < cnt; j++) {
        answer = answer.replace(chr, "");
      }
    }
  }
  return String(answer);
};
I don't use this often, but it has been useful. It removes each element of chars from the string. If cnt is undefined or zero, all are removed. If cnt is 1 or more, then that many are removed.

between
()
String.prototype.between = function (begin, end, including) {
  including = including || false;
  var left = this.indexOf(begin);
  if (left < 0) {
    return String('');
  }
  left += begin.length;
  var right = typeof end === 'undefined' ? this.length : this.indexOf(end, left);
  if (right < 0) {
    return String('');
  }
  return including ? String(begin + this.substring(left, right) + end) : String(this.substring(left, right));
};
There are various ways of pulling SGML and other markups apart. This one, in various languages, has been in the toolkit for years. This variant permits excluding or including the delimiters. Apart from that, it isn't smart -- "drooling singing".between("droo","ing") gives l

endswith
()
String.prototype.endswith = function (str) {
  return this.indexOf(str) !== -1 && this.indexOf(str) === this.length - str.length;
};
Returns true if the strings ends with contents of str otherwise false. Has helped with detecting filetypes in filenames.

toSqlString
()
String.prototype.toSqlString = function () {
  return String("'" + String(this).replace(/'/g, "''") + "'");
};
This puts a single quote at the start and end of the string and doubles any embedded single quotes. I use this in combination with .questionMarkIs() to format SQL statements.

toArrayOfLines
String.prototype.toArrayOfLines = function () {
  return this.split(/\r\n|\r|\n/g);
};
Splitting a text file to lines is something I do a lot of. This is the functional variant of code I have in almost every script written over the last 7 years.

questionMarkIs

String.prototype.questionMarkIs = function (val) {
  return String(this.replace("?", val));
};
For a while I was doing all kinds of weird things to build SQL queries. Lately I've taken to simply putting question marks in and then replacing them with the value (with or without .toSqlString()).

That should do for now. Enjoy!

© Copyright Bruce M. Axtens, 2018

Thursday, February 08, 2018

[configuration files] dhall

Okay, I know next to nothing about this at the moment but it does look interesting.
dhall is a programmable configuration language that is not Turing-complete. You can think of Dhall as: JSON + functions + types + imports
I can think of some places where this approach to config would be helpful and less dangerous that what I am currently doing.

© Copyright Bruce M. Axtens, 2018

Wednesday, February 07, 2018

[tbas] tbas basic interpreter

In my ample (NOT!) spare time, I'm helping out with a programming language project called tbas. I saw it advertised on comp.lang.basic.misc in September 2017 (yep, usenet is still going strong.)

The author is one Antonio Maschio from Italy.

You can get source, documentation and a CygWin binary from the main site. There are some examples on RosettaCode.

To give you an idea of the flavour of the language, the following is a simple CAESAR cipher implementation.

    LET MSG$ = ""
    LET OFFS = 0
    LINE INPUT "Message"; MSG$
    INPUT "Offset"; OFFS
    DIM TARG(LEN(MSG$))
    CHANGE MSG$ TO TARG
    FOR I = 1 TO UDIM(TARG)
        TARG(I) = TARG(I) + OFFS
    NEXT
    CHANGE TARG TO MSG$
    PRINT MSG$

An example of running the above

    >tbas CAESAR.BAS
    Message ? My dog's got fleas
    Offset ? 1
    Nz!eph(t!hpu!gmfbt

© Copyright Bruce M. Axtens, 2018

Thursday, July 20, 2017

[FreeDOS] The FAST and SOFA compilers

Two recent additions to the FreeDOS stable of development languages are FAST (Fast PC Compiler) and SOFA (Super Optimised Fast Assembler), inventions of one Peter Campbell of New Zealand. Peter developed FAST and SOFA in the mid 1980s and they were used as the main development languages for the Fastbase accounting system. In 2000, Peter rewrote the entire system in Tcl. All use and development of FAST and SOFA stopped at that point.

SOFA is an 8088 (and semi-80386) assembler. The syntax has some similarities to two other shareware assemblers,
A86 and CHASM. SOFA can assemble its own source-code. Its features include quick assembly time (thousands of lines per second), conditional compilation and include files.

FAST was written in SOFA. The language syntax was influenced by Basic, Pascal, C and Assembler. The binaries produced are small and fast
[1].

Peter Campbell died in tragic circumstances at Easter 2007, leaving the Fastbase business to his brother, Russell Bell.

The adding of FAST and SOFA to FreeDOS took a little too long: I had heard of the language during the 1990s and had rediscovered it in the
Vetusware abandonware collection. From there I found out about FastBase and made contact with Russell. This was 2009 and it was at that time that I suggested to Russell that SOFA/FAST could be re-released as Open Source software, thus preserving in some way Peter's legacy. Russell promptly gave permission and provided me with the sources. Embarassingly, it has taken me eight years to finalise the process.

SOFA and FAST will appear eventually on
HOPL (The Online Historical Encyclopaedia of Programming Languages). In the meantime, postings regarding the languages can be found on HOPL's Facebook front-end at SOFA and FAST respectively.

[1] Already some FreeDOS utilities have been rewritten in FAST.

© Copyright Bruce M. Axtens, 2017

Wednesday, December 02, 2015

[Browsers] Inconsistent HTML Entities

I fancy that this is old hat to most of you, but I had thought HTML entities cut and dried: An ampersand, a word and a semicolon (reminds me a little of dBase III, actually.) It seems, however, that certain browsers are still unsure as to what constitutes an HTML entity, and where it should end.

One of the languages I use for server-side management uses the ampersand + word + semicolon format to mark where variables may be interpolated into the output stream. So it was with some surprise when it was pointed out to me by a colleague that &currentValue; was being rendered as ¤tValue;.

Being the inquisitive sort, I went to
dev.w3.org and downloaded all the HTML entity names. After a bit of fiddling about in jQuery, I had the list. After a bit more fiddling, this time in JScript, I ended up with an HTML file showing the entity name, the entity as rendered, and then what happens when you leave off the trailing semicolon and append some other text (in this case 'es'). This is where things get ... well ... unusual. Some HTML entites follow the standard. Others like &curren; and &pound; don't. You enter &poundage, expecting the browser to give &poundage only to have it give you £age. Weirdness abounds. Take &centerdot; which actually renders as ¢erdotes!

So as to give you an idea of how it looks in your browser, I've put the file up in a
jsfiddle . Let me know how you get on and whether your browser is as compliant is it makes out.

Enjoy!


© Copyright Bruce M. Axtens, 2015

Saturday, November 07, 2015

[COBOL] Sum multiples of 3 and 5

Last night I posted the following code on RosettaCode as another solution to the Sum multiples of 3 and 5 challenge. (Mine is the third one down after all the more-mathematical solutions.)

My solution is as brute-force as it gets, using only adds and comparisons.
       IDENTIFICATION DIVISION.
       PROGRAM-ID. SUM35.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  THREE-COUNTER   USAGE BINARY-CHAR value 1.
           88 IS-THREE VALUE 3.
       01  FIVE-COUNTER    USAGE BINARY-CHAR value 1.
           88 IS-FIVE VALUE 5.
       01  SUMMER          USAGE BINARY-DOUBLE value zero. 
       01  I               USAGE BINARY-LONG.
       01  N               USAGE BINARY-LONG.

       PROCEDURE DIVISION.
       10-MAIN-PROCEDURE.
           MOVE 1000000000 TO N.
           MOVE 1 TO I.
           PERFORM 20-INNER-LOOP WITH TEST AFTER UNTIL I >= N.
           DISPLAY SUMMER.
           STOP RUN.
       20-INNER-LOOP.
           IF IS-THREE OR IS-FIVE 
               ADD I TO SUMMER END-ADD
               IF IS-THREE
                   MOVE 1 TO THREE-COUNTER
               ELSE
                   ADD 1 TO THREE-COUNTER
               END-IF
               IF IS-FIVE
                   MOVE 1 TO FIVE-COUNTER
               ELSE    
                   ADD 1 TO FIVE-COUNTER
               END-IF
           ELSE
               ADD 1 TO FIVE-COUNTER END-ADD
               ADD 1 TO THREE-COUNTER END-ADD
           END-IF.
           ADD 1 TO I.
           EXIT.
       END PROGRAM SUM35.
The above code compiles on GnuCOBOL 2.0 and MicroFocus Visual COBOL 2.3. In the latter environment, I was able to get a run time of 7.3 seconds for the 1,000,000,000 iterations (AMD A6-5200 APU running at 2.00 GHz.)

I ended up in COBOL via the usual circuitous route through other programming languages after figuring out a solution using
mLite. The next postings will demonstrate the mLite and perhaps others.

© Copyright Bruce M. Axtens., 2015

Sunday, October 11, 2015

[GnuCOBOL 2.0] Beginning COM

In my ample (NOT!) spare time, I'm exploring making COM available to the Windows implementation of GnuCOBOL. You can do GnuCOBOL on Linux and Mac as well.

Many thanks to
Brian Tiffin over on GnuCOBOL's Sourceforge Forum for cheering me on.
       IDENTIFICATION DIVISION.
       PROGRAM-ID. OLE.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  HRESULT     USAGE BINARY-LONG.
           88 S_OK     VALUE 0.
           88 S_FALSE  VALUE 1.
       01  NUL         USAGE BINARY-LONG VALUE 0.
       
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
        CALL STDCALL "OleInitialize"
            USING BY VALUE NUL
            RETURNING HRESULT.
            DISPLAY HRESULT.

        CALL STDCALL "OleUninitialize" USING
            BY REFERENCE OMITTED
            GIVING NULL.

            STOP RUN.
       END PROGRAM OLE.
The are some runtime settings (Windows 10 Home, 64bit) required to get that working, namely
set COB_PRE_LOAD=ole32
set COB_LIBRARY_PATH=C:\windows\syswow64
I should sometime create a Github project for this, in case others want to run with it.

© Copyright Bruce M. Axtens, 2015

[CSNOBOL4] Decimal to Binary #2

Many thanks to Gordon Peterson who took my non-idiomatic code and improved it both in size and speed, viz
         DEFINE("BIN(N)")                            :(BIN_END)
BIN      BIN = (GT(N,1) BIN(N / 2), ) REMDR(N,2)     :(RETURN)
BIN_END
This is guru level stuff.

I'm also grateful to
Fred Weigel who first responded to my posting in the Snobol Yahoo! Group and made some very useful suggestions. He points out that Gordon's solution is a prime candidate for DEXP, viz:
dexp('bin(n) = (gt(n, 1) bin(n / 2), ) remdr(n, 2)')
That's enough CSNOBOL4 for now, though if you do want to spend some time with it (Windows or Linux), I'd suggest using Rafal M. Sulejman's TkSLIDE.

© Copyright Bruce M. Axtens, 2015

Wednesday, October 07, 2015

[CSNOBOL4] Decimal to Binary

Okay, I think this is the last of the solutions to Binary Digits. Thie one's in CSNOBOL4. Kudos to Phil Budne for maintaining and expanding this amazing programming language.

The code below, like all the ones before it, is recursive.
        DEFINE('BIN(N,STR)')              :(BIN_END)
BIN     EQ(N,0)                           :S(NZERO)
        BIN = BIN(N / 2, REMDR(N,2) STR)  :S(RETURN)
NZERO   BIN = EQ(SIZE(STR),0) '0'         :S(RETURN)
        BIN = STR                         :(RETURN)
BIN_END

        OUTPUT = BIN(0)
        OUTPUT = BIN(5)
        OUTPUT = BIN(50)
        OUTPUT = BIN(9000)
END


© Copyright Bruce M. Axtens, 2015

[Euphoria] Decimal to Binary

Having solved the Binary Digits task in mLite and FBSL, I thought I'd have a go in OpenEuphoria. Kudos to David Craig of Rapid Deployment Software for the original implementation and to the subsequent team of heroes for a very powerful Windows/Linux/Mac programming (interpreted and/or compiled) language.

The code below, expressed in v4.1.0 form, follows the FBSL fairly closely.
include std/math.e 
include std/convert.e

function Bin(integer n, sequence s = "")
  if n > 0 then
   return Bin(floor(n/2),(mod(n,2) + #30) & s)
  end if
  if length(s) = 0 then
   return to_integer("0")
  end if
  return to_integer(s)
end function

printf(1, "%d\n", Bin(0))
printf(1, "%d\n", Bin(5))
printf(1, "%d\n", Bin(50))
printf(1, "%d\n", Bin(9000))
There's already an Euphoria solution to the task. Some enterprising soul might want to check which of the two solutions is the faster.

© Copyright Bruce M. Axtens, 2015

[FBSL] Decimal to Binary

Having solved the Binary Digits task in mLite, I thought I'd have a go in FBSL. Kudos to the FBSL team for a very useful and powerful Windows scripting language. Even ABAP users can leverage it!

The code below, expressed in v3.5 RC form, follows the mLite fairly closely.

#AppType Console
function Bin(byval n as integer, byval s as string = "") as string
 if n > 0 then return Bin(n \ 2, (n mod 2) & s)
 if s = "" then return "0"
 return s
end function

print Bin(5)
print Bin(50)
print Bin(9000)

pause
It was during the testing of this code that it dawned on me that the mLite wasn't handling the binary 0; appropriately. Thus those who notice such things will discover a subtle change in the mLite posting.

© Copyright Bruce M. Axtens, 2015

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