Thread: [Assorted-commits] SF.net SVN: assorted:[994] scala-commons/trunk
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-10-07 07:50:33
|
Revision: 994 http://assorted.svn.sourceforge.net/assorted/?rev=994&view=rev Author: yangzhang Date: 2008-10-07 07:50:23 +0000 (Tue, 07 Oct 2008) Log Message: ----------- updating for scala 2.7.2 Modified Paths: -------------- scala-commons/trunk/README scala-commons/trunk/publish.bash scala-commons/trunk/src/commons/Misc.scala Modified: scala-commons/trunk/README =================================================================== --- scala-commons/trunk/README 2008-10-07 01:58:49 UTC (rev 993) +++ scala-commons/trunk/README 2008-10-07 07:50:23 UTC (rev 994) @@ -25,6 +25,16 @@ [JScrape]: http://apsquared.net/JScrape.html [gnuplot]: http://www.gnuplot.info/ +Setup +----- + +Requirements: + +- [Scala] 2.7.2-RC2 +- [SimpleBuild] + +[SimpleBuild]: http://assorted.sf.net/simple-build/ + Related work ------------ Modified: scala-commons/trunk/publish.bash =================================================================== --- scala-commons/trunk/publish.bash 2008-10-07 01:58:49 UTC (rev 993) +++ scala-commons/trunk/publish.bash 2008-10-07 07:50:23 UTC (rev 994) @@ -7,7 +7,7 @@ } fullname='Scala Commons' -version=0.1 +version=0.2 license=scala websrcs=( README ) webfiles=( src/doc ) Modified: scala-commons/trunk/src/commons/Misc.scala =================================================================== --- scala-commons/trunk/src/commons/Misc.scala 2008-10-07 01:58:49 UTC (rev 993) +++ scala-commons/trunk/src/commons/Misc.scala 2008-10-07 07:50:23 UTC (rev 994) @@ -60,10 +60,6 @@ */ def !==(that: String) = !(===(that)) /** - * Repeat the string n times. - */ - def *(n: Int) = repeat(s) take n mkString ("", "", "") - /** * Truncate a string to be of length n. */ def truncate(n: Int) = s substring (0, s.length - n) @@ -75,7 +71,7 @@ /** * String interpolator. */ - def format(a: Array[AnyRef]) = String.format(s, a) + def format(a: Array[AnyRef]) = String.format(s, a:_*) } implicit def str2xstr(s: String): XString = XString(s) implicit def xstr2str(s: XString): String = s.s This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2010-03-02 22:53:37
|
Revision: 1572 http://assorted.svn.sourceforge.net/assorted/?rev=1572&view=rev Author: yangzhang Date: 2010-03-02 22:53:31 +0000 (Tue, 02 Mar 2010) Log Message: ----------- updated Collections to build with scala 2.8; added notes to README Modified Paths: -------------- scala-commons/trunk/README scala-commons/trunk/src/commons/Collections.scala Modified: scala-commons/trunk/README =================================================================== --- scala-commons/trunk/README 2010-03-01 05:26:28 UTC (rev 1571) +++ scala-commons/trunk/README 2010-03-02 22:53:31 UTC (rev 1572) @@ -41,6 +41,17 @@ Changes ------- +version 0.3 + +- updated for Scala 2.8 +- removed unnecessary functions + - `Collections.sortCounts` deprecated by `SeqLike.sortBy` + - `Collections.take` deprecated by `List.take + - `Collections.untilNull` deprecated by `Iterator.continually` and + `takeWhile` + - `Collections.iterator2array` + - `Collections.concat` deprecated by `xs reduceLeft (_ ++ _)` + version 0.2 - updated for Scala 2.7.2 Modified: scala-commons/trunk/src/commons/Collections.scala =================================================================== --- scala-commons/trunk/src/commons/Collections.scala 2010-03-01 05:26:28 UTC (rev 1571) +++ scala-commons/trunk/src/commons/Collections.scala 2010-03-02 22:53:31 UTC (rev 1572) @@ -52,7 +52,7 @@ def camelToLower(s: String, sep: String) = { val xs = for (c <- s) - yield if (c.isUpperCase) sep + c.toLowerCase else c + yield if (c.isUpper) sep + c.toLower else c xs mkString "" } def camelToUnder(s: String) = camelToLower(s, "_") @@ -76,8 +76,8 @@ // TODO: Is there a way to "chain" views? Then Iterable2FilterMap is // unnecessary and can be removed. - implicit def Iterable2FilterMap[T](s: Iterable[T]) = new FilterMap(s.elements) - implicit def Iterable2Iterator[T](s: Iterable[T]) = s.elements + implicit def Iterable2FilterMap[T](s: Iterable[T]) = new FilterMap(s.iterator) + implicit def Iterable2Iterator[T](s: Iterable[T]) = s.iterator implicit def Iterator2FilterMap[T](s: Iterator[T]) = new FilterMap(s) class FilterMap[T](s: Iterator[T]) { @@ -107,7 +107,7 @@ */ def last = { var last = i.next - for (val x <- i) { last = x } + for (x <- i) { last = x } last } } @@ -129,14 +129,12 @@ class RichStream[a](val s: Stream[a]) { // TODO: Fix this; it's dangerously inefficient and could cause a stack // overflow (see StreamRecursion test in sandbox)! - // TODO: Rename; confusing enough with groupBy != Haskell's groupBy, which - // is in turn == groupByPairwise. /** * This splits up the stream by using spanBy * <p> - * <code>[1..9].groupBy(_/3) == [[1,2],[3,4,5],[6,7,8]]</code> + * <code>[1..9].chunkBy(_/3) == [[1,2],[3,4,5],[6,7,8]]</code> */ - def groupBy[b](f: a => b) = { + def chunkBy[b](f: a => b) = { def r(s: Stream[a]): Stream[Stream[a]] = s match { case Stream.cons(h,t) => { val cur = f(h) @@ -144,11 +142,11 @@ // val (x,y): (Seq[a],Seq[a]) = spanBy(s)(f(_) == cur) val (x,y) = spanBy(s)(f(_) == cur) Stream.cons( - Stream fromIterator x.elements, - r(Stream fromIterator y.elements) + Stream fromIterator x.iterator, + r(Stream fromIterator y.iterator) ) } - case Stream.empty => Stream.empty + case Stream.Empty => Stream.Empty } r(s) } @@ -163,8 +161,8 @@ def sum(xs: Iterator[Int]) = xs.foldLeft(0)(_+_) def sum(xs: Seq[Double]) = xs reduceLeft ((x:Double,y:Double)=>x+y) def sum(xs: Iterator[Double]) = xs reduceLeft ((_:Double)+(_:Double)) - def mean(xs: Seq[Int]) = sum(xs.elements) / xs.size - def mean(xs: Seq[Double]) = sum(xs.elements) / xs.size + def mean(xs: Seq[Int]) = sum(xs.iterator) / xs.size + def mean(xs: Seq[Double]) = sum(xs.iterator) / xs.size def median(xs: Seq[Long]) = xs(xs.length / 2) import scala.util.Sorting @@ -204,24 +202,7 @@ (min1,min2) } - // TODO: Rename. /** - * Destructively sort the array by the tuples' second elements, and return - * the array. - */ - def sortCounts[a](xs: Array[(a,Int)]) = { - Sorting.stableSort(xs, (p: (a,Int), q: (a,Int)) => p._2 > q._2) - xs - } - - // TODO: Rename. - /** - * Return an array of the mappings in the Map, sorted by their entry-values. - */ - def sortCounts[a](h: mut.Map[a,Int]): Seq[(a,Int)] = - sortCounts(h toArray) - - /** * Given an iterator, return a HashMap from each distinct element to its * count. */ @@ -237,9 +218,7 @@ */ def topHist[a](xs: Iterator[a], n: Int): (mut.HashMap[a,Int], Seq[(a,Int)]) = { val h = hist(xs) - val sorted = sortCounts(h) - val took = take(sorted, n) - (h, took) + (h, h.toArray sortBy (_._2) take n) } /** @@ -283,20 +262,6 @@ } /** - * Return an iterator that yields invocations of f until it returns null. - * Useful for, e.g., Java's IO stream abstractions. - */ - def untilNull[a](f: => a) = new Iterator[a] { - var upcoming = f - override def hasNext = upcoming != null - override def next = { - val emit = upcoming - upcoming = f - emit - } - } - - /** * For each x in xs, if p(x), then x is a header, and it owns all the xs * after it until the next x for which p(x) holds. The return value is the * header and its body. @@ -335,9 +300,7 @@ val h = new mut.HashMap[a,mut.Set[b]] with mut.MultiMap[a,b] { override def makeSet = new mut.HashSet[b] } - for ((k,v) <- xs) { - h add (k,v) - } + for ((k,v) <- xs) h addBinding (k,v) h } @@ -357,11 +320,6 @@ } /** - * Convert an iterator to array. - */ - def iterator2array[a](xs: Iterator[a]) = xs.toList.toArray - - /** * A combination of take and drop. * <p> * <code>span(3)([a,b,c,d,e]) == ([a,b,c],[d,e])</code> @@ -450,7 +408,7 @@ * pairwise([]) == [] * </code> */ - def pairwise[a](xs: Iterable[a]) = xs.elements zip (xs.elements drop 1) + def pairwise[a](xs: Iterable[a]) = xs.iterator zip (xs.iterator drop 1) /** * Same as Haskell's groupBy. Groups together equal elements, letting the @@ -494,7 +452,7 @@ * remaining elements are repeat(gen). */ def pad[a](n: Int, e: => a, s: Iterator[a]) = - Stream.concat(Stream.fromIterator(s), repeat(e)) take n + Stream.concat(s.toStream, repeat(e)) take n /** * Truncate elements off the end of the sequence that satisfy the given @@ -517,13 +475,13 @@ } def argmax(xs: Seq[Int]) = - xs.elements.zipWithIndex reduceLeft { + xs.iterator.zipWithIndex reduceLeft { (a:(Int,Int),b:(Int,Int)) => (a,b) match { case ((x,i),(y,j)) => if (x > y) a else b } } def argmin(xs: Seq[Int]) = - xs.elements.zipWithIndex reduceLeft { + xs.iterator.zipWithIndex reduceLeft { (a:(Int,Int),b:(Int,Int)) => (a,b) match { case ((x,i),(y,j)) => if (x < y) a else b } @@ -560,7 +518,7 @@ */ def indexGroups[a,b](xs: Seq[a])(f: a => b) = { val i = Iterator from 0 - Stream fromIterator xs.elements groupBy f map (_ map (x => i.next)) + xs.toStream.iterator chunkBy f map (_ map (x => i.next)) } /** @@ -576,7 +534,7 @@ * </code> */ def zipx[a](xss: Seq[Iterable[a]]): Stream[Seq[a]] = { - val is = xss map (_.elements) + val is = xss map (_.iterator) def rec: Stream[Seq[a]] = if (is forall (_.hasNext)) Stream.cons(is map (_.next), rec) else Stream.empty @@ -588,20 +546,14 @@ * length of the resulting list is the length of the shortest input list. */ def zipx[a](xss: Iterable[Seq[a]]) = { - val width = xss.elements.next.length + val width = xss.iterator.next.length val iters = for (i <- 0 until width) - yield xss.elements map (_(i)) + yield xss.iterator map (_(i)) List(iters: _*) } /** - * Concatenate iterators. - */ - def concat[a](iters: Seq[Iterator[a]]) = - iters reduceLeft ((x: Iterator[a], y: Iterator[a]) => x ++ y) - - /** * Eliminate consecutive duplicates. */ def uniq[a](xs: Seq[a]) = groupPairwiseBy(xs)(_==_) map (_.head) @@ -654,7 +606,7 @@ def coord[a](i: Int, xss: Iterable[Seq[a]]): (Int, Int) = { var x = i var y = 0 - for (val xs <- xss) { + for (xs <- xss) { if (x <= xs.length) { return (x,y) } else { x -= (xs.length + 1); y += 1 } } @@ -706,7 +658,7 @@ */ def show(showLeaf: a => String): String = { def r(t: Tree[a]): Stream[String] = t match { - case Branch(ts) => Stream concat (ts map r) map (" " + _) + case Branch(ts) => (ts map r flatten) map (" " + _) case Leaf(x) => List(showLeaf(x)) toStream } r(this) mkString "\n" @@ -723,7 +675,7 @@ * Flatten the leaves into a single stream. */ def flatten: Stream[a] = this match { - case Branch(ts) => Stream concat (ts map (_.flatten)) + case Branch(ts) => (ts map (_.flatten) flatten) case Leaf(x) => Stream cons (x, Stream empty) } } @@ -733,11 +685,11 @@ /** * Build a tree whose i-th level branch has a fanout of xs(i). */ - def treeFromFanouts[a](gen: => a, fanouts: Seq[Int]): Tree[a] = + def treeFromFanouts[a: ClassManifest](gen: => a, fanouts: Seq[Int]): Tree[a] = fanouts match { case Seq() => Leaf(gen) case Seq(fanout, rest@_*) => - Branch(replicate(fanout, treeFromFanouts(gen, rest)).toArray) + Branch(replicate(fanout, treeFromFanouts(gen, rest)).toArray[Tree[a]]) } } @@ -747,7 +699,7 @@ def r(n: TreeNode[a], lvl: Int): Stream[String] = { Stream cons ( " " * lvl + n.value, - Stream concat (n.children map (n => r(n, lvl+1))) + (n.children map (n => r(n, lvl+1)) flatten) ) } r(this,0) mkString "\n" @@ -772,8 +724,8 @@ case Leaf(x) => Leaf(f(x)) } def flatten[b](f: a => b): Stream[b] = this match { - case And(ts) => Stream concat (ts map (_ flatten f)) - case Or(ts) => Stream concat (ts map (_ flatten f)) + case And(ts) => (ts map (_ flatten f) flatten) + case Or(ts) => (ts map (_ flatten f) flatten) case Not(t) => t flatten f case Leaf(x) => Stream cons (f(x), Stream empty) } @@ -827,16 +779,6 @@ loop } - /** - * Take an elements from a list. - */ - def take[a](src: Seq[a], n: Int) = { - val count = n min src.length - val dst = new Array[a](count) - src.elements take count copyToArray (dst, 0) - dst - } - // // Misc // This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2010-03-03 00:12:40
|
Revision: 1573 http://assorted.svn.sourceforge.net/assorted/?rev=1573&view=rev Author: yangzhang Date: 2010-03-03 00:12:34 +0000 (Wed, 03 Mar 2010) Log Message: ----------- imported code from RelationalCloud project; more fixes to build on scala 2.8 Modified Paths: -------------- scala-commons/trunk/README scala-commons/trunk/src/commons/Collections.scala scala-commons/trunk/src/commons/Control.scala scala-commons/trunk/src/commons/Io.scala scala-commons/trunk/src/commons/Misc.scala Added Paths: ----------- scala-commons/trunk/src/commons/Jdbc.scala scala-commons/trunk/src/commons/RichIterator.scala scala-commons/trunk/src/commons/TableFormatter.scala scala-commons/trunk/src/commons/Timer.scala Modified: scala-commons/trunk/README =================================================================== --- scala-commons/trunk/README 2010-03-02 22:53:31 UTC (rev 1572) +++ scala-commons/trunk/README 2010-03-03 00:12:34 UTC (rev 1573) @@ -44,6 +44,14 @@ version 0.3 - updated for Scala 2.8 +- imported code from RelationalCloud project + - Closeable views + - Jdbc + - RichIterator + - TableFormatter + - Timer + - `in` operator + - removeCBlockComments - removed unnecessary functions - `Collections.sortCounts` deprecated by `SeqLike.sortBy` - `Collections.take` deprecated by `List.take Modified: scala-commons/trunk/src/commons/Collections.scala =================================================================== --- scala-commons/trunk/src/commons/Collections.scala 2010-03-02 22:53:31 UTC (rev 1572) +++ scala-commons/trunk/src/commons/Collections.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -12,6 +12,19 @@ object Collections { // + // Convenience + // + + /** + * Let yourself write `x in xs`. + **/ + class InOperand[A](x: A) { + def in(xs: Seq[A]) = xs contains x + def notIn(xs: Seq[A]) = !(xs contains x) + } + implicit def toInOperand[A](x: A) = new InOperand(x) + + // // Tuples // @@ -141,10 +154,7 @@ // TODO: The next line induces a bug in Scala. // val (x,y): (Seq[a],Seq[a]) = spanBy(s)(f(_) == cur) val (x,y) = spanBy(s)(f(_) == cur) - Stream.cons( - Stream fromIterator x.iterator, - r(Stream fromIterator y.iterator) - ) + Stream.cons(x.toStream, r(y.toStream)) } case Stream.Empty => Stream.Empty } @@ -518,7 +528,7 @@ */ def indexGroups[a,b](xs: Seq[a])(f: a => b) = { val i = Iterator from 0 - xs.toStream.iterator chunkBy f map (_ map (x => i.next)) + xs.iterator.toStream chunkBy f map (_ map (x => i.next)) } /** @@ -658,7 +668,7 @@ */ def show(showLeaf: a => String): String = { def r(t: Tree[a]): Stream[String] = t match { - case Branch(ts) => (ts map r flatten) map (" " + _) + case Branch(ts) => (ts.toStream map r flatten) map (" " + _) case Leaf(x) => List(showLeaf(x)) toStream } r(this) mkString "\n" @@ -675,7 +685,7 @@ * Flatten the leaves into a single stream. */ def flatten: Stream[a] = this match { - case Branch(ts) => (ts map (_.flatten) flatten) + case Branch(ts) => (ts.toStream map (_.flatten) flatten) case Leaf(x) => Stream cons (x, Stream empty) } } @@ -699,7 +709,7 @@ def r(n: TreeNode[a], lvl: Int): Stream[String] = { Stream cons ( " " * lvl + n.value, - (n.children map (n => r(n, lvl+1)) flatten) + (n.children.toStream map (n => r(n, lvl+1)) flatten) ) } r(this,0) mkString "\n" @@ -724,8 +734,8 @@ case Leaf(x) => Leaf(f(x)) } def flatten[b](f: a => b): Stream[b] = this match { - case And(ts) => (ts map (_ flatten f) flatten) - case Or(ts) => (ts map (_ flatten f) flatten) + case And(ts) => (ts.toStream map (_ flatten f) flatten) + case Or(ts) => (ts.toStream map (_ flatten f) flatten) case Not(t) => t flatten f case Leaf(x) => Stream cons (f(x), Stream empty) } Modified: scala-commons/trunk/src/commons/Control.scala =================================================================== --- scala-commons/trunk/src/commons/Control.scala 2010-03-02 22:53:31 UTC (rev 1572) +++ scala-commons/trunk/src/commons/Control.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -43,7 +43,7 @@ /** * Invoke f(i) for all i from 0 on. */ - def loop[a](f: Int => a) = for (val x <- Stream from 0) f(x) + def loop[a](f: Int => a) = for (x <- Stream from 0) f(x) /** * Stream the repetition of f. Modified: scala-commons/trunk/src/commons/Io.scala =================================================================== --- scala-commons/trunk/src/commons/Io.scala 2010-03-02 22:53:31 UTC (rev 1572) +++ scala-commons/trunk/src/commons/Io.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -22,6 +22,13 @@ implicit def Reader2TextReader(r: Reader) = TextReader(r) implicit def TextReader2Reader(tr: TextReader) = tr.in + implicit def writer2closeable(w: java.io.Writer) = + new Closeable { def close = w.close } + implicit def raf2closeable(f: java.io.RandomAccessFile) = + new Closeable { def close = f.close } + implicit def istream2closeable(i: java.io.InputStream) = + new Closeable { def close = i.close } + // // Files // Added: scala-commons/trunk/src/commons/Jdbc.scala =================================================================== --- scala-commons/trunk/src/commons/Jdbc.scala (rev 0) +++ scala-commons/trunk/src/commons/Jdbc.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -0,0 +1,120 @@ +// Based on <http://scala.sygneca.com/code/simplifying-jdbc>. + +package commons + +import java.sql.{DriverManager, Connection, ResultSet, PreparedStatement, Statement, Date, Timestamp}; + +object Jdbc { + private def strm[X](f: RichResultSet => X, rs: ResultSet): Stream[X] = + if (rs.next) Stream.cons(f(new RichResultSet(rs)), strm(f, rs)) + else { rs.close(); Stream.empty }; + + implicit def conn2Statement(conn: Connection): Statement = conn.createStatement; + + implicit def query[X](s: String, f: RichResultSet => X)(implicit stat: Statement) = { + strm(f,stat.executeQuery(s)); + } + + private def iter[X](f: RichResultSet => X, rs: ResultSet) = new Iterator[X] { + var lastNext = rs.next + def hasNext = lastNext + def next = { + if (!lastNext) throw new Exception + val ret = f(new RichResultSet(rs)) + lastNext = rs.next + ret + } + } + + implicit def iquery[X](s: String, f: RichResultSet => X)(implicit stmt: Statement) = { + iter(f,stmt.executeQuery(s)) + } + + implicit def rrs2Boolean(rs: RichResultSet) = rs.nextBoolean; + implicit def rrs2Byte(rs: RichResultSet) = rs.nextByte; + implicit def rrs2Int(rs: RichResultSet) = rs.nextInt; + implicit def rrs2Long(rs: RichResultSet) = rs.nextLong; + implicit def rrs2Float(rs: RichResultSet) = rs.nextFloat; + implicit def rrs2Double(rs: RichResultSet) = rs.nextDouble; + implicit def rrs2String(rs: RichResultSet) = rs.nextString; + implicit def rrs2Date(rs: RichResultSet) = rs.nextDate; + implicit def rrs2Timestamp(rs: RichResultSet) = rs.nextTimestamp; + + implicit def resultSet2Rich(rs: ResultSet) = new RichResultSet(rs); + implicit def rich2ResultSet(r: RichResultSet) = r.rs; + class RichResultSet(val rs: ResultSet) { + + var pos = 1 + def apply(i: Int) = { pos = i; this } + + def nextBoolean: Boolean = { val ret = rs.getBoolean(pos); pos = pos + 1; ret } + def nextByte: Byte = { val ret = rs.getByte(pos); pos = pos + 1; ret } + def nextInt: Int = { val ret = rs.getInt(pos); pos = pos + 1; ret } + def nextLong: Long = { val ret = rs.getLong(pos); pos = pos + 1; ret } + def nextFloat: Float = { val ret = rs.getFloat(pos); pos = pos + 1; ret } + def nextDouble: Double = { val ret = rs.getDouble(pos); pos = pos + 1; ret } + def nextString: String = { val ret = rs.getString(pos); pos = pos + 1; ret } + def nextDate: Date = { val ret = rs.getDate(pos); pos = pos + 1; ret } + def nextTimestamp: Timestamp = { val ret = rs.getTimestamp(pos); pos = pos + 1; ret } + + def foldLeft[X](init: X)(f: (ResultSet, X) => X): X = rs.next match { + case false => init + case true => foldLeft(f(rs, init))(f) + } + def map[X](f: ResultSet => X) = { + var ret = List[X]() + while (rs.next()) + ret = f(rs) :: ret + ret.reverse; // ret should be in the same order as the ResultSet + } + } + + implicit def ps2Rich(ps: PreparedStatement) = new RichPreparedStatement(ps); + implicit def rich2PS(r: RichPreparedStatement) = r.ps; + + implicit def str2RichPrepared(s: String)(implicit conn: Connection): RichPreparedStatement = conn prepareStatement(s); + + class RichPreparedStatement(val ps: PreparedStatement) { + var pos = 1; + private def inc = { pos = pos + 1; this } + + def execute[X](f: RichResultSet => X): Stream[X] = { + pos = 1; strm(f, ps.executeQuery) + } + def <<: Stream[X] = execute(f); + + def execute = { pos = 1; ps.execute } + def <<! = execute; + + def addBatch = { pos = 1; ps.addBatch } + def executeBatch = { pos = 1; ps.executeBatch } + + def <<(b: Boolean) = { ps.setBoolean(pos, b); inc } + def <<(x: Byte) = { ps.setByte(pos, x); inc } + def <<(i: Int) = { ps.setInt(pos, i); inc } + def <<(x: Long) = { ps.setLong(pos, x); inc } + def <<(f: Float) = { ps.setFloat(pos, f); inc } + def <<(d: Double) = { ps.setDouble(pos, d); inc } + def <<(o: String) = { ps.setString(pos, o); inc } + def <<(x: Date) = { ps.setDate(pos, x); inc } + def <<(x: Timestamp) = { ps.setTimestamp(pos, x); inc } + } + + implicit def conn2Rich(conn: Connection) = new RichConnection(conn); + + class RichConnection(val conn: Connection) { + def <<(sql: String) = new RichStatement(conn.createStatement) << sql; + def <<(sql: Seq[String]) = new RichStatement(conn.createStatement) << sql; + } + + implicit def st2Rich(s: Statement) = new RichStatement(s); + implicit def rich2St(rs: RichStatement) = rs.s; + + class RichStatement(val s: Statement) { + def <<(sql: String) = { s.execute(sql); this } + def <<(sql: Seq[String]) = { for (x <- sql) s.execute(x); this } + } + + def queryOne(s: String)(implicit stat: Statement) = + query(s, rs => rs:Int).head +} Modified: scala-commons/trunk/src/commons/Misc.scala =================================================================== --- scala-commons/trunk/src/commons/Misc.scala 2010-03-02 22:53:31 UTC (rev 1572) +++ scala-commons/trunk/src/commons/Misc.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -90,4 +90,10 @@ override def next = base + i.next override def hasNext = i.hasNext } + + /** + * Remove C block comments. + */ + def removeCBlockComments(s: String) = s.replaceAll("/\\*(?:.|[\\n\\r])*?\\*/", "") + } Added: scala-commons/trunk/src/commons/RichIterator.scala =================================================================== --- scala-commons/trunk/src/commons/RichIterator.scala (rev 0) +++ scala-commons/trunk/src/commons/RichIterator.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -0,0 +1,72 @@ +package commons + +import scala.collection.{mutable => mut} + +class RichIterator[X](it: Iterator[X]) { + /** Note that this is dangerous in that the states of the sub-iterators and + * the iterator are tightly coupled. */ + def iterChunkAs[K,Y](f: X => (K,Y)) = new Iterator[(K,Iterator[Y])] { + var xform = if (it.hasNext) Some(f(it.next)) else None + def hasNext = xform != None + def next = { + if (!hasNext) throw new Exception + val key = xform.get._1 + val subiter = new Iterator[Y] { + def hasNext = xform != None && xform.get._1 == key + // as long as we're not past the end and we're on the active key + def next = { + if (!hasNext) throw new Exception + val ret = xform.get._2 + xform = if (it.hasNext) Some(f(it.next)) else None + ret + } + } + (key, subiter) + } + } + def iterChunkBy[K](f: X => K) = iterChunkAs(x => (f(x), x)) + + def iterSplitOn(isCut: X => Boolean) = new Iterator[Iterator[X]] { + var fresh = true + def next: Iterator[X] = { + if (fresh) fresh = false + else it dropWhile isCut + it takeWhile (!isCut(_)) + } + def hasNext:Boolean = fresh || { it dropWhile isCut; it hasNext } + } + + def chunkAs[K,Y](f: X => (K,Y)) = new Iterator[(K,Seq[Y])] { + val bit = it.buffered + def hasNext = bit.hasNext // nextElt != None + def next = { + if (!bit.hasNext) throw new Exception + val chunk = new mut.ArrayBuffer[Y] + var xform = f(bit.head) // (nextElt.get) + val key = xform._1 + // as long as we're not past the end and we're on the active key + while (bit.hasNext && xform._1 == key) { + chunk += xform._2 + bit.next // consume it + if (bit.hasNext) xform = f(bit.head) + } + (key, chunk) + } + } + def chunkBy[K](f: X => K) = chunkAs(x => (f(x), x)) +} + +class CachedIterator[X](it: Iterator[X]) extends Iterator[X] { + var last: X = _ + def hasNext = it.hasNext + def next = { + last = it.next + last + } +} + +object RichIterator { + implicit def toRichIterator[X](it: Iterator[X]) = new RichIterator(it) + implicit def toRichIterator[X](it: Iterable[X]) = new RichIterator(it.iterator) + implicit def toRichIterator[X](it: Array[X]) = new RichIterator(it.iterator) +} Added: scala-commons/trunk/src/commons/TableFormatter.scala =================================================================== --- scala-commons/trunk/src/commons/TableFormatter.scala (rev 0) +++ scala-commons/trunk/src/commons/TableFormatter.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -0,0 +1,13 @@ +package commons + +case class TableFormatter(val rows: Iterable[List[Any]]) { + val xss = rows map (_ map (_ toString) toArray) toArray + override def toString = { + val fmt = ( + for ((x,i) <- xss(0).zipWithIndex) yield { + "%" + (xss map (_(i).length) reduceLeft (Math.max(_,_))) + "s" + } + ).mkString(" | ") + xss map (String.format(fmt, _: _*)) mkString "\n" + } +} Added: scala-commons/trunk/src/commons/Timer.scala =================================================================== --- scala-commons/trunk/src/commons/Timer.scala (rev 0) +++ scala-commons/trunk/src/commons/Timer.scala 2010-03-03 00:12:34 UTC (rev 1573) @@ -0,0 +1,26 @@ +package commons + +object Timer { + + /** + * Return the time in milliseconds taken to run f. + */ + def time(f: =>Any): Long = { + val start = System.currentTimeMillis + f + val stop = System.currentTimeMillis + stop - start + } + + /** + * Evaluate f, printing the time it took. + */ + def printTime[A](f: =>A) = { + val start = System.currentTimeMillis + val ret = f + val stop = System.currentTimeMillis + println("...took " + (stop - start) / 1000. + " s") + ret + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2010-03-03 05:55:05
|
Revision: 1575 http://assorted.svn.sourceforge.net/assorted/?rev=1575&view=rev Author: yangzhang Date: 2010-03-03 05:54:59 +0000 (Wed, 03 Mar 2010) Log Message: ----------- more fixes; link to grizzled Modified Paths: -------------- scala-commons/trunk/README scala-commons/trunk/src/commons/Collections.scala scala-commons/trunk/src/commons/Control.scala Modified: scala-commons/trunk/README =================================================================== --- scala-commons/trunk/README 2010-03-03 00:33:42 UTC (rev 1574) +++ scala-commons/trunk/README 2010-03-03 05:54:59 UTC (rev 1575) @@ -41,7 +41,7 @@ Changes ------- -version 0.3 +version 0.2 - updated for Scala 2.8 - imported code from RelationalCloud project @@ -60,10 +60,6 @@ - `Collections.iterator2array` - `Collections.concat` deprecated by `xs reduceLeft (_ ++ _)` -version 0.2 - -- updated for Scala 2.7.2 - version 0.1 - initial release, for use with Scala 2.7.0 @@ -74,10 +70,12 @@ Code found here generally tries to complement code in the following other handy libraries: +- the [Grizzled] utility library - the [Scala standard library] -- the [ScalaX] community library +- the [ScalaX] community library (not actively maintained) - the [ScalaZ] library [Scala standard library]: http://www.scala-lang.org/docu/files/api/ -[scalax]: http://scalax.scalaforge.org/ -[scalaz]: http://wiki.workingmouse.com/index.php/Scalaz +[ScalaX]: http://scalax.scalaforge.org/ +[ScalaZ]: http://wiki.workingmouse.com/index.php/Scalaz +[Grizzled]: http://www.clapper.org/software/scala/grizzled-scala/ Modified: scala-commons/trunk/src/commons/Collections.scala =================================================================== --- scala-commons/trunk/src/commons/Collections.scala 2010-03-03 00:33:42 UTC (rev 1574) +++ scala-commons/trunk/src/commons/Collections.scala 2010-03-03 05:54:59 UTC (rev 1575) @@ -2,9 +2,6 @@ import scala.collection.{mutable => mut} -// TODO: Is there a way to avoid having to explicitly handle both Iterators and -// Iterables? - // TODO: Pretty much anywhere I take a number, I'd like to make the facility // more general, but without (say) incurring the reflection costs associated // with structural typing. @@ -781,7 +778,7 @@ if (iter hasNext) { val x = iter.next if (p(x)) loop - else Iterator single x append iter + else Iterator single x ++ iter } else { iter } Modified: scala-commons/trunk/src/commons/Control.scala =================================================================== --- scala-commons/trunk/src/commons/Control.scala 2010-03-03 00:33:42 UTC (rev 1574) +++ scala-commons/trunk/src/commons/Control.scala 2010-03-03 05:54:59 UTC (rev 1575) @@ -13,16 +13,6 @@ finally { x.close } /** - * Time some code. - */ - def time(f: =>Any): Long = { - val start = System.currentTimeMillis - f - val stop = System.currentTimeMillis - stop - start - } - - /** * Return Some(f) if the function succeeded, or None if there was an * Exception. */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |