fozziethebeat | 9 Feb 18:12
Picon
Gravatar

Scala sometimes fails to load a jar

Hello all,

I've been using scala fairly heavily and often just write short one
object programs that tie together a number of classes defined in a
java package i've been working with, as if my scala code is the main
for the java tools.  I tend to run things without compiling with
simple commands like:

    scala -cp sspace-lib.jar MyScalaProg.scala args_here

And that works for the most part, except on certain occasions where
scala, for reasons unknown, fails to load the associated jar, sspace-
lib.jar.  Sometimes I can solve this by running scala from where the
jar is located, othertimes it's the exact opposite.  Here's some
sample runs to clarify:

$ scala -cp bin/sspace-lib.jar DTest.scala

    /home/stevens/devel/S-Space/DTest.scala:32: error: not found:
value log
        a.zip(b).map(v=>if (v._1 == 0d) 0.0 else v._1 * log(v._1/
(v._2+eps))).sum

Everything looks as expected, I forgot to import log but otherwise it
recognizes my java based imports

$ cd bin
$ scala -cp sspace-lib.jar ../DTest.scala

  /home/stevens/devel/S-Space/bin/../DTest.scala:1: error: not found:
(Continue reading)

Ka Ter | 9 Feb 17:55
Gravatar

Type parameter, collection and return type

Hi,

why is the following code producing the compiler error 'type mismatch; 
found   : Traversable[Any]  required: C'? The type of the collection
doesn't change and therefore it is a C. If I ommit the ':C' of the
method than the return type is inferred to Traversable[Any].

        class Test[C <: Traversable[Any] : Manifest](collection: C)
        {
            def test(): C = collection.filter(e => e == e)
        }

        (new Test(Set[String]())).test

--

-- 
Best Regards

Ka Ter

Ken Scambler | 9 Feb 04:09
Picon

Re: Disambiguating a parameter name

Thanks Naftoli.  (back on list, oops) :)

Hmm, still seems awkward though, having to have a dodgy parameter name as a first class part of a class' API.  I suppose I can live with it though.

Cheers,
Ken



On 9 February 2012 14:04, Naftoli Gugenheim <naftoligug-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
You replied off list, but anyway I think there are two conventions used, to name the constructor parameter either _theRealName or theRealName0.


On Wednesday, February 8, 2012, Ken Scambler wrote:
Well, I was using by-name parameters and lazy vals to allow a bunch of immutable structures to bootstrap themselves in one pass.   This demonstrates the issue:

class MyClass(theFooby: => Something) {
  lazy val fooby: Something = theFooby

  // everything else can use fooby; theFooby should not be run more than once.
}

Cheers,
Ken


On 9 February 2012 13:51, Naftoli Gugenheim <naftoligug-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
What is the situation that involves a constructor?


On Wednesday, February 8, 2012, Ken Scambler wrote:
That's a good thought, thanks Naftoli.  It doesn't work (nicely) for constructor parameters though; the extra def or val would be a member rather than a temporary variable.

On 9 February 2012 10:52, Naftoli Gugenheim <naftoligug <at> gmail.com> wrote:
What I've done sometimes is:

def createX(y: String): X = {
  def tmp = y
  new X {
    def y: String = tmp
  }
}


On Tuesday, February 7, 2012, Ken Scambler wrote:
I often find myself with the problem of disambiguating a parameter name against a class member of the same name:

trait Foo { def bar: String }

def createFoo(theBar: String): Foo = new Foo {
  def bar: String = theName
}
 
Here I've added a meaningless syllable to the parameter name to make it unique.  However, since the "named parameters" feature makes parameter names part of the external API of a class, I really don't want to do this.   Also we're assuming here that we want to keep Foo as a trait, and not make it a class with a constructor.

Is there a way around this without picking silly names?  There seems no way to specify the parameter over the member.

Cheers,
Ken



Ken Scambler | 9 Feb 04:03
Picon

Disambiguating a parameter name

Well, I was using by-name parameters and lazy vals to allow a bunch of immutable structures to bootstrap themselves in one pass.   This demonstrates the issue:

class MyClass(theFooby: => Something) {
  lazy val fooby: Something = theFooby

  // everything else can use fooby; theFooby should not be run more than once.
}

Cheers,
Ken



On 9 February 2012 13:51, Naftoli Gugenheim <naftoligug-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
What is the situation that involves a constructor?


On Wednesday, February 8, 2012, Ken Scambler wrote:
That's a good thought, thanks Naftoli.  It doesn't work (nicely) for constructor parameters though; the extra def or val would be a member rather than a temporary variable.

