Using Closure compiler with Underscore.js _.template - google-closure-compiler

Is there any way to compile Underscore.js templates on the server and get the Closure compiler to work with the generated code?
The main problem is that _.template:
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};
generates JavaScript with a with-statement in it. The two obvious routes are:
modify Underscore.js's _.template not to generate withs
coerce Closure into playing nice
Is the second option possible?

Generally, the JS engines perform better without "with", so if generating it without "with" is an option that is likely the best solution.
Otherwise your options depend on whether you are hoping to using Closure Compilers ADVANCED mode. In SIMPLE mode, the compiler won't rename your properties on the template, and will assume that any undeclared variable are globals. So as long are your template object isn't causing any local variables to be shadowed it might "just work".

Related

Cannot identify language in SALT

I just started using SALT for a project i am working on. It is said to work with Python but I find quite a bit of difference in thier syntax and overall format. I have pasted a code for a simple task which just opens and imports and loads some libraries onto the SALT console. I hope someone can check abnd see if he/she can instantly identify the language being used and what the code does. This is because i have a suspicion that the code is a mixture between C, Python as well as Java... if that is so doen't that mean it should be a totally different language on its own?
code:
var rtwxlib = import'rtwxlib';
var string = import'string';
var monitor = rtwxlib.Monitor
{
EvActivate = func() { print "Activate\n"; };
EvShutdown = func() { print "Shutdown\n"; };
EvProgress = func(self, fDone, msg = "") {
print("Progress: %d %s \r"::format(fDone*100, msg));
};
EvEventMsg = func(self, msg) {
print("\nEvent: %s\n"::format(iStat, msg));
};
};
var solver = rtwxlib.Solver(monitor);
solver::Open("test.wrx");
solver::DelGeometry();
solver::SaveAs('testresults.wrx');
solver::Close();
I was able to indentify the syntax of the language used as C. I beieve the problem I had which confused me was the libraries used for this code which I later found out was for a particular program. Thank you to all those who tried to help though :)

Getting errors when Browsery bundle with SquishIt

