Wednesday, February 29, 2012

collate

//src: http://blog.bloidonia.com/post/18073244930/whats-new-in-groovy-1-8-6-the-collate-method

//v1.8.6+//
def list = 1..10
def listInFours  = list.collate( 4 )
assert listInFours == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]

def listInFours2 = list.collate( 4, false )

// Notice the [ 9, 10 ] remainder has been dropped
assert listInFours2 == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]

def gridList = list.collate( 3 ).collate( 2 )

assert gridList == [ [ [1, 2, 3], [4, 5, 6] ],
                     [ [7, 8, 9], [10]      ] ]

def mph        = [ 10, 26, 30, 32, 27, 14, 19, 22, 40, 14 ]
def window     = mph.collate( 3, 1, false )

assert window == [ [10, 26, 30],
                   [26, 30, 32],
                   [30, 32, 27],
                   [32, 27, 14],
                   [27, 14, 19],
                   [14, 19, 22],
                   [19, 22, 40],
                   [22, 40, 14] ]
                   
def windowAvg  = window*.sum()*.intdiv( 3 )
assert windowAvg == [22, 29, 29, 24, 20, 18, 27, 25]

def items   = [ 'ham', 30, 'cheese', 20, 'steak', 95 ]
def itemMap = items.collate( 2 ).collectEntries()

assert itemMap == [ ham:30, cheese:20, steak:95 ]

def range   = 1..20
def (odds,evens) = range.collate( 2 ).transpose()

assert odds  == (1..19).step( 2 ) // odd numbers 1 - 19
assert evens == (2..20).step( 2 ) // even numbers 2 - 20

Monday, February 27, 2012

Regex look-ahead/behind syntax

//http://groovy.codehaus.org/Regular+Expressions
def r = /e+/
def str = 'me cheese please'
def m = str =~ r

assert m.size() == 5
println m*.toString() //[e, ee, e, e, e]

/////////////////////////////

def r = /(This boy) is/
def str = 'This boy is 10. This boy wants chocolate. This boy is tall.'
def m = str =~ r

assert m.size() == 2
assert m.collect { it[1] } == ['This boy','This boy']

/////////////////////////////

assert "abc".replaceAll(/(a)(b)(c)/, "\$1\$3") == 'ac' //back references

/////////////////////////////

//http://www.regular-expressions.info/captureall.html
r = /((?:abc|123)+).*?/
str = '123abc 123abc123'
m = str =~ r

assert m.size() == 2
println m*.toString()
print m[0][1..-1]
println m[1][1..-1]

/////////////////////////////

//password of 8 characters long and two non-letters
def r1 = /.*[^a-zA-Z].*[^a-zA-Z].*(?<=.{7})/  //look-behind ?<=

assert 'abc' !=~ r1
assert 'abcde12' !=~ r1
assert 'abcdef12' ==~ r1
assert 'abc1defgggg2' ==~ r1
assert 'abc1defgggg' !=~ r1

//word is foo$wrd*, store $wrd*
def wrd = 'bar'
def r2 = /foo((?=$wrd)[\w]+)/  //look-ahead ?=

def foo = "foo${wrd}hellow"
assert foo ==~ r2
def m = foo =~ r2
assert m[0][1] == "${wrd}hellow" // note: $wrd not consumed by check, is stored in result

foo = 'foohellow' // no $wrd
assert foo !=~ r2