On 9 February 2012 10:52, Naftoli Gugenheim <naftoligug <at> gmail.com> wrote:
What I've done sometimes is:

def createX(y: String): X = {
  def tmp = y
  new X {
    def y: String = tmp
  }
}


On Tuesday, February 7, 2012, Ken Scambler wrote:
I often find myself with the problem of disambiguating a parameter name against a class member of the same name:

trait Foo { def bar: String }

def createFoo(theBar: String): Foo = new Foo {
  def bar: String = theName
}
 
Here I've added a meaningless syllable to the parameter name to make it unique.  However, since the "named parameters" feature makes parameter names part of the external API of a class, I really don't want to do this.   Also we're assuming here that we want to keep Foo as a trait, and not make it a class with a constructor.

Is there a way around this without picking silly names?  There seems no way to specify the parameter over the member.

Cheers,
Ken



Chris Reeves | 9 Feb 02:13
Picon

Oddity with implicit conversion and objects in objects

Greetings,

I have a wrapper class that has an implicit conversion to the class
that it is wrapping, but it doesn't behave consistently. When using
the implicit conversion on anything but a nested object, a println in
the implicit def will be executed. For objects in objects, the
conversion apparently happens, as it doesn't error and returns the
object, but the println doesn't execute. Can anyone shed some light on
this behavior? Here's the misbehaving example:

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Wrapper[A](val item: A)
object Wrapper {
  implicit def unwrap[A](in: Wrapper[A]): A = {
    println("unwrapping...")
    in.item
  }
}
object Foo {
  object foo extends Object
  val int = 10
  def str = "test"
}
class Bippy {
  object foo extends Object
  val int = 10
  def str = "test"
}

// Exiting paste mode, now interpreting.

defined class Wrapper
defined module Wrapper
defined module Foo
defined class Bippy

scala> val cw = new Wrapper(new Bippy)
cw: Wrapper[Bippy] = Wrapper <at> 394d4138

scala> cw.foo
unwrapping...
res0: object Bippy#foo = Bippy$foo$@55b4fea9

scala> cw.int
unwrapping...
res2: Int = 10

scala> cw.str
unwrapping...
res3: java.lang.String = test

scala> val ow = new Wrapper(Foo)
ow: Wrapper[Foo.type] = Wrapper <at> a67ca87

scala> ow.int
unwrapping...
res4: Int = 10

scala> ow.str
unwrapping...
res5: java.lang.String = test

scala> ow.foo
res6: Foo.foo.type = Foo$foo$@3a4449c2

Thanks, Chris

Edmondo Porcu | 8 Feb 23:52
Picon

Enumerations / Lists of available types

Dear all,
I have an abstract  animal, and three concrete type of animals: dog, cat and pig. Each instance of one of these classes correspond to an existing animal, with his weight, his size, and all this kind of stuff.

I would like in some way to list all the available types of concrete animals, and returning  a list containing for each available subtype a description. I can create an enumeration, having one value corresponding to each subclass of animals. However, this force me to update my enumeration each time I add a new subclass of animal.

The classical case is for example a web application to store data about animals: first you would have to decide which kind of animal you want to add, then you get redirected to a specific page where you can fill the necessary data for that kind of animal.
Is there a better way to do this?


Thank you for your help
Best Regards

Edmondo



Daniel Persson | 8 Feb 20:39
Picon
Gravatar

Java developer new to Scala

Hi people.

My background is in java development so I thought scala should not be that hard to learn.

I think there isn't a better way to learn an new language than to have an actual problem to solve. So the issue I've looked into is to build a simple text parser to change data from MySQL dump file to a format that sqlite would consider correct for init of an database.

My goal of this mail isn't to ask for an solution. I just wanted to get some hints or tips on which concepts to look future into to improve my code. At the moment I've implemented code that could gather all the create statements and create the tables in sqlite.

I'll add my code and an example of an dump from mysql so you'll see what kind of data that could occur during this processing. The code is quite adhoc at the moment so I know I could do alot of simplifications. But because I don't know the language that well and don't have any scala developers closeby so I can't get hints, tips, tricks or pointers to improve either.

------------------------------------------------------------------------- CUT --------------------------------------------------------------------------
import scala.io._
import scala.collection.mutable.ArrayBuffer

class Statement {
  var name = ""
  var sqltype = ""
  var notNullable = false
  var default = ""
  var autoincrement = false
  var sqlStr = ""
  var havePrimeKey = false
   
  override def toString :String = {
    if(sqlStr != "")
      return sqlStr
    if(autoincrement && sqltype.indexOf("int") != -1)
      sqltype = "integer primary key autoincrement"
       
    var str = name+" "+sqltype
    if(notNullable)
      str += " NOT NULL"
    if(default != "")
      str += " DEFAULT "+default
    return str   
  }
}