I am currently refactoring the javascript portions of a web site, and now I have bundled some scripts together using Browserify. The resulting script is bundled along with other resources using SquishIt. In Debug mode, when SquishIt is not bundling all the scripts together everything seems to work just fine, but when running in Production, and SquishIt bundles everything together I get errors from the Browserify part of my bundle. The error is complaining that r has no length property (see line 18) below. This part of the code is created by Browserify when bundling the scripts.
(function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f
}
var l = n[o] = {
exports: {}
};
t[o][0].call(l.exports, function(e) {
var n = t[o][1][e];
return s(n ? n : e)
}, l, l.exports, e, t, n, r)
}
return n[o].exports
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s
})({
I really can't think of anything that using SquishIt to bundle all the scripts would break the logic of the browserified scripts. What could be the cause of this? This gist shows the entire source code, in case that is relevant.
I have not changed anything on the ASP.NET side (in the bundling), and the relevant part of my ´Head.ascx´ looks like this:
Bundle.JavaScript()
.Add(Assets.JavaScript.GetUrl("main.js").ToString())
.Add(Assets.JavaScript.GetUrl("Plugins/raphael-min.js").ToString())
.Add(Assets.JavaScript.GetUrl("Plugins/vector_map.js").ToString())
// more ...
.Render("~/Content/"+Assets.VersionString+"/Scripts/Combined/combined.js")
Have a look at this comment it may help https://github.com/jetheredge/SquishIt/issues/320#issuecomment-139921409
Is there a reason you need to use two different bundling solutions?

How to optimize CasperJS project using Google Closure?

I'm trying to optimize the CasperJS tests run.js code(https://github.com/n1k0/casperjs/blob/master/tests/run.js), so that I could understand how I can use it further to optimize further the tests that I've written. Here's the sample run.js of the CasperJS project that I was trying to optimize using ADVANCED_OPTIMIZATIONS flag to the compiler.
(https://github.com/n1k0/casperjs/blob/master/tests/run.js)
But the optimized code is as below:
phantom.d || (console.log("This script must be invoked using the casperjs executable"), phantom.c(1)); var a = require("fs"), c = require("utils").h, d = require("casper").create({g:!1}); d.options.n = d.a.get("direct") || !1; d.options.i = d.a.get("log-level") || "error"; d.m("open.location", function(b) { return!/^http/.test(b) ? c("file://%s/%s", phantom.e, b) : b }); var e = []; d.a.b.length ? e = d.a.b.filter(function(b) { return a.isFile(b) || a.isDirectory(b) }) : (d.f("No test path passed, exiting.", "RED_BAR", 80), d.c(1)); d.test.j("tests.complete", function() { this.k(true, void 0, d.a.get("xunit") || void 0) }); d.test.l.apply(d.test, e);
Obviously, this is failing as being told by the compiler (Ex: JSC_INEXISTENT_PROPERTY: Property casperLoaded never defined on phantom at line 2 character 5
if (!phantom.casperLoaded) )
Can you please guide me as to how to use the Closure Compiler, to optimize all of the JS files in the project with their dependencies, thus avoiding these errors and proceed further.
I went through the documentation for the Closure, but I wasn't able to figure out the approach needed in this case.
FYI: I was using the Closure compiler.jar
Support has been added to Closure Compiler to make it is easier to work with Common JS and AMD/require.js modules using the following compiler flags:
--transform_amd_modules
--process_common_js_modules
--common_js_entry_module
--common_js_module_path_prefix
See Experimental support for Common JS and AMD/require.js modules in Closure Compiler

Dynamic properties in Scala

Does Scala support something like dynamic properties? Example:
val dog = new Dynamic // Dynamic does not define 'name' nor 'speak'.
dog.name = "Rex" // New property.
dog.speak = { "woof" } // New method.
val cat = new Dynamic
cat.name = "Fluffy"
cat.speak = { "meow" }
val rock = new Dynamic
rock.name = "Topaz"
// rock doesn't speak.
def test(val animal: Any) = {
animal.name + " is telling " + animal.speak()
}
test(dog) // "Rex is telling woof"
test(cat) // "Fluffy is telling meow"
test(rock) // "Topaz is telling null"
What is the closest thing from it we can get in Scala? If there's something like "addProperty" which allows using the added property like an ordinary field, it would be sufficient.
I'm not interested in structural type declarations ("type safe duck typing"). What I really need is to add new properties and methods at runtime, so that the object can be used by a method/code that expects the added elements to exist.
Scala 2.9 will have a specially handled Dynamic trait that may be what you are looking for.
This blog has a big about it: http://squirrelsewer.blogspot.com/2011/02/scalas-upcoming-dynamic-capabilities.html
I would guess that in the invokeDynamic method you will need to check for "name_=", "speak_=", "name" and "speak", and you could store values in a private map.
I can not think of a reason to really need to add/create methods/properties dynamically at run-time unless dynamic identifiers are also allowed -and/or- a magical binding to an external dynamic source (JRuby or JSON are two good examples).
Otherwise the example posted can be implemented entirely using the existing static typing in Scala via "anonymous" types and structural typing. Anyway, not saying that "dynamic" wouldn't be convenient (and as 0__ pointed out, is coming -- feel free to "go edge" ;-).
Consider:
val dog = new {
val name = "Rex"
def speak = { "woof" }
}
val cat = new {
val name = "Fluffy"
def speak = { "meow" }
}
// Rock not shown here -- because it doesn't speak it won't compile
// with the following unless it stubs in. In both cases it's an error:
// the issue is when/where the error occurs.
def test(animal: { val name: String; def speak: String }) = {
animal.name + " is telling " + animal.speak
}
// However, we can take in the more general type { val name: String } and try to
// invoke the possibly non-existent property, albeit in a hackish sort of way.
// Unfortunately pattern matching does not work with structural types AFAIK :(
val rock = new {
val name = "Topaz"
}
def test2(animal: { val name: String }) = {
animal.name + " is telling " + (try {
animal.asInstanceOf[{ def speak: String }).speak
} catch { case _ => "{very silently}" })
}
test(dog)
test(cat)
// test(rock) -- no! will not compile (a good thing)
test2(dog)
test2(cat)
test2(rock)
However, this method can quickly get cumbersome (to "add" a new attribute one would need to create a new type and copy over the current data into it) and is partially exploiting the simplicity of the example code. That is, it's not practically possible to create true "open" objects this way; in the case for "open" data a Map of sorts is likely a better/feasible approach in the current Scala (2.8) implementation.
Happy coding.
First off, as #pst pointed out, your example can be entirely implemented using static typing, it doesn't require dynamic typing.
Secondly, if you want to program in a dynamically typed language, program in a dynamically typed language.
That being said, you can actually do something like that in Scala. Here is a simplistic example:
class Dict[V](args: (String, V)*) extends Dynamic {
import scala.collection.mutable.Map
private val backingStore = Map[String, V](args:_*)
def typed[T] = throw new UnsupportedOperationException()
def applyDynamic(name: String)(args: Any*) = {
val k = if (name.endsWith("_=")) name.dropRight(2) else name
if (name.endsWith("_=")) backingStore(k) = args.first.asInstanceOf[V]
backingStore.get(k)
}
override def toString() = "Dict(" + backingStore.mkString(", ") + ")"
}
object Dict {
def apply[V](args: (String, V)*) = new Dict(args:_*)
}
val t1 = Dict[Any]()
t1.bar_=("quux")
val t2 = new Dict("foo" -> "bar", "baz" -> "quux")
val t3 = Dict("foo" -> "bar", "baz" -> "quux")
t1.bar // => Some(quux)
t2.baz // => Some(quux)
t3.baz // => Some(quux)
As you can see, you were pretty close, actually. Your main mistake was that Dynamic is a trait, not a class, so you can't instantiate it, you have to mix it in. And you obviously have to actually define what you want it to do, i.e. implement typed and applyDynamic.
If you want your example to work, there are a couple of complications. In particular, you need something like a type-safe heterogenous map as a backing store. Also, there are some syntactic considerations. For example, foo.bar = baz is only translated into foo.bar_=(baz) if foo.bar_= exists, which it doesn't, because foo is a Dynamic object.

Retrieving values of MS CRM fields through variable

I have a question about the Dynamics CRM 4.0 Webservice. I've been using it to get records from CRM into ASP.NET. After the request and the casting, the values of the columns (for instance for a contact) can be accessed through;
BusinessEntity be = getBusinessEntity(service, crmGuid, type, colnames);
contact tmp = (contact)be;
Response.Write("firstname: " + tmp.firstname + "<BR>");
Response.Write("lastname: " + tmp.lastname+ "<BR>");
I have an array of strings which identify which columns should be retrieved from CRM (colnames), for instance in this case {"firstname", "lastname"}.
But colnames can become quite big (and may not be hardcoded), so I don't want to go through them one by one. Is there a way to use something like
for(int i = 0; i < colnames.length; i++)
{
Response.write(colnames[i] + ": " + tmp.colnames[i] + "<BR>");
}
If I do this now I get an error that colnames is not a field of tmp.
Any ideas?
Not using BusinessEntity (unless you use reflection). DynamicEntity is enumerable by types deriving from Property. You'll have to do something like (I did this from memory, so might not compile)...
for(int i = 0; i < colnames.length; i++)
{
string colName = colnames[i];
foreach(Property prop in tmp)
{
if (prop.name != colName)
continue;
if (prop is StringProperty)
{
var strProp = prop as StringProperty;
Response.Write(String.Format("{0}: {1}<BR />", colName, strProp.Value));
}
else if (prop is LookupProperty)
{
...
}
... for each type deriving from Property
}
}
Reply to Note 1 (length):
Could you give me an example of what you're using. If you are only looking at the base types (Property) then you won't be able to see the value property - you'll need to convert to the appropriate type (StringProperty, etc).
In my example tmp is a DynamicEntity (it defines GetEnumerator which returns an array of Property). The other way to access the properties of a DynamicEntity is using the string indexer. For tmp:
string firstname = (string)tmp["firstname"];
Note that if you use this method, you get the Values (string, CrmNumber, Lookup) and not the whole property (StringProperty, CrmNumberProperty, etc).
Does that answer your question? Also, I recommend using the SDK assemblies and not the web references. They're much easier to use. The SDK download has a list of helper classes if you choose to use the web references, however. Search "Helper" in the SDK.

Resources