//ADVANCED/////////////////////////////
def churnText(String text) {
    def points = [[k: ~/(N|n)orth(E|e)ast(ern)?/                                                                , v:'NE'],
              [k: ~/(?>(N|n)orth(W|w)est(ern|:)?)(?! Territories)/                                              , v:'NW'],
              [k: ~/(S|s)outheast(ern)?/                                                                        , v:'SE'],
              [k: ~/(?>(S|s)outh(\s)?(W|w)est(ern)?)(?! Hill| Bend)/                                            , v:'SW'],
              [k: ~/(?>(N|n)orth(ern)?|Upstate)(?! Carolina| Dakota| Platte| Neck| Mariana Islands| Bay|ridge)/ , v:'N' ],
              [k: ~/(E|e)ast(ern)?/                                                                             , v:'E' ],
              [k: ~/(?>(S|s)outh(ern|side)?)(?! Carolina| Dakota)/                                              , v:'S' ],
              [k: ~/(?!(?<=George ))(?>(W|w)est(ern| of the)?)(?! Virginia| Palm Beach)/                        , v:'W' ],
              [k: ~/(?>(C|c)entral|Center|Middle|the middle section of the)(?!town| Peninsula| Tennessee|ia)/   , v:'C' ]]
    
    points.each {p ->
      def matcher = (text =~ p.k)
      text = matcher.replaceAll(p.v)
      println "p.v: ${p.v} text: $text"
    }
}

churnText('Northwest Virginia')
println '='*40
churnText('NorthWestern Territories')
println '='*40
churnText('East George West')
return

Thursday, February 23, 2012

Swing Notification Popup

//see: http://groovy.codehaus.org/GUI+Programming+with+Groovy

import groovy.swing.*
import java.awt.*
import javax.swing.*
import javax.swing.border.*
import groovy.util.slurpersupport.NodeChild as Node
 
public class Notify { 
 def sb = new SwingBuilder()

 public static void main(String[] args) {
  // creates and displays itself
  new Notify(args)
 }

 public Notify(String[] args){
  // arg is path to xml message file, 
  // will be deleted after popup displayed
  if (args.size() != 1) return 
  
  String appTitle = ".:. Notification .:."
  String filePath = args[0]
  Color backgroundColor = Color.yellow
  Border emptyBorder = BorderFactory.createMatteBorder(5, 5, 5, 5, backgroundColor)
    
  Toolkit tk = Toolkit.getDefaultToolkit()
  Dimension screenSize = tk.getScreenSize()
  final int WIDTH = screenSize.width
  final int HEIGHT = screenSize.height
  
  int w = WIDTH / 2
  int h = HEIGHT / 2
  
  int x = (WIDTH / 2) - (w / 2)
  int y = (HEIGHT / 2) - (h / 2) - 50
  
  Font fontSubject = new Font("Serif", Font.PLAIN, 24)
  Font fontMessage = new Font("Serif", Font.PLAIN, 16)
  
  //generate frame//
  sb.dialog(id:"popupBox", title:appTitle, visible:true, alwaysOnTop:true, defaultCloseOperation:JFrame.DISPOSE_ON_CLOSE, resizable:false, location:[x, y], size:[w, h]) 
  {
   borderLayout()
   label(id:"subject", constraints:BorderLayout.NORTH, horizontalAlignment:JTextField.CENTER, font:fontSubject, "SUBJ")
   
   panel(constraints:BorderLayout.CENTER){
    gridLayout(cols:1, rows:1, hgap:1, vgap:1)
    scrollPane(border:emptyBorder) {
     textArea(id:"message", editable:false, lineWrap:true, wrapStyleWord:true, font:fontMessage, "MESG")
    }
   }
  }
  def frame = sb.popupBox
  
  //decorate frame color//
  def cp = frame.contentPane
  cp.background = backgroundColor
  sb.message.background = cp.background
  
  //populate frame data//
  File xmlFile
  Node root
  try {
   xmlFile = new File(filePath)
   root = new XmlSlurper().parse(xmlFile)
   //println root.getClass().name
  } 
  catch (Exception) {
   xmlFile = new File("")
   root = new XmlSlurper().parseText('''
    Error
    Sorry, file path or XML syntax error.
    ''')
  }
  
  sb.subject.text = root.subject.text() // if not found, subject UI label is hidden
  sb.message.text = root.message.text() ? 
   root.message.text().replaceAll('\\\\n', System.getProperty( "line.separator" )) :
   'Sorry, empty notification.'
  
  //display form//
  frame.show()
  
  try {
   xmlFile.delete()
  } catch (Exception ignore) {}
 }
}

Thursday, February 16, 2012

Shell/Command line execution