object ReadFile extends Application {
//  val s = Source.fromFile("dump.sql", "UTF-8")
  val s = Source.fromFile("dump2.sql", "UTF-8")
  var createArr = new Array[String](3)
  var createStatArr = new ArrayBuffer[Statement]
  var createStatement = false 
  val out = new java.io.FileWriter("c:/temp/sqltest/createtables.sql")
  var table = ""
  var havePrime = false

  s.getLines.foreach( (line) => {
    if(line.trim.toLowerCase.startsWith("create")) {
      createStatement = true
      createArr = line.split("`")
      if(createArr.length > 1) {
         table = createArr.apply(1)
         out.write("drop table if exists '"+table+"';\n")
         out.write("create table '"+table+"' (\n")
      }     
    }
   
    if(createStatement && line.trim.startsWith(")")) {
      createStatement = false
      var first = true
      var havePrimeKey = false
      createStatArr.foreach( (stat) => {
         if(!first)
           out.write(",\n")
         out.write("\t"+stat.toString())
         first = false
      })           
      out.write("\n);\n\n")
      createStatArr = new ArrayBuffer[Statement]
      havePrime = false
    }
   
    if(createStatement) {
      if(!(line.trim.toLowerCase.startsWith("create")  ||
          line.trim.toLowerCase.startsWith("primary key") ||
          line.trim.toLowerCase.startsWith("unique key") || 
          line.trim.toLowerCase.startsWith("key") ||
          line.trim.toLowerCase.startsWith("constraint"))
          ) {
       
         createArr = line.trim.split(' ')
         var stat = new Statement
                 
         if(createArr.length > 1) {
            stat.name = createArr.apply(0)
            var linestr = createArr.apply(1)
            if(linestr.endsWith(","))
               linestr = linestr.substring(0, linestr.length()-1);
            stat.sqltype = linestr
             
            if(createArr.apply(1).startsWith("enum"))
               stat.sqltype = "varchar(9)"
            if(line.indexOf("NOT NULL") != -1)
              stat.notNullable = true
            if(line.toLowerCase().indexOf("auto_increment") != -1) {             
              stat.autoincrement = true
              havePrime = true
            }
                           
            for(i <- 0 until createArr.length) {                
              if(createArr.apply(i).compareToIgnoreCase("default") == 0) {
                var linestr = createArr.apply(i+1)
                if(linestr.endsWith(","))
                   linestr = linestr.substring(0, linestr.length()-1);
                if(linestr.compareTo("CURRENT_TIMESTAMP") == 0)
                   linestr = "'0000-00-00 00:00:00'"
                if(linestr.compareTo("'0000-00-00") == 0)
                   linestr = "'0000-00-00 00:00:00'"
                stat.default = linestr
              }
            }
            createStatArr += stat        
         }       
      }
     
      if(
          line.trim.toLowerCase.startsWith("primary key") ||
          line.trim.toLowerCase.startsWith("constraint")
          ) {
         var stat = new Statement
         var linestr = line.trim()

         stat.sqlStr = line.trim
         if(linestr.endsWith(",")) {
            stat.sqlStr = linestr.substring(0, linestr.length()-1);
         }
         if(!havePrime || linestr.indexOf("PRIMARY") == -1)
            createStatArr += stat                         
      }
    }
       
  })

  out.close 
}
------------------------------------------------------------------------- END --------------------------------------------------------------------------

