unexpected else in coffeescript when using super - backbone.js

I am using backbone.js, writing it in coffeescript but get this error and am not able to resolve it !
Snippet of the code:
module.exports = class CoreModel extends Backbone.Model
destroyed: false
# Helper to toggle the state of boolean value (using not)
toggle: (key) -> #swap key, invert
# Helper to change the value of an entry using a function.
swap: (key, f) -> #set key, f #get key
toJSON: -> if #destroyed then 'DESTROYED' else super
Error:
[stdin]:11:45: error: unexpected else
toJSON: -> if #destroyed then 'DESTROYED' else super
^^^^
Not sure why this is an unexpected else!

If you are using coffeescript 2, then you need to use parenthesis with super(). The error message here should really be more helpful.
You can read about it in the docs.
module.exports = class CoreModel extends Backbone.Model
destroyed: false
# Helper to toggle the state of boolean value (using not)
toggle: (key) -> #swap key, invert
# Helper to change the value of an entry using a function.
swap: (key, f) -> #set key, f #get key
toJSON: -> if #destroyed then 'DESTROYED' else super()
If you find a situation where you want the old behavior (all arguments are forwarded onto the super call, then you can use this:
foo: -> super arguments...

Related

How to add entries to my map without overwrite existing with a fallback in case of empty

I'm trying to create a map from a list of files that changed in our SCM,
So far I've managed to get the list of the changed files(in the code below I put hard-coded example )
and then map them to the relevant services which I want to build.
I also added the fallback in case the path is not mapped in the "path2component" function.
My problem is that the map that I'm creating is always overriding itself,
and not inserting the entries one after the other as expected.
ChangedFilesList = [main/exporter/pom.xml, main/app/download-server/pom.xml]
ChangedFilesList.each {
println "Changes in file: ${it}"
def file = "${it}"
triggermap = path2component.findAll{ // find relevant map entries
file.find(it.key)
}.collectEntries{ // build your map
["trigger-${it.value}", true]
} ?: ["trigger-none": true] // provide a fallback
println "triggermap:" + triggermap
}
My output is this:
Changes in file: main/app/download-server/pom.xml
triggermap:[trigger-download-server:true]
Changes in file: main/exporter/pom.xml
triggermap:[trigger-rest-exporter:true]
Expected output:
Changes in file: main/app/download-server/pom.xml
triggermap:[trigger-download-server:true]
Changes in file: main/exporter/pom.xml
triggermap:[trigger-download-server:true,trigger-rest-exporter:true]
The following code:
def changedFiles = ['main/exporter/pom.xml', 'main/app/download-server/pom.xml']
def path2component = [
'main/exporter': 'rest-exporter',
'main/app/download-server': 'download-server'
]
def triggerMap = path2component.findAll { path, service ->
changedFiles.any { it.find(path) }
}.collectEntries { path, service ->
["trigger-${service}".toString(), true]
}.withDefault { false }
println triggerMap
println("rest-exporter: ${triggerMap['trigger-rest-exporter']}")
println("unchanged-service: ${triggerMap['trigger-unchanged-service']}")
uses the groovy map withDefault construct to specify a value which should be returned if a key is not found in the map. This code tries to mock your scenario with a path2component map. Result of running the above:
─➤ groovy solution.groovy
[trigger-rest-exporter:true, trigger-download-server:true]
rest-exporter: true
unchanged-service: false
However if they only thing you want to do is figure out if a service needs rebuilding, there is really no need to have the 'trigger-' prefix in there:
def simplerMap = path2component.findAll { path, service ->
changedFiles.any { it.find(path) }
}.collectEntries { path, service ->
[service, true]
}.withDefault { false }
println simplerMap
println("rest-exporter: ${simplerMap['rest-exporter']}")
println("unchanged-service: ${simplerMap['unchanged-service']}")
which prints:
─➤ groovy solution.groovy
[rest-exporter:true, download-server:true]
rest-exporter: true
unchanged-service: false
and if you don't have millions of items in this trigger map (i.e. performance is not an issue), you could also just do:
def changedServices = path2component.findAll { path, service ->
changedFiles.any { it.find(path) }
}.values()
println changedServices
println("rest-exporter: ${changedServices.contains('rest-exporter')}")
println("unchanged-service: ${changedServices.contains('unchanged-service')}")
which prints:
─➤ groovy solution.groovy
[rest-exporter, download-server]
rest-exporter: true
unchanged-service: false
Groovy provides variant of get, that lets you provide a fallback, which also get's written into the map. E.g.:
def m = [a: true]
assert m.get("b", false)==false
assert m.containsKey("b")
Yet, the absence of a key with a regular get will give you null, which is basically false

Maya Python static class function scope

I have some trouble getting my static class to work. There is something I am missing about the scope of functions within a class. If called the script gives me following error:
NameError: global name 'disableCostumFrames' is not defined #
import maya.cmds as cmds
from functools import partial
class Blast:
def createWindow():
# Todo:
# hanldes the gui for the user
windowID = 'window'
if cmds.window(windowID, exists = True):
cmds.deleteUI('window')
window = cmds.window(windowID, title="Blast", iconName='Blast', widthHeight=(400, 200) )
cmds.frameLayout( label='')
cmds.rowColumnLayout( numberOfColumns=4, columnWidth=[(1, 100),(3, 100)] )
cmds.text( label='Start: ' )
global Blast_startFrame
Blast_startFrame = cmds.textField( enable = False)
cmds.text( label=' End: ' )
global Blast_endFrame
Blast_endFrame = cmds.textField( enable = False)
cmds.setParent('..')
cmds.rowColumnLayout( numberOfColumns=2, columnWidth=[(1, 100), (2, 100)] )
cmds.radioCollection()
#cmds.radioButton( label='Full', select = True, onCommand= partial(disableCostumFrames, Blast_startFrame, Blast_endFrame ) )
#cmds.radioButton( label='Costum', onCommand= partial(enableCostumFrames, Blast_startFrame, Blast_endFrame ) )
cmds.setParent('..')
cmds.rowColumnLayout( numberOfColumns=1, columnWidth=[(1, 400), (2, 100)] )
cmds.button( label='Playblast' ,command= 'createPlayblast')
cmds.setParent('..')
cmds.showWindow( window )
return Blast_startFrame, Blast_endFrame
def main():
createWindow()
def enableCostumFrames(Blast_startFrame, Blast_endFrame, *args):
cmds.textField(Blast_startFrame, edit=True, enable=True)
cmds.textField(Blast_endFrame, edit=True, enable=True)
def disableCostumFrames(Blast_startFrame, Blast_endFrame, *args):
cmds.textField(Blast_startFrame, edit=True, text="", enable=False)
cmds.textField(Blast_endFrame, edit=True, text="", enable=False)
How do I need to define these functions within the class? I am calling the module like that:
import sys
Dir = 'c:/Blast'
if Dir not in sys.path:
sys.path.append(Dir)
try: reload(Blast_v011)
except: import Blast_v011
Blast_v011.Blast()
maybe iam doing something wrong on this side? Appreciated any help.
In this case you need to add a self reference to all of the methods in your class. The usual python class looks like this:
class MyClass(object):
def __init__(self):
self.variable = 123
def some_method(self):
print "my variable = ", self.variable
def some_other_method(self):
if self.variable > 1:
self.some_method()
The self reference in the member functions is how you get at class member variables and other functions -- it's python's way of referring to what other languages call this.
Instance methods can only be called on an instance (it's the instance that gets passed in as self). You can make a method that is called on the class itself -- rather than any particular instance of the class -- using the #classmethod decorator. Classmethods also take an argument, but instead of self it's a reference to the class. You use it the same way to get variables defined at the class level, which are shared by all copies of the class:
class HasShared(object):
shared = 99
#classmethod
def a_class_method(cls):
print cls.shared
(You can mix and match class and instance methods in the same class).
You can also make static methods using the #staticmethod decorator. These don't get a default argument at all:
class NotPythonic(object):
#staticmethod
def needs_no_args():
print "call me as NotPythonic.needs_no_args()"
In Python we tend to avoid this formula, since you can get a static method by just creating a function in a module without making a class to hold them. For the example code you posted, I'd probably just make a conventional class using instance methods, since your functions need the names of the gui widgets to be able to actually ask them questions.

$timeout cannot find my variable

Ok using Angular and Coffeescript here the following works:
angular.module 'someApp'
.factory 'someFactory', ($timeout) -> new class SomeClass
constructor: ->
#humans = 1
findHuman: ->
$timeout((=>#humans+=1), 1000)
Which is fine I guess but I'd like to have the #humans+=1 part somewhere else.
So why does this not work?
angular.module 'someApp'
.factory 'someFactory', ($timeout) -> new class SomeClass
constructor: ->
#humans = 1
findHuman: ->
$timeout(addOneHuman, 1000)
addOneHuman = =>
#humans+=1
Testing around with console.log or $log, adding #'s here and there, -> instead of => sometimes the variable humans is NaN, sometimes it is undefined.
What do I have to do to make this work? :)
I don't know the Angular side of things that well but I think your problem is that this:
addOneHuman = =>
doesn't do what you think it does. Something like this:
class C
f = ->
m: ->
creates f as essentially a private function within C. The JavaScript version is equivalent to:
var C = (function() {
function C() {}
var f = function() {};
C.prototype.m = function() {};
return C;
})();
so f is just a variable that references a function and f is in scope for anything in C. Changing it to:
f = =>
doesn't do anything because there is no this that applies when f is defined. On the other hand, m is a method (note the C.prototype.m in the JavaScript version) so there is an applicable this and m: => can do something useful.
You just want your addOneHuman to be a method rather than a plain old function:
addOneHuman: =>
# ---------^
There might be something useful to you in a couple of my other answers:
coffeescript scope of variable assignment vs property assignment in object's other properties
How to make method private and inherit it in Coffeescript?

get classOf[Array[A]] from classOf[A]

I have a list of scala classes in the form like:
List(classOf[A], classOf[B], ...)
I need to register these classes as well as the array of the classes into kryo. The result is like:
kryo.register(classOf[A])
kryo.register(classOf[Array[A]])
kryo.register(classOf[B])
kryo.register(classOf[Array[B]])
...
So, with the list at hand, I may just use a foreach to register both the class and the array of the class.
However, I fail to get classOf[Array[A]] from classOf[A]. I have tried the ClassTag as following method:
def getArrayClass[T: ClassTag](c: Class[T]): Class[_] = {
classOf[Array[T]]
}
The result is not the right (though the type of the both results is the same), and kryo still complains that Class is not registered: A[].
scala> getArrayClass(classOf[A])
res0: Class[Array[A]] = class java.lang.Object
scala> classOf[Array[A]]
res1: Class[Array[A]] = class [LA;
Any clues? Thanks.
You can do it using the wrap method ClassTag:
def getArrayClass(c: Class[_]): Class[_] =
scala.reflect.ClassTag(c).wrap.runtimeClass
Note that this does not work if c is classOf[Null] or classOf[Nothing] (I believe this is bug in ClassTags). For any other Class, it will work.
You can also go to the Java way of doing it, without ClassTags, which is basically equivalent:
def getArrayClass(c: Class[_]): Class[_] =
java.lang.reflect.Array.newInstance(c, 0).getClass

Tuple case mapping don't work with generic Array[T] in scala

I don't understand why the compiler cannot understand the case instruction mapping on tuple when i try to use with generics Array[T].
class Variable[T](val p: Prototype[T], val value: T)
class Prototype[T](val name: String)(implicit m: Manifest[T])
// Columns to variable converter
implicit def columns2Variables[T](columns:Array[(String,Array[T])]): Iterable[Variable[Array[T]]] = {
columns.map{
case(name,value) =>
new Variable[Array[T]](new Prototype[Array[T]](name), value)
}.toIterable
}
Error say :
error: constructor cannot be instantiated to expected type;
found : (T1, T2)
required: fr.geocite.simExplorator.data.Variable[Array[T]]
case(name,value) =>
I'm also not sure about the wording of the error, but first of all, you will need the manifest for T because it is required for constructing new Prototype[Array[T]] (the array manifest can be automatically generated if a manifest for its type parameter is in scope).
Is there any reason you absolutely need arrays? They come with the irregularity of Java's type system, they are mutable, and they offer very little advantage over for example Vector. Lastly, and that's probably why carry around the manifests, unlike arrays standard collections do not require manifests for construction.
class Variable[T](val p: Prototype[T], val value: T)
class Prototype[T](val name: String)
implicit def cols2v[T](cols: Vector[(String,Vector[T])]): Vector[Variable[Vector[T]]] =
cols.map {
case (name, value) => new Variable(new Prototype(name), value)
}

Resources