//def cmd = "cmd /C dir"
def cmd = ["cmd","/C","dir g*.bat"] // more flexible format

//Groovyish Java//
Runtime r = Runtime.runtime
Process p = r.exec(cmd.toArray(new String()))
BufferedReader inp = new BufferedReader(new InputStreamReader(p.getInputStream()))
while (line = inp.readLine()) { println line }

//Groovy!//
println cmd.execute().text

Friday, February 10, 2012

Colt - Random Number Generators

/*
 * see: http://acs.lbl.gov/software/colt/
 */
@Grapes(
    @Grab(group='colt', module='colt', version='1.2.0')
)
import cern.jet.random.*

println Binomial.staticNextInt(500,0.5d)
println ChiSquare.staticNextDouble(10.0d)
println Exponential.staticNextDouble(1.0d)
println ExponentialPower.staticNextDouble(1.0d)
println Normal.staticNextDouble(10.0d,1.0d)
println Poisson.staticNextInt(100.0d)
println Uniform.staticNextDoubleFromTo(1.0d,100.0d)
println VonMises.staticNextDouble(10.0d)

Apache Commons Collections

@Grapes(
    @Grab(group='commons-collections', module='commons-collections', version='3.2.1')
)
import org.apache.commons.collections.*
import org.apache.commons.collections.map.*
import org.apache.commons.collections.bidimap.*

IterableMap map1 = [a:1, b:2] as HashedMap
map1.each {
    print it.key
    println it.value
}

OrderedMap map = new LinkedMap()
map.with {
    put("FIVE", "5")
    put("SIX", "6")
    put("SEVEN", "7")
    assert firstKey() == "FIVE"
    assert nextKey("FIVE") == "SIX" 
    assert nextKey("SIX")  == "SEVEN"
}

BidiMap bidi = new TreeBidiMap()
bidi.with {
    put("SIX", "6")
    assert get("SIX") == "6"
    assert get("SIX") == "6"
    assert getKey("6") == "SIX"
    removeValue("6")
    assert getKey("SIX") == null
    put("ONE", "1")
}
BidiMap inverse = bidi.inverseBidiMap()  // returns a map with keys and values swapped
assert inverse.getKey("ONE") == "1"

Buffer buffer = new UnboundedFifoBuffer()
buffer.with {
    add("ONE")
    add("TWO")
    add("THREE")
    assert remove() == "ONE"
    assert remove() == "TWO"
}

Bag bag = new HashBag()
bag.with {
    add("ONE", 6)  // add 6 copies of "ONE"
    remove("ONE", 2)  // removes 2 copies of "ONE"
    assert getCount("ONE") == 4
}

Trove - high speed regular and primitive collections

/*
 * see: http://trove.starlight-systems.com/
 */
@Grapes(
    @Grab(group='net.sf.trove4j', module='trove4j', version='3.0.2')
)
import gnu.trove.set.*
import gnu.trove.set.hash.*
import gnu.trove.list.*
import gnu.trove.list.array.*
import gnu.trove.list.linked.*
import gnu.trove.map.*
import gnu.trove.map.hash.*

//Most Trove classes start with the letter "T" to indicate that they're part of the Trove library.
THashSet s = new THashSet()
100.times { i ->
  s.add ((i / 2).toInteger())
}
assert s.size() == 50
assert s.contains(0)

TIntArrayList a = new TIntArrayList()
100.times { i ->
  a.add ((i / 3).toInteger())
}
assert a.size() == 100
assert a.get(0) == 0

TIntLinkedList l = new TLinkedList()
100.times { i ->
  l.add ((i / 4).toInteger())
}
assert l.size() == 100
assert l.get(0) == 0

THashMap m = new THashMap()
m['a'] = 1
m.b = 2
assert m.a == 1

Thursday, February 9, 2012

Google Guava

/*
 * see: http://code.google.com/p/guava-libraries/
 * grails caching idea: http://refactr.com/blog/2012/05/grails-in-memory-cache-using-googles-guava-library/
 */
@Grapes([
     @Grab("com.google.guava:guava:14.0.1")
])
import java.util.concurrent.TimeUnit
import com.google.common.primitives.Ints
import com.google.common.collect.Iterables
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.google.common.hash.Hashing
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader

List list = [1,2,3,3]
assert Iterables.frequency(list, 2) == 1
assert Iterables.frequency(list, 3) == 2

String temp = "test"
md5 = Hashing.md5()
String hash = md5.newHasher().putBytes(temp as byte[]).hash()
assert hash != temp
assert hash == "098f6bcd4621d373cade4e832627b4f6"

ImmutableList of = ImmutableList.of("a", "b", "c", "d");
// Same one for map
ImmutableMap map = ImmutableMap.of("key1", "value1", "key2", "value2");
//list of ints
List theList = Ints.asList(1, 2, 3, 4, 522, 5, 6);

//see: https://code.google.com/p/guava-libraries/wiki/CachesExplained
Cache cache = 
CacheBuilder.newBuilder()
  .weakKeys()
  .maximumSize(10000)
  .expireAfterWrite(10, TimeUnit.MINUTES)
  .build( new CacheLoader() {
    @Override
    public String load(Integer key) throws Exception {
      return retreveStringForKey(key);
    }
    @Override
    public Object load(Object o) { return o; } //???
  });

cache.metaClass.propertyMissing { k -> delegate.get(k) }
cache.metaClass.propertyMissing { k, v -> delegate.put(k, v) }
cache["a"] = 9
assert cache.size() == 1
assert cache["a"] == 9

Wednesday, February 8, 2012

Java2Html

@Grapes(
    @Grab(group='de.java2html', module='java2html', version='5.0')
)
import de.java2html.*;
import de.java2html.options.*;

String javaText = '''
/**
 * This is about ClassName.
 * {@link com.yourCompany.aPackage.SuperClass}
 * @author author
 */
public class ClassName extends SuperClass {
  /* This comment may span multiple lines. */
  private int integer = 0;
  public final static char character = 'A';
  // This comment may span only this line
  private String string = "zero";
}
'''

JavaSourceConversionSettings conversionOptions = new JavaSourceConversionSettings(new JavaSourceConversionOptions());
String htmlText = Java2Html.convertToHtmlPage(javaText, conversionOptions);
println (htmlText)

Tuesday, February 7, 2012

Geb Web Test

//updated Jan 12 2013
//check out Geb/Phantomjs integration via RemoteWebDriver support!

@Grapes([
     @Grab("junit:junit-dep:4.8.2"),
     @Grab("org.codehaus.geb:geb-junit4:0.7.2"),  //soon to go 0.9.0
     @Grab("org.seleniumhq.selenium:selenium-firefox-driver:2.28.0"),
     @Grab("org.seleniumhq.selenium:selenium-remote-driver:2.28.0"),
     @Grab("org.seleniumhq.selenium:selenium-support:2.28.0")
])
import geb.*
import geb.driver.CachingDriverFactory
import org.openqa.selenium.*
import org.openqa.selenium.remote.*
//import org.openqa.selenium.firefox.FirefoxProfile
//import org.openqa.selenium.firefox.FirefoxDriver
//import java.awt.Robot // see http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)


def cachedDriver = CachingDriverFactory.clearCacheAndQuitDriver() // clean-up old window & driver if any :)

File path = new File("C:\\geb-test\\")
path.mkdirs()

String searchFor = "dogs" // or null = off

String downloadImgURL = 'http://freemailtemplates.com/wp-content/themes/psdfiles-freemailtemplates/images/download-button.png' // or null = off
String downloadImgPathFile = path.absolutePath+'\\pic.png'

String screenshotURL = 'http://www.yahoo.com' // or null = off
String screenshotPathFile = path.absolutePath+'\\screenshot.png'
// NOTE: these two webdrivers ONLY init'ed for the URL page screenshots (which need a headless/remote browser like phantomjs) //
// you could probably just go to the URL and generate a report, too...? //
final RemoteWebDriver rdriver
final WebDriver augmentedDriver
if (screenshotURL) {
    try {
        rdriver = new RemoteWebDriver( "http://localhost:9134".toURL(), DesiredCapabilities.firefox() )
        augmentedDriver = new Augmenter().augment(rdriver)
    } 
    catch (Exception e) { screenshotURL = null }
}