------------------------------------------------------------------------- CUT --------------------------------------------------------------------------
CREATE TABLE `table1` (
  `oneId` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `anotherId` int(11) unsigned NOT NULL,
  `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `theblob` blob NOT NULL,
  `hashKey` varchar(16) NOT NULL,
  PRIMARY KEY (`oneId`),
  UNIQUE KEY `hashKey` (`hashKey`)
) ENGINE=InnoDB AUTO_INCREMENT=240 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = <at> saved_cs_client */;

--
-- Dumping data for table `table1`
--

LOCK TABLES `table1` WRITE;
/*!40000 ALTER TABLE `table1` DISABLE KEYS */;
INSERT INTO `table1` VALUES (1,2,'2010-08-06 11:52:54',0xfaff80988e80eee7798,'fafasd'),(2,142456,'2010-07-30 11:11:29',0xfaff80988e80eee7798,'asfaew'),(3,220748,'2010-08-03 06:16:24',0xfaff80988e80eee7798,'ar5hffgadbf');
/*!40000 ALTER TABLE `table1` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `table2`
--

DROP TABLE IF EXISTS `table2`;
/*!40101 SET <at> saved_cs_client     = <at> <at> character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `table2` (
  `timestamp` bigint(20) NOT NULL DEFAULT '0',
  `type` int(11) NOT NULL DEFAULT '0',
  `id` int(11) NOT NULL DEFAULT '0',
  `data1` int(11) NOT NULL DEFAULT '0',
  `blob1` blob,
  `blob2` blob,
  `bool` tinyint(1) NOT NULL DEFAULT '0',
  KEY `table2Key1` (`type`),
  KEY `table2Key2` (`id`),
  KEY `table2Key3` (`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = <at> saved_cs_client */;
--------------------------------------------------------------------------END --------------------------------------------------------------------------


Best regards

Daniel
Russ P. | 8 Feb 09:04
Picon

preventing addition of Base and Derived classes

Suppose I have the following trivial Base and Derived classes:

class Base() {
    def + (b: Base) = new Base
    }

class Derived() extends Base() {
    def + (d: Derived) = new Derived
    }

object XTest {

    def main(args: Array[String]) {

        val b = new Base
        val d = new Derived

        println()
        println("Base + Base = " + (b + b))
        println("Base + Derived = " + (b + d))
        println("Derived + Base = " + (d + b))
        println("Derived + Derived = " + (d + d))
        println()
        }
    }

The output of the XTest is this:

Base + Base = Base <at> 2ade1cb6
Base + Derived = Base <at> 5c2f06b6
Derived + Base = Base <at> 1361c602
Derived + Derived = Derived <at> 780eb73e

Is it possible to modify this code in such a way that the compiler
allows Bases objects to be added to each other and allows Derived
objects to be added to each other but rejects any attempt to add a
Base and a Derived object? In other words:

Base + Base  <-- compiles
Derived + Derived  <-- compiles
Base + Derived  <-- should not compile
Derived + Base  <-- should not compile

Thanks.

--Russ P.

Eugen Labun | 8 Feb 07:41
Picon

Prepend a directory to Java bootclasspath

Hi All,

for testing purposes, I need to override some core Java classes.

My classes are in the directory <path>.
In a pure Java environment it can be done using "java -Xbootclasspath/p:<path> ..." option.

But how to do that if running a Scala program?

Unfortunately we don't have the "prepend" ("/p")option for manipulating Java bootclasspath. And in 
the "-javabootclasspath" option the whole path must be specified, which is pretty long, and I don't 
know how to get its content from withing a script that runs the Scala program.

I already tried to add "Xbootclasspath" option directly into the Scala starting script:

"%_JAVACMD%" -Xbootclasspath/p:"<path>" %_JAVA_OPTS% %_PROPS% -cp "%_TOOL_CLASSPATH%" 
scala.tools.nsc.MainGenericRunner  %*

(scala.bat / Scala 2.9.1 / Windows XP)

But in this case the Java replacement classes get ignored.

Perhaps someone has a solution?

--
EL

Eric Kolotyluk | 8 Feb 01:39
Picon
Gravatar

File System Traversal

I got some nice code a while ago from Joshua Suereth which included

     // We create a 'collection' that can iterate over files.
     object files extends Traversable[File] {
        override def foreach[U](f: File => U): Unit = {
           // Note we could remove recursion here with some work.  You 
should make this recurse in whatever order you
           // desire for optimum early-exit in your algorithm.
           def iter(file: File) : Unit =
             if(file.isDirectory) file.listFiles foreach iter
             else f(file)
           iter(new File(sourceName))
        }
     }

I was just wondering if there is already something in the Scala 
libraries that does this as it seems like a really common thing to do - 
traverse a set of files and directories.

Scala often seems to have nice little utilities for basic things like 
this, but I am not always sure of the best way to find them. For 
example, it would be nice to just do something like

    val scalaFiles = File("src").traversable.view.filter(_.getName 
endsWith ".scala")

But Scala does not seem to have its own file system API, nor can I find 
anything suitable in Scalaz.

I guess there is the basic question of trade-offs: how much stuff should 
people just know how to do in Scala because it is easy to express (like 
Josh's code) and how much should be found in the libraries because it is 
a common and simple operation.

Cheers, Eric

RANI BEJJANKI | 7 Feb 22:50
Picon
Gravatar

QA Tester



 

Thanks and Regards

Rani

Oberon IT, Inc

1300 W, Walnut Hill Lane, STE 263, Irving, TX-75038.



__________ Information from ESET NOD32 Antivirus, version of virus signature database 6866 (20120207) __________

The message was checked by ESET NOD32 Antivirus.

http://www.eset.com


Gmane