// NOTE: config ONLY init'ed for reporting purposes //
def config = new Browser().getConfig() // steal a default config(??)
config.reportsDir = path

try{

    Browser.drive(config) {
        if (searchFor) {
            go "http://www.google.ca/"
            assert title.contains("Google")
            
            // basic searching/reading/etc ////////////////////////////////////////////
            def inputs = $("input, button")
            assert inputs.size() > 2
            inputs.each {
                println ":"+it.value()
            }
            
            // try a real Google search! ////////////////////////////////////////////
            def textSearch = $("form[action='/search'] input[type='text']")
            assert textSearch.size() == 1

            textSearch.value( searchFor )
            
            def buttonSearch = waitFor { $("input[type='button'], button") }.findAll{ it.text().toLowerCase().contains("search") }
            if (buttonSearch.size() == 0)
                // try another DOM node search //
                buttonSearch = waitFor { $("input[type='button']#gbqfb, button#gbqfb", 0) }
            
            assert buttonSearch.size() == 1
            
            buttonSearch.click()
            
            def items = waitFor { $("li.g") }
            // show the first item's text
            println items[0].text()
                
            def imgs = $("img")
            def srcs = imgs*.@src
            srcs.each { src ->
                // show the img sources
                println "img: " + (src ?: 'n/a')
            }
        }

        // try another page! ////////////////////////////////////////////
        go "http://cnn.com"
        assert title.contains("CNN.com")
        println ">>>" + title

        // try to dump the page's HTML and screenshot! ////////////////////////////////////////////
        reportGroup "cnn"
        report "homepage"

        // try to inject jQuery into the page! ////////////////////////////////////////////
        injectLibrary(js, 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js') ////////////////////////////////////////////
        js."jQuery.noConflict"()

        // try to grab the body's raw HTML! ////////////////////////////////////////////
        String body = ''+js."document.body.innerHTML"+''

        // try a URL file download! ////////////////////////////////////////////
        if (downloadImgURL) {
            try {
                downloadFile(browser, downloadImgURL, downloadImgPathFile)
            }
            catch (Exception e) { println "[ERROR] downloading: ${e.message}\n${e.printStackTrace()}" }
        }

        // try a URL page screenshot! ////////////////////////////////////////////
        if (screenshotURL) {
            try {
                screenshot(augmentedDriver, screenshotURL, screenshotPathFile)
            } 
            catch(Exception e) { println "[ERROR] screenshot: ${e.message}\n${e.printStackTrace()}" }
        }
        
        println '==Done=='

        //close() // close window, not neccesary with CachingDriverFactory.clearCacheAndQuitDriver()
        //quit()  // quit window, not neccesary with CachingDriverFactory.clearCacheAndQuitDriver()
    }

    cachedDriver = CachingDriverFactory.clearCacheAndQuitDriver() // clean-up window & driver if successful :)
    
} 
catch(Exception e) { println "[ERROR] Please try again: ${e.message}" }
//==END MAIN==//


//these util methods all get their context object passed in as a final//
def downloadFile(final Browser browser, String downloadImgURL, String downloadImgPathFile) {
    input = browser.downloadStream(downloadImgURL) // geb function
    output = new BufferedOutputStream(new FileOutputStream(downloadImgPathFile))
    output << input
}

def screenshot(final WebDriver driver, String url, String filename) {
    /*********************************************************
     * Note: you need a headless/remote web server running (like phantomjs)
     *  - beware, this doesn't seem to like HTTP redirects
     *********************************************************/
    driver.get(url)

    final File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)
    scrFile.renameTo(filename ?: 'screenshot.png')
}

def injectLibrary(final js, String library){
    if (!js."document.body.innerHTML".contains(library))
        js.exec("document.body.appendChild(document.createElement('script')).src='$library'");
    //assert js."document.body.innerHTML".contains(library)
}