Changelog
29/04/2019
- Fixed auto fight min %
- Fixed auto shipyard warp
- Fixed auto fleet upgrade preventing from modify ships design
- New formula for enemy defense, now star and increase slowly
v0.1 - 28/04/2019
-
Naval capacity capped ad 10k because of performance. Naval capacity now is
more difficult to obtain but larger ship require less.
- Removed limited storage from metal, crystal and alloy.
-
Fixed Automators saving and now automators don't reset with prestige.
- Added options to search for custom level with Search Automator.
- Added shipyard warp automator.
-
"Expensive / Economic" mod now stack additive instead of multiplicative.
- Missile and nuke buff.
- Prestige rest.
- Changed "+200% energy" prestige to "+400% research".
- Fixed minor some minor bugs and descriptions.
- Increased search required.


About US
Quality is not an act, it is a habit”– Aristotle
For us every client interaction, every assignment and every task is an oppurtunity to add value. For us attention to detail is imperative. We ensure all processes are followed and quality work is delivered and that is what makes us stand apart and helps our cleints stand out of their competition as well.
We help busineses from all over the world and from different areas of expertise. When we help you with your tasks, and assign you remote employees, it is done very carefully. We have taken our years of expereince to help us shape our hiring, trainning and selecting the best out of the best candidates out there. We offer you support from assistants who are the best fit for the job at hand and skilled to take on challenges & learn each day with a smile.
Solutions that match your growth and assistants that are a fit for the role. When you want to scale up or down, have new products or services to launch, we help you with all the support that you need, right from the admin side of things to the more technical needs of the project at hand. We are your global outsourcing partner who offers you flexibility and scalability that is right for you.


The web is abuzz right now with ecmascript 6 on the horizon. If you get node 0.11,
you can use it server side already. Once of the big features I’m excited about
are generators.
I’ve blogged about them previously
Alas, I’ve only found nothing out there on the web that covers anything beyond basic
instatiation and invocation. With just that to go on, it was hard for me to initially see
the hype. A few days ago, I had an appifany.
Generators are first class objects. Like functions, they can be composed from smaller parts. Therefore,
much of we know about functions can be applied to generators!
On that note, I will lay the ground work for understanding how to really USE generators.
It all starts with a bind
If you’ve worked with javascript for any of length of time, You should be familiar with bind.
Called: running the function which gives us its return value along with side effects.
1
something();
The bind is implimented by taking a literal function and calling it within another
literal function passing along the context and possible arguments using .apply().
Instantiated: a runnable instance is created by calling the Generator function
1
vargen=Gen();
Run: You can then iterate through the generator by calling next()
1
gen.next();
Unlike a function, We are going to compose generators to be run inside of a co() function.
Co will run a generator until it comes accross a yield. Whatever is on
right side of the yield will be passed into co. the generator will be frozen until the
value can be resolved. This includes thunks, promises and even other generators!
A generator equivilent for a bind looks like this.
Like functions, generators also have a call() and apply() methods which can be used
to invoke the function with an explicit context. The yield is there because when we
run this new function inside co(), the instantiated generator will be run and the
return value will be be spat out to be returned by this generator.
With that in mind, How about a function that takes two generators and runs one inside
the other? How would we impliment that?
If you are interested in exploring this subject further, I’m working on a javacript
library for composing generators called Shen.
Its a toolkit for composing generators for running inside co like lego pieces.
To give you a taste of its power, Instead of join,
Shen implements cascade which allows you to
merge 1 or more generators.
varshen=require('shen');co(shen.cascade(function*(next){//each yield freezes the generator until the next returns.console.log(1);yieldnext;console.log(1);return;},function*(next){console.log(2);yieldnext;console.log(2);return;},shen.cascade(function*(next){//thats right, you can nest them too!console.log(3);returnyieldnext},function*(){return})))();/* Outputs 1 2 3 2 1 */
Shen functions all compose with each other allowing you to put together generators
as easily as you would curry a function.
In addition to cascade and bind, Shen also currently includes…
branch and dispatch for conditional logic
delay for… delaying?
parallel: run several generators and get back an array of the return values
oscillator: run a generator at a specific interval and get back an immediate event emitter
that fires with the latest returned value of the generator
Current use-cases off the top of my head include using oscillator and parrallel to run several
network requests at the same time. you’d get an event emitter with all the returned values in
one place. One thing to note is that you can’t completely escape callbacks but you can create
areas in your code where callbacks are invisible. The generator takes care of the hard stuff.
Its still very much a work in progress and only works on node 0.11 but I invite you all to try it out.
If you want to help, I’m always welcome to new ideas for pieces to add to the ecosystem.
contributing a few tests or implementations of ideas would be great too!
Note: you need to run node 0.11 with –harmony to run the code.
From the creators of express comes a brand new framework for node powered by
the new ecmascript 6 generators syntax. Koa is an interesting
reimagining of how we will be able to build web applications in javascript.
The old paradigm
In the standard node library, The ‘http’ module is used to create servers.
12345678
varserver=http.createServer(function(req,res){res.writeHead(200,{'Content-Type':'text/plain'});//server logic goes hereres.end('');});server.listen(3000,'<IP_ADDRESS>');console.log('listening on port 3000');
Express exposes a function that we can give to
http.createServer as a callback. Express middleware is a set of functions that
take 3 arguments, req, res and next. The middleware performs some operations, modifies
either the request or response objects and passed down to the next middleware in the stack
by calling next(). Its akin to a water flow model where the the response ends somewhere
near the end of the middleware stack.
Enter Koa, The generators based framework
Like express, Koa works internally by generating a callback that can be passed to
http.createServer(). Unlike Express, it uses generators to provide a much more fine grained
model of control flow.
A very basic koa app looks like this, lets make it serve up the contents of a file
123456789101112131415161718192021
varkoa=require('koa');varPromise=require('bluebird');//creates promise yielding versions of fsvarfs=Promise.promisifyAll(require('fs'));//create the koa instancevarapp=koa();app.use(function*(next){//here's an example middleware that logs to the consoleconsole.log('timestamp: before request => ',time.now());yieldnextconsole.log('timestamp: after request => ',time.now());});app.use(function*(){this.body=yieldfs.readFileAsync('./app.js','utf8');});app.listen(3000);console.log('now listening on port 3000');
Unlike Express, the middleware is written using generators.
Downstream middleware in Koa flows upstream on return. Middleware
yields down stream by explicitly calling ‘yield next.’. Upon return, the control
flow yields back up to where the upstream middleware yielded downstream.
Where Express passes native node req and res objects through to each function, Koa
manages a context where it encapsulates them behind an interface. They are still available
through the ‘this’ keyword as this.req and this.res. However, Its not reccomended in
the docs that you work with these native objects. One could imagine calling this.res.end(”)
would throw a monkey wrench in the control flow. Instead you are supposed to work through
the this.response and this.request. Most of the methods are aliased directly to this. ‘this.body’
for example, is aliased to this.response.body.
There does not yet appear to be a direct way to get
to the request body. The co-body parser accesses the req.body directly so while the docs say
don’t do it, Koa is still young so you may have to get your hands dirty.
A Todo app in koa
Now that we’ve covered the basics, lets try something a little more complex. A todo
List seems like a good thing no one has ever tried to make before in any technology ever!
To simplify assumptions, lets just store the todos in memory.
By itself, Koa is very minimalistic. It does not provide body parsing, sessions, or
routing in the core. Unfortunately Koa is still young so there just aren’t that many
npm modules for it just yet. A quick search on the Koa website
shows that we do have the necessary modules for a basic todo.
//jshint esnextvarkoa=require('koa');varstaticServer=require('koa-static');//this allows us to parse the native req object to get the bodyvarparse=require('co-body');varrouter=require('koa-route');var_=require('underscore');varPromise=require('bluebird');varpath=require('path');varfs=Promise.promisifyAll(require('fs'));varapp=koa();//our very basic data storevartodos=[];//gets us unique idsvarcounter=(function(){varcount=0;returnfunction(){count++;returncount;};})();//serve up the public directory where we have all the assetsapp.use(staticServer(path.join(__dirname,'public')));app.use(router.post('/todos',function*(){/* yield lets us pass asynchronous functions that return promises or thunks It will freeze the middleware till its resolved and pass it back in. */vartodo=(yieldparse.json(this));todo.id=counter();todos.push(todo);this.body=JSON.stringify(todos);}));app.use(router.get('/todos',function*(){this.body=JSON.stringify(todos);}));app.use(router.delete('/todos/:id',function*(id){todos=_(todos).reject(function(todo){console.log('what? ',todo,id);returntodo.id===parseInt(id,10);},this);this.body=JSON.stringify(todos.sort(function(a,b){returna-b;}));}));app.listen(3000);console.log('listening on port 3000');
The ‘yield’ keyword ca do some interesting things. If we pass into it
an asynchronous function that returns a thunk or promise, it will stop execution of
the middleware and wait till it resolves. It then returns the value of the promise or thunk
and resumes the generator. This is a hell of a lot easier to read.
A word of caution
The ‘yield’ keyword lets us do some safe blocking but it isn’t always the ideal solution.
While the event loop itself isn’t blocked by it the way futures can, it does block resuming
of any operations that occur after it.
For example, if we run three asynchronous operations top to bottom that do not depend on
each other, like the following…
This completely defeats the purpose of node’s (almost automatic) concurrency. When we call
async1, we are blocking until async2 runs. This is unoptimal. It would be better to get the promises
for the three functions and yield on a merged promise.
I’m excited to cut my teeth on some bigger problems. As the framework matures, Its going to
allow more fine grained control for how we write the next generation of web applications.
Ecmascript 6 (harmony) is coming out soon and one of the most exciting features
it offers are generators. Generators are a minimalist flow control system that gives
a much finer grained level of control than we were afforded up till now.
Note: the code in this blog will only run in node v0.11.x when run as –harmony.
Like a function, a generator is an object that declares some behavior. Its first class
just like javascript functions and you can pass it around as values and return them from other
functions.
A generator is declared like a function only with a ‘*’ before the parens.
We then create an instance of the generator by calling it.
When we run gen.next(), the code executes until we get to yield. The generator
then stops which is why the console.log() does not get called. The state of the
generator is returned by next which gives us two things.
state.value: the value on the right side of the yield; in this case 5.
state.done: a boolean that returns true if there are no more yields in the generator.
We’ve called gen.next() the one time. The second time we call gen.next(), we have the option
of passing in an argument to it that will be returned by yield inside the generator.
This example shows a more advanced example of bidirectional passing.
123456789101112131415161718
varmyGenerator=function*(){varfirstWord=yield5;console.log(firstWord);//=> "hello"varsecondWord=yield10;console.log(secondWord);//=> "world"};vargen=myGenerator();varstate=gen.next();console.log(state.value);//=> 5state=gen.next("hello");//=> 'hello' gets printed to the screen from inside the generatorconsole.log(state.value);//=> 10console.log(state.done);//=> falsestate=gen.next('world');//=> 'world' gets printedconsole.log(state.value);//=> 10console.log(state.done);//=> true
One of the biggest growing pains of javascript development is wrapping one’s
head around async programming and functions run asyncronously. Promises give us a
value that represents the eventual value returned from an asynchronous function.
Promises are promised in ecmascript 6 but they aren’t available when I run node 0.11
with –harmony yet so I use Bluebird
1234567891011
varPromise=require('bluebird');//extends node's fileSytem with versions of the async functions that return promises//the promisified versions are the original name + 'Async'varfs=Promise.promisifyAll(require('fs'));fs.readFileAsync('.gitignore','utf8').then(function(contents){console.log(contents);// prints the contents of the .gitignore file.});console.log('this runs before the callback passed to "then" which is counterintuitive.')
This code Works because when the function is called, it creates a closure that doesn’t get
garbage collected because the function passed to the promise retains a reference to this scope.
When its called, it can operate on variables in this containing scope. However we
cannot return to the original function call. Thus Unless you are used to thinking about promises,
its a bit unintuitive that the console.log on the following line runs before the callback passed
to the then() handler of the promise.
Generators on the other hand, let us FREEZE the execution context until the file resolves.
There’s an excellent library called
co from the creator of express that allows
us to create coroutines using generators. thus we could write the previous code using
generators.
123456789101112
varPromise=require('bluebird');varfs=Promise.promisifyAll(require('fs'));varco=require('co');co(function*(){vara=yieldfs.readFileAsync('.gitignore','utf8');console.log(a);//this doesn't run until the previous function resolves.varc=yieldfs.readFileAsync('package.json','utf8');console.log(a);console.log(c);return;})();
This is pretty exciting, This Asyncrouous code looks downright synchronous. Its also running
in its own context so it doesn’t block the event loop. Within the generator, we can write
much more fine grained flow control for asynchronous functions.
That said, how does co work? The basic premise is that we use yield to pass back the promise
into co where it waits till the function resolves. Then we call the next() of this function
passing in the value from the resolved promise.
co itself is extremely flexible allowing you to pass in thunks, or A+spec promises into
yield. Here I’ll demonstrate a simplified version that can accept only promises.
varco=function(fngen){/* next takes a instatiated generator and calls and a value returned from calling next on it gen is an instance of a generator yieldable is the value returned from calling gen.next() */varnext=function(gen,yieldable){if(!yieldable.done){//if //we assume yieldable.value is a promise so we call then() to get the valueyieldable.value.then(function(val){/* we call next on gen and pass in the value into gen.next() to inject the value back into out coroutine where it gets returned by the yield in the generator. By call gen.next(val), gen resumes execustion passing val back and gen.next() return when it hits the next yield keyword returning the value passed in to yield. */next(gen,gen.next(val));});}};returnfunction(){//instatiate the generatorvargensym=fngen();//get the first yieldablevaryieldable=gensym.next();if(!yieldable.done){next(gensym,yieldable);}};};
The concept is pretty simple, yield passed back the value on the right to gen.next()
which it returns. The value we pass into the gen.next call to gen.next() becomes
the value returned by yield. Sorta like a zig zag or a needle stitching.
I’m excited to see some of the new projects that will take advantage of this new
ecmascript 6 feature. One big example comming to mind is the new koa framework. Unlike
its predecessor express/connect, Koa is a set of pluggable middleware components
that utilize generators heavily for flow control.
I’ve been building large scale applications in Backbone for about 8 months now.
In that time I’ve used throax as well as building custom solutions in backbone.
Last night, I live coded the creation of a demo backbone framework similar in features
to Thorax.
When building a large scale Backbone, there are several consderations to consider.
How are we going to have templates load? Inline html declarations in the views do not scale
how do we handle render?
how do we handle child views?
By default, backboneView.render() is a noop. Its meant to be overidden. Backbone.Events gives us
a nice set of methods to allow Backbone objects to listenTo() events off each other, However, the
actual bindings and callbacks are left to the implimenter.
Loading Templates
the first thing is figure out how we want the templates to load. If using a tool like require.js
or browserify, there are plugins for automatically compiling templates and sending to the client
just a compiled template function we can plug into out view. Since I’m trying to keep it simple,
the easiest way to get templates is to wrap your templates in a script tag. To prevent the browser
from executing it as javascript, we add a type that is not ‘text/javascript’.
Transforming these into working templates is fairly straightforward. For each
script tag with type=”text/template”, run the template compiler over the html inside and
store it somewhere. In this case I add a data-name attribute which will be the key for the
hash I store the compiled template in.
In this version, I chose to use express + jade, Of course writing underscore templates
in jade seemed a little odd so I delegated those to jade’s include statement. I know there
are projects like jade-browserify so maybe I’ll eventually update this using just jade.
doctype html
htmlheadtitle=titlelink( rel="stylesheet",href='/components/bootstrap/dist/css/bootstrap.css')
link( rel="stylesheet",href='/stylesheets/style.css')
script( src="/components/jquery/jquery.js")
script( src="/components/bootstrap/dist/js/bootstrap.js")
script( src="/components/underscore/underscore.js")
script( src="/components/backbone/backbone.js")
script( src="/javascripts/base.js")
script( src="/javascripts/application.js")
bodyblock content
script(type="text/template",data-name="main")
include templates/main.html
script(type="text/template",data-name="header")
include templates/header.html
script(type="text/template",data-name="menuLinks")
include templates/menulink.html
script( src="/javascripts/init.js")
The actual contents of the underscore templates in the *.html templates will
now be compiled and loaded into “templates[data-name]” where I can access it later.
Creating our own Base Backbone Objects.
The first thing we want to do is determie the shared behavior of backbone objects
in our app. For special cases we can overide them later. However, for the sake of time, we
want some decalrative way of telling the object what template to use and a default render()
method that we can use in most situations.
//first we declare a namespace to store these new Objectsapplication={};application.BaseView=Backbone.View.extend({initialize:function(){Backbone.View.prototype.initialize.apply(this,arguments);if(this.model){this.listenTo(this.model,'change',this.render);}/* if the BaseView is extended with a tpl string, we want to have that be available but we also want to be able to load it at runtime and have it overide the base tpl string */this.tpl=options.tpl||this.tplthis.loadTemplate(this.tpl);}loadTemplate:function(tpl){/* if tpl is a function, we assign it directly, otherwise, if its a string, we look it up in our templates map. */if(_.isFunction(tpl)){this.template=tpl;}elseif(_.isString(tpl)){this.template=template[tpl];}else{thrownewError('tpl must be a function or a string!');}}render:function(){//see below}});
Next up we need to create a render function. Its arbitrary based on the particular
needs of your application. For most purposes however, Its sufficiant to make a
view’s model’s attributes available inside the templates.
12345678910
//from the render in the preceeding examplerender:function(){this.$el.html('');//empty the view's nodevarcontext={};//create a context objectif(this.model){_.extend(context,this.model.attributes);}this.$el.html(this.template(context));returnthis;}
Here’s a great first start. Now any View that extends BaseView will have a
render. The only interface we must follow is that the View have a model
and a tpl which tells the View how to resolve this.template.
Of course there’s a major component missing. Any good backbone framework
has a way of embedding subViews. Turns out its sort of tricky.
The Lifecycle of a Backbone view in this case is to listen to changes on
model and call render() which updates the view’s $el property. Thus its
impossible to proceed until this.$el is completely demystified.
what is $el?
I’ve heard alot of confusion about the nature of ‘this.$el’. Typically, a Backbone
View is a controller for a node. This node is a structure relevant to the
document object model.
you may be familiar with a dom object if you’ve used jquery.
12
var$body=$('body');// => returns a jquery wrapped object$body[0]//returns the wrapped object representing the body dom node.
In much the same way, a backbone view is a controller for a dom object.
You may have seen the kickstart for a backbone app that involves doing a jquery
lookup on a node and setting its html to your view’s $el property
Assuming the render() method of the view returns ‘this’, then calling it before calling the
$el property guarantees that the dom object managed by the view will be updated before being
placed in the dom. When render() is called again, it updates the contents of that $el. The
$container has a reference to $el stored in it thus ensuring that calling render() will change
the webpage to reflect the latest state of the model.
Extending out Render() to support subViews.
With the afformentioned definition of $el in mind, The best way to embed a subview
(with string based template engines, you do something else with dom based ones.) is to do an
initial render of the dom node marking off somehow places to embed subviews. Then afterwards,
go back through the $el and systematically embed $el for each subview in their respective places.
12345678910111213141516171819202122232425262728
//updated render()this.$el.html('');varcontext={};context._subView=function(viewName){return'<div class="subView view-'+viewName+'"></div>';};if(this.model){_.extend(context,this.model.attributes);}//pop it in the domthis.$el.html(this.template(context));//notice we do this AFTER we rerender the new this.$elvarsubViews=this.subViews;this.$el.find('.subView').each(_.bind(function(index,el){var$el=$(el);// view-varsubView=_(Array.prototype.slice.call(el.classList)).chain().filter(function(className,index){return(className.match(/^view-/));},this).map(function(className){returnclassName.slice(5);},this).value()[0];//grab the first item$el.html(subViews[subView].render().$el);},this));returnthis;
There’s a new things we’ve added to this version.
There is now a ‘subView()’ helper being passed into context, this will generate
the slug that we will look for when embedding a subview.
After the $el is rendered, we are searching for dom elements with class subview
for each subView, we find the name of the subview we embed in there given as
view-[viewName] and look it up in the view’s subViews key/val lookup object.
Its a property of teh parent view.
With this, we now have an easy way of supporting subviews.
In the next installment in this series, we’ll build a base ControllerView class which we
can use to render generic collections. Yes, they’ll be embedable as subviews in our BaseView.
Lexical scoping (scoping accordinng to location in source code) is probably one of
the most powerful features a programming language can have.
Today, I’m going to show you how to use lexical scoping to
create powerful abstractions. I will begin by introducing the concept of scope.
From there I will introduce a few rules for figuring out the scope of your variables
in javascript and then introduce the concept of a closure and how it will make you
positivly badass at Javascript.
What is a scope?
I’m assuming you have written code before. Hell, I’d dare assume you’ve written a var.
1
varvariableName="variable value";
What does it mean to use the var keyword? As you may know, good javascript has you
prepend all your variables with var. Most will also advocate wrapping all your code in
an immediatly invoked function.
123456789101112
//this is being declared in the global scope.//its functionally equivilant to window.foo or just plain foovarfoo="super bar";(function(){varfoo="inner bar";console.log('this foo refers to the foo inside this function ',foo);})();/* I don't always create inline annonymous functions, but when I do, Iimmediatly invoke them. Live dynamically my friends <3 */console.log('this one will print the top level: ',foo);
Let’s start with this relativly simple example to begin growing some understanding.
Internally, the interpreter/compiler represents scopes with a tree (in simple cases, just a linked list).
At each node in the tree is a dictionary of values that we refer to with the variable
names from your source code. When we refer to foo, the interpreter (or the compiler at compile time)
will look for it in the most immediate scope. If it doesn’t find a value there, it will look
up the scope tree until it finds a node with a matching key/val and uses it for the current instruction.
Look at that previous code sample. If there wasn’t a var foo at the top of the function,
The interpreter would look for scope[foo] and find that it isn’t there. It would then look for an
entry named foo in the current scope’s parent. That is the global scope where
the variable foo exists. It refers to the value “super bar.”
Creating scopes and determining the current scope’s parent
The rules for creating scopes differ between languages. In Javascript, we start new scopes with a
function.
As you can see, we have three nodes and there are variables that are available
at each node. If you try to access a variable, the interpreter will look up the nodes
until it finds an entry that matches.
Lets go deeper. How about we not even bother with immediatly invoking the function.
How would that work?
The simple answer is that it changes nothing. The scope chain rules are consistent. The only difference
is that we now have two ways variables can enter the scope.
Through the scope tree, variables in parent scopes are available.
When variables are injected in via the function arguments which can be
pulled from some other scope where we invoke the function.
We delay the instantiation of the scopes until they are invoked later in the program.
Scope order is created lexically. Each new function definition in the source (ie: text, hence the lexical)
is being read into the interpreter as a place to mark a new node in the scope chain on invocation.
I mentioned that the scope datastructure resembles a tree because both Scope C and E
belong to B as siblings. B in turn, belongs to A.
None of these functions are being invoked but the scope lookup rules are locked to A -> B, B-> C, B->E
Things get hairier when we invoke them.
How on earth is this function maintaining state? The Binder, on invocation, takes the argument 5
and creates a scope according to the rules set forward in the source code of binder.
Now, 2 is in Scope B and being assigned to the variable “state” we instantiated in scope B.
We then return the object back.
The object we get back from calling binder() has two functions and thus two child
scopes of B, (C, and D) which we return back to Scope A. via the return.
Now it gets weird. When we call b1.get(), we invoke a function from scope A
which internally has a scope C who’s parent scope is scope B. It thus returns a value from scope B
back into scope A. Think of it like a closed loop of scopes. ie: a closure. ;)
This is pretty powerful. b1.set() does something similar only its injecting a variable from scope
A containing 2 into scope E where it is assigned to a variable in scope B and subsuquently returned.
B1.get(), on its next invocation returns the same value stored in that variable from the same scope
into scope A, the top level context.
We can use this to create objects with completely encapsulated states.
This gives us a leg up when trying to wrangle asynchrounous processes.
Here’s an example of a function that runs a function passed as an argument after a delay.
while we wait for the function to fire,
we can register functions to be called when the function is resolved.
//scope Avardelay=function(fn,args,timeout){//Scope Bvarstatus="pending";//how we track what the status of the internal state isvarresult;//where we are going to store the result of calling fn.vardeps=[];//where we store registered callbacks.setTimeout(function(){//Scope C/* the scope chain from here is A -> B-> C this simply calls teh function and allows us to pass in the arguments as an array */result=fn.apply(this,args);//call the functionstatus="done";//we run through all the functions in deps and run them one//by one.deps.forEach(function(dep){//Scope Ddep.call(this,result);});},timeout);//the two objects being returned have access to this scope//which allows us to invoke them to affect this internal //environmental.return{done:function(func){//Scope E//A -> B -> Cif(status==="pending"){deps.push(func);}if(status==="done"){func(result);}}}}varpromise=delay(function(msg){//Scope Freturnmsg+" world";},["hello"],3000);//by passing this function to done, you guarantee that//when the function passed into delay is called, it will pass//the result into the function passed in here.promise.done(function(result){//Scope Gconsole.log(result);});//3000 milliseconds later//> "hello world"
Yeah its a wee bit contrived but it illustrates a point. By using a closure to wrap a
bunch of data into this enclosed space, we can hide away some
pretty sophisticated machinery to invert the responsibilty of control. Now the
object maintains the state of the async call to the file and we register functions
that it will call when the async call is resolved. This removes alot of overhead for managing
async functions.
In Node.js, we pass a callback into the third paramater for the standard library functions.
What if we could apply the same principle and get an object we could pass along functions to
and know it will take care of running them when the file is available?
varfileObject=function(fileName,encoding){varfs=require('fs');varstatus="pending";varresult_data;varresult_error;vardeps_success=[];vardeps_fail=[];vardeps_always=[];varret={};encod=encoding||'utf8';fs.readFile(fileName,encoding,function(err,data){result_data=data;result_error=err;if(!result_error){deps_success.forEach(function(fn){fn(result_data);});status="success";}else{deps_fail.forEach(function(fn){fn(result_error);});status="error";}deps_always.forEach(function(fn){fn();});});varqueueFunction=function(list,fn){list.push(fn);};vardone=function(fn){if(status==="done"){fn(result_data);returnret;}if(status==='pending'){queueFunction(deps_success,fn);returnret;}};varfail=function(fn){if(status==="error"){fn(result_error);}if(status==="pending"){queueFunction(deps_fail,fn);}returnret;};varalways=function(fn){if(status==="pending"){queueFunction(deps_always,fn);}else{fn();}returnret;};ret.done=done;ret.fail=fail;ret.always=always;//this exposes the status as a readonly propertyObject.defineProperty(ret,'status',{get:function(){returnstatus;},enumerable:true});returnret;};
Hey, that wasn’t so bad. We return an object of three functions and
it will take care of running the appropriate functions based on the
status of the object’s internal async operation when its resolved.
I like Backbone.js a lot. It’s a fantastic utlity library for building your own
best of breed javascript applications. It is much more configurable than Angular
or Ember - both of which make numerous assumptions about the nature of your app,
which may or may not lead to frustration when working with a legacy codebase. While
you certainly won’t be cranking out apps as quickly as you would in more magical frameworks,
Backbone gives you enough to get started. It stays slim in features to avoid stepping
on your toes. Backbone is the fixed gear bike of frontend javascript frameworks.
I recommend anyone new to Backbone build a few projects to learn it. In practice,
I don’t recommend using Backbone alone for building out a full mvc system. Its missing
a few really important features that you would have to implement yourself.
Enter Thorax
In the world of Backbone extensions, there are three major players, Marionette, Thorax, and
Chaplain. I haven’t looked at Chaplain and I found Marionette heavy for my needs.
Thorax on the other hand, was a breath of fresh air. I especially loved the
handlebars.js templates integration.
In the following posts, I will outline some of the major benefits of using Thorax.
Out of the box render() that works
Child view management
Layout Views
The MVC in Backbone’s MVC
Out of the box render() that works
Backbone.View’s default render method is a noop(), (ie: function() {}).
Backbone’s author’s intend for you to write your own render function which
sets its instance’s el property to your view’s generated representation of
the model’s data. Backbone avoids adding in this feature to keep it agnostic to
your templating system.
Note: Handlebars
Handlebars is an html templating language for javascript.
and generates a string of html that you can inject into the dom.
12
<h1>hello there</h1><p>hello Douglas</p>
Since Thorax makes the decision of using Handlebars, it can give us a default render()
method that’s usable rather than a noop(). Thorax.View.render() constucts a
context object containing all of the properties of the view instance and the attributes
of the model which is passed into the Handlebars template function so that it’s available
in the rendered view.
12345678910111213141516
//render function, this is what a Thorax render does, // *this* resolves to the thorax instancevarrender=function(){//get the attributes of the propertyvarviewProperties={};for(varpropertyinthis){viewProperties[property]=this[property];};//underscore.js's extendif(this.model){viewProperties=_.extend(viewProperties,this.model.attributes);};this.$el.html(this.template(viewProperties));returnthis;}
By default, properties of the view insance get passed to the template
but not the functions. What if we want to overide this?
In the past, I would write view helpers in order to render attributes that required computation.
There’s a more elegant way using the
defineProperty function.
1234567891011121314151617181920212223242526
varpeter=newThorax.Model({firstName:'Peter',lastName:'de Croos',githubHandle:'Cultofmetatron'});varPersonView=Thorax.View.extend({template:Handlebars.compile("we can call {{firstName}}, {{lastName}} and {{fullName}}"),initialize:function(){Object.defineProperty(this,'fullName',{get:function(){returnthis.model.get('firstName')+' '+this.model.get('lastName');},enumerable:true// see note below});}});varpeterView=newPersonView({model:peter});
Technical note: By default, properties defined by defineProperty are not enumerable.
IE: They won’t show up when you do the for (property in this) {}. Because
thats how thorax’s render view gets at the attributes, it won’t show up in the template
either. Luckily that is easy enough to fix by specifying the option
enumerable:true
Child view management
Backbone does nothing to address embedded views. It expects you to write your own logic
for handling child views in the render function. As you can imagine, it is kind of a pain.
It sounds simple enough in theory, but in practice it means that you have to write code to check
if a parent view is being removed and recursivly have it descend into all it child views to
undelegate events from the dom. This is a major potential source of javascript memory leaks.
Thorax provides some great helper functions for this. It just wins.
Thorax.Views can be embedded in another view simply by adding the subview as a property.
1234567891011121314151617181920
varblogModel=Thorax.Model({name:'console.log(this.thought)',post:newThorax.Model({title:"Thorax is awesome",content:"maximum callstack exeeded"})});varPostView=Thorax.View.extend({template:Handlebars.compile('<h2>{{title}}</h2><p>{{content}}</p>')});varblogView=newBlogView({template:Handlebars.compile("<h1>{{name}}</h1>{{view postView}}"),model:blogModel,postView:newPostView({model:this.model.get('post')})});
As you can see, it was as easy as embedding {{view postView }}
inside the template and Thorax takes of care of yielding control of that region to the
child view.
Layout Views
Let me just say that layout views are really awesome. A layout view is
a view with the sole purpose being a container which can hold whatever
view/model combo fits the current context.
The MVC in Backbone’s MVC
There’s a Backbone.Model and a Backbone.View but where is Backbone.Controller? (hint: there isn’t one)
Currently Marrionette augments Backbone with a Controller object but
Thorax does nothing of the sort. I guess the real question is, where does a controller fit?
Philosphically, MVC stands for a seperation of concerns between
Models: the data containing the application logic we are modelling on the computer
Views: Objects that manage the presentation of the models. This includes binding
event handlers and rerendering when the underlying model(s) change.
Controllers: Objects that take care of managing what view and model are relevant.
In the Rails world, the architectural philosphy revolves around the concept
of skinny controller/fat Model. The brunt of the code for manipulating the models should
be inside the instance methods in the models themeselves and the controller interacts with it
through an api.
When we really get down to it, controllers perform a few functions.
Watch out for some event that should trigger a change in view and/or model.
Manage the creation of new view instances to represent new or altered models.
Render html and insert it into the DOM.
Our controller will handle only the details of getting the proper model and binding
it to a view so that it can be rendered.
Lets create a function PostController that does nothing more than lookup a
model by its id and creates a post view.
12345678
varpostController=function(postId){//for info on Thorax.Views, Thorax.Models and Thorax.Collections,//see the note belowvarpostView=newThorax.Views.FullPagePostView({model:Thorax.Collections.posts.get(postId)});returnpostView;}
Note About Thorax Registries
Thorax provides a Registry: a series of hashes
where you can store the Constructor Functions for your
extended models and views.
Now we have a basic controller that handles cases 2 and 3 of our list. We still need to take care
of figuring out how we want to determine when this controller gets called. In the projects
I have worked on, I’ve solved this problem using the router.
Thorax does nothing special with the router so we will use Backbone.Router as is. It will manage one
Layout view, a special Thorax view made for holding other views.
12345678910
//router.jsvarlayoutContainer;varcallController=function(controller){returnfunction(){//arguments is used to shift responsibilty of knowing the //amount of paramaters to the controllervarview=controller.apply(this,arguments);layoutContainer.setView(view);};};
The function callController takes a controller, passes along
the arguments given to it by the router and takes care of the
boiler plate of creating a view and setting it into the container.
layoutContainer.setView() takes care of undelegating events of
all elements attached to the previous view (if there was a previous view)
as it swaps in the html of the new view.
1234567891011121314151617181920
//continued from abovevarRouter=Backbone.Router.extend({initialize:function(){layoutContainer=newThorax.LayoutView({template:'#AppLayout'});/* this is the point in the html where our container will be injected in. from here on out, the router and controller system will take care of swappng out application views within this container. */layoutContainer.appendTo('#entry-point');$(document).trigger('popstate');},routes:{'posts/:postId':'postRoute'},postRoute:callController(postController)});
This is a pretty straight forward setup with one possible new thing. So you
probably noticed the $(document).trigger(‘popstate’). In standard backbone,
the application instance Router has a method navigate() usually called by
1
router.navigate('path/to/route',{trigger:true});
The trigger true is needed by backbone for the router to trigger any associated actions.
The browser by default writes to history when the document recieves the
popstate event.
The browser triggers popstate automatically when you enter a page or hit the backwards or forward buttons.
When you click back, the new url will load and the router which is listening
for the popstate event on ‘document’ will perform the behavior associated with that url.
By having the $(document).trigger(‘popstate’) at the end of the initialization, we guarantee
that once the router is finished initializing, it will read in the url and trigger the appropriate
context for the app for the url. This is great if we want multiple url entry points through
which the user enters the app. The user gets the same javascript no matter what url of the
website they visit. The app takes care of loading the right content based on the url.
Finally, the template option that was passed into the instantiation of layoutView is optional.
By default, Thorax wraps the layout in a div tag. We can customize the layoutView by giving it a template
and using the layout-element helper in that template.
Its been a few months since I’ve started using backbone on my personal projects.
Its a great library for rolling out MVC structure into your application but the
learning curve is pretty brutal.
The first step to really understanding the backbone.js framework.
 Its far
too minimal. Backbone is more like a toolkit library for contructing MVC frameworks.
The real key is how we use it. Like Chess, it can be
learned very quickly. the problem is that you also need to understand the tactics and strategies.
The offical docs leave a lot to the imagination and the examples are lackluster at best if they
exist at all.
Backbone.Model
Backbone.Model is a storage container where we can add and remove
items via set and get attributes.
You may be wondering why you don’t use newModel.foo = ‘bar’?
The real power in backbone is in the
events that models can fire. By having you access the model’s attributes via
set and get, you ensure that the associated callbacks get fired everytime
an attribute is changed.
For example, in a View containing a Model,
when we change an attribute on the model via the setter and getter methods.
A callback automatically makes the model emit a ‘change’ event which we can set
the view to listen to and trigger a rerender.
Extending Backbone.Model
Backbone.Model is inherited using extend. This is also where we add methods
that may be specific to our particular subclass of Backbone.Model. For instance,
lets create a Comments model which may contain a username, content, rating
and timestamp.
12345678910111213141516171819202122232425262728
varComment=Backbone.Model.extend({//defaults are self explanatorydefaults:{rating:0,},/* * initialize runs whenever new is called, it takes care of * setting up __super in the inheritance chain * there is also 'constructor' which overides the contructor entirely * leaving you to manually impliment the prototype chaining. * ie: only use constructor if you know what you are doing. */initialize:function(){this.set('owner',getCurrentUser());this.set('timestamp',newDate());},upvote:function(){this.set('rating',this.get('rating')++);returnthis;}});/* now we initialize the model passing in values in an object. */varnewComment=newComment({content:"backbone needs a library for reactive databindings",});newComment.upvote().get('rating');// => 1
Here we’ve set up a basic backbone model for setting representing a comment.
In defaults, we put in an object of default attributes. You may be wondering why I
set up the owner and timestamp attributes in initialize.
The defaults object and anything inside it is evaluated into a static object
inside the extend function call. Thus, if you were to try this
123456789
varComment=Backbone.Model.extend({//defaults are self explanatorydefaults:{rating:0,owner:getCurrentUser();timestamp:(function(){returnnewDate()})();}...})
you would find that every instance will have the same timestamp. To get around this,
I have the functionality for those defaults set to run in initialize.
Backbone.Model events
Backbone models should only broadcast events in order to notify things that
contain it. A model itself can contain another model as an attribute.
Backbone.Model’s ‘change’ event fires when it detects a change in the value of the attribute.
If the value is a model, then a change in that model’s attributes won’t change the reference
to the model. Unlike the dom, we have to explicitly set up our own event bubbling.
To set up your own event delegation, you have to set up a listener in the parent model to listen for
events in the attribute model.
123456789101112131415
varCommentHolder=Backbone.Model.extend({initialize:function(){/* We set up event listeners here the first argument is message being fired the second is the function to be invoked the third is the context for function to be called in */this.get('comment').on('all',this.bubble,this);},bubble:function(){// apply is used to propegate all possible arguments// that can be coming form multiple events.this.trigger.apply(this,arguments);//trigger is a backbone function}})
‘all’ is a backbone defined catch all event
that sends along the name of the event as the first argument. The model will listen
to its comment and broadcast any messages it recieves to any who would hear.
Internally within node, every object has an id that V8 uses to keep track of these
object. In the same way, when we invoke a request to the operating system to create
a process, the operating system loads the program into memory and assigns it an id
which can be used to track the running program throughout its life cycle.
The id this process is assigned is called a pid and it can be accessed from within
node via process
12
varpid=process.pid;console.log(pid);
Fun fact: if you open another terminal and type “kill -9 (process pid).” You will
have effectivly terminated the process in the other window by having the operating
system directly deliver a kill switch to your running node instance.
The process module is global so we don’t need to require it. It gives us alot of
information about the running node instance that we can use in our programs.
Example operations include
exiting the program
changing directories/ getting directory information
getting the name of the directory of the start script
retrieving argumenst passed into the command line invocation of the script
process events
specific to node.js is the ability to bind to occur at process events.
12345678910
varrunOnExit=function(){console.log('...exiting');};process.on('exit',function(){/* its important that you do not invoke * any asynchronous functions in here */runOnExit();});
In the case of exit, the event loop terminates. The documentation specifically
mentions events scheduled with setTimeout. Its important to note that this applies
to all asych events as they all operate on setTimeout underneath.
Consequently, if you need to write some pertinent information to the disc, Be sure
to use writeFileSync!!
process.kill
TLDR: Processes can send signals to each other and recieve signals from the ernal
Signals can be compared to events
and event listeners in javascript. kill()’s name is unfortunate since kill
is really a function for sending messages to other processes as OS signals. You will
use this function to tell other processes to go kill themeselves most of the time.
This isn’t limited to node processes speaking amongst themeselves. Ever run node and then
exit it using ctrl-c.
For a great list of standard unix signals, check out this
Awesome Chart
We can orginaize them according to their default behaviors.
kill requests/reports
error reporting
device access notification
coordinating io
We can overide the default behaviors for some of these signals.
1234567891011121314151617
console.log("to delete => kill -9 "+process.pid);console.log("\n\n this is a a reinforced program, it will not easily die");/* SIGINT is sent to your process when you type in CTR-C. the operating system intercepts this command and relays it to your node instance. node's default response is to exit. */process.on('SIGINT',function(){console.log('you tried to press CTRL-C, go ahead, try again');});process.on('SIGTSTP',function(){console.log('LOL, nope - CTRL-Z won\'t save you!! either');});//this keeps the program from exitingvarmainLoop=function(){setTimeout(mainLoop,0);};mainLoop();
A more realistic scenario would be a situation in which you need to
write some files to the disk before kicking off the exit procedures.
12345
process.on('SIGINT',function(){console.log('writing to disk');saveData();returnprocess.exit(0);});
You cannot overwrite the kill -9 signal. This is why certain programs can become corrupted
when you kill-9 them. they are not given a chance to save state.
For more information about signals, I found these two guides to be excellent.
 If you are looking to build some
form of complex communication pipeline between individual processes,
you are better off doing so over tcp. There are frameworks that facilitate
this such as zeromq with an
excellent node binding available.
As a language made to exist within the browser, javascript did not originally
come with a way to do process process related tasks. Until Chrome, browser based
javascript was running within the same process as the browser.
In Chrome, every tab runs in its own process. Consequently, your javascript on any given
page runs in its own process. Now that node has brought javascript into the server and far from
the restrictive confines of the browser, We can do intersting things like run other programs from node.
What is a process?
Much like the relationship between a Constructor function + its prototypye and the
object created by invoking the new keyword, a process is an operating system level invocation
of some program.
Process vs Program - a very high level overview
Imagine the hardrive that powers your computer. Stored on it is a long range of numbers.
For all practical purposes, we can think of it as a long serial stream of bits layed out. with information
encoded on them. At some magical location is the boot sector. When the computer first starts running,
it startsloading binary data from the hardrive into the RAM and then loads this data into the cpu.
At this point we load the master process which we call the operating system kernal.
The kernal then takes care of managing other processes in the system.
At this point, we get to your program. If we were doing this in C, the the compiler would compile your
source code into binary code which follows an executable format. The actual encoding of this binary instruction
stream varies across cpu architectures and operating systems. They do happen to share some
common characteristics. Most of this information is located in the header of the file as information that tells
the operating system that this code is executable and information on how it is to be run.
Entry Point Address
At some point in the binary stream of bytes that is your program, there exists the first instruction that
needs to be loaded into the cpu. The Operating System loads this address into memory and queues it up
for running into the cpu.
Data
Constants in the process are stored in the data stream in some area where they can be accessed by the
Process as it runs. This includes mathematical constants such as Math.PI or string error messages.
Symbol and Lookup Tables.
To properly explain symbol and lookup table, I need to elaborate on what is going on at the
instruction level on your computer. Basicly, it stores the locations of all the variables and function
entry points. in memory.
Processes verses threads
The simple $2 answer is that processes have their own copy of all the data and symbol information. In some languages, multiple threads exist within a process and all share the same data. more importantly, you cannot create threads in node.
Processes and node
For us nodesters, the picture gets a bit more complicated. The computer loads up the program instructions
we affectionatly know as node and loads it into memory. From there, the node program as a static set of
bits on the hardrive becomes an almost living thing that loads your javascript into memory and run it!
To clarify, the process running when you run your node program is an instance of the node program. You can
have several node instances running in memory. They can even all serve http requests as long as they are
not trying to bind to the same port.
Understanding processes is incredibly useful. In Ruby, processes forking is used heavily in the design of
unicorn. Services like nodejitsu and heroku utilize smart people who understand
how processes work to architect systems that run and manage your code on the cloud. More importantly, node code
can only run on one processor at any given time but by using features such as fork, you can set up a master
node process that delegates tasks to subprocesses it spawns yourself. Since node processes are so
lightweight, you could concievably run hundreds on your system at the same time.
Of all the stranger than fiction things I have seen, I can’t say I have experienced as blatant
a miscarriage of conceptual understanding as I have with javascript’s object system. (Ok, I might
be exagerating just a little…)
Javascript is an interesting language. It is quite powerful when paired with appropriate libraries
like underscore. Its prototypical inheritence model is a mindblowlingly powerful reductionist critique
of classical inheritance. In the right hands, functions become lego pieces that can be glued onto objects
in staggeringly flexible ways.
On “this”
Lets take an object
1
varmyObject={};
This is a basic object. It is also a hash.
123456789101112
//We can access it via dot notation or hash notationmyObject['jackson']=5;5+myObject['jackson'];// => 10;5+myObject.jackson;// => 10;//we can store strings, numbers, other objects and very importantly,// other functions!myObject.title=function(){return"this is the Jackson "+this.jackson;}myObject.title()// => "this is the Jackson 5";
If you are currently a javascript programmer, you’ve probably seen code like this. In
langages like Java, or c, Functions are simply routines that operate on code. they are static.
Once they exist, they exist in only one context. The Java version of ‘this’ refers to the instance
of the instantiated object.
Functions in javascript are “First Class.”
This is a really important distinction to make because it enables all of the most
powerful code reuse techniques. A function can exist beyond an object. It can be made an
instance function a several different objects. In practice, it means we can assign functions to
variables and pass it into functions as arguments. We can even return functions from other functions.
Put more succinctly…
We can create a function which performs operations related to an abstract “this” attribute without knowing what “this” is going to be till we hook up a context to it when its called.
It is important to discuss the notion of call time. Languages where functions are not first class
do not have a call time.
Lets take a cannonical example in Java.
12345678910111213141516
publicclassExampleClass{publicintfoo;publicstaticvoidmain(String[]args){System.out.println("Clojure is way more fun");}publicExampleClass(intfoo){// initialize code goes herethis.foo=foo;}publicgetFoo(){returnthis.foo;}}
Java functions are not first class. The ‘this’ refers only to the instantiated instance of
this class. If I instantiate this class and call the function, I will get the
class variable “foo” of the instance.
12345
ExampleClassexampleClass=newExampleClass(5);// Java is ridiculous!!!exampleClass.getFoo();// => 5// this results in an error because there is no public variable getFooexampleClass.getFoo;
Because Java’s functions are not first class, there is no notion of this function being
referred to unless its being specifically called. Javascript’s functions are dfferent. I can declare
a javascript function and bind it to several objects.
This code in javascript works because javascript functions are variables that can be assigned and passed
around like a company pen. (thats about as work safe a metaphor as I could come up with. sorry…) The only
large difference between functions and other javascript types is that functions can be called.
Call time is the point where the javascript function is executed. If it contains a ‘this’ inside it. That keyword then
resolves to whatever object that function is being called upon. If there is no object, ‘this’ resolves
to the global object. In Browsers, the global object is window.
new is a feature of javascript that changes the context of ‘this’ in
a constructor function. when new is called on a constructor function being called, new
becomes an object that is being modified and eventually returned. It will delegate function calls it
cannot respond to to whatever the function’s prototype attribute is. IE: functions in javasript are
objects.
123456789101112131415161718
vardundar={gummy:'bear'}varContructorFunction=function(){// at this point this == {};this.foo="bar"// "return this" is implicit}ContructorFunction.prototype=dundar;newObject=newContructorFunction();newObject.gummy;// => 'bear'newObject.foo;// => 'bar'
The __proto__ Attribute
Javascript’s prototype delegation is setup such that if an attribute is accessed on an object and the
object does not have that attribute. It will defer that request to the object set as its __proto__.
The __proto__ is determined by the constructor function’s prototype attribute.
Actually it DOES, But only in V8 - ie: chrome and node.js
(as an interesting aside, this technique is used alot in the express source code. Don’t try this at home,
unless you do server side node at home of course!)
Sorry to burst your bubble but I must advise you that you do not do this on the browser as it will not work
becase __proto__ is a protected attribute. Thats right, the song and dance above it using new is
the only surefire way to assign the __proto__ attribute.
call() and apply()
To recap
Unless you call the function with new, ‘this’ becomes resolved within the function to whatever is on
the left side of the ‘.’.
12
// if 'this' is in the definition of getFoo, it will resolve to myObject.myObject.getFoo()
call() and apply() can be called on any function and allow you to explicitly set what ‘this’ will
resolve to. the only difference is that call takes the arguments of the function right after the new
meaning of ‘this’ and apply takes the arguments as an array.
myObject1={foo:'bar',num:1}myObject2={foo:'manshu',getFoo:function(){returnthis.foo;}inc:function(num){this.num+=num;returnthis.num;}}//errors out because it doesn't have a getFoo() methodmyObject1.getFoo();myObject2.getFoo()// => 'manshu'//heres where is gets interestingmyObject2.getsFoo.call(myObject1)// => 'bar'//this one errors because myObject2 does not have a num attributemyObject2.inc()// baddmyObject2.inc.call(myObject1,1);//sets myObject1.num to 2//apply does the same with the arguments in an arraymyObject2.inc.apply(myObject1,[1]);// myObject1.num is now 3!!
Now we’re ready for how to create inheritence chains in javascript!
(that article is comming soon.)


Example of hashes: grades = { "Jane Doe" => 10, "Jim Doe" => 6 } options = { :font_size => 10, :font_family => "Arial" } options = { font_size: 10, font_family: "Arial" } Creating new hashes: grades = {} grades.default = 0 grades = Hash.new grades = Hash.new(0) Adding or modifying key/value: grades["Dorothy Doe"] = 9 books[:matz] = "The Ruby Language" Accessing hashes: grades["Dorothy Doe"] books[:matz] h = { "a" => 100, "b" => 200 } h["a"] # 100 h["c"] # nil
A hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to arrays, but where an array uses integers as its index, a hash allows you to use any object type.
Some things to know about hashes:
Learn more about Ruby hashes and hash methods here.
Examples of arrays: ary = [1, "two", 3.0] #=> [1, "two", 3.0] a = [ 1, 2, [true, [4, "hello"] ] ] Creating new arrays: ary = [] ary = Array.new #=> [] Array.new(3, true) #=> [true, true, true] Adding or modifying elements: ary[0] = 4 ary[1] = "hello world" Accessing arrays: arr = [1, 2, 3, 4, 5, 6] arr[2] #=> 3 arr[100] #=> nil
Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array---that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.
Some things to know about arrays:
Learn more about Ruby arrays and array methods here.
Examples of strings: my_string = "hello world" my_string = String.new("hello world") "1 2 3 4 5 6, yes this is a super long string!" Creating new strings: 'creating a new string within single-quotes' "or create a new string within double-quotes" a = "or assign a string to a variable" Adding or modifying strings: a = "hello " a << "world" #=> "hello world" a.concat("world") #=> "hello world" Accessing strings: a = "hello there" a[1] #=> "e" a[2, 3] #=> "llo" a[2..3] #=> "ll"
A string is a group of characters that typically make up human readable words or sentences.
Some things to know about strings:
Learn more about Ruby strings and string methods here.
Examples of integers: 2016 123456 Creating new integers: 2016 a = 2016 Adding or modifying integers: 2016 * 20 + 1 a = 123456 * 2 - 10 a + 100000
An integer means a whole number (no decimals).
Some things to know about integers:
Learn more about Ruby integers and integer methods here.


Interest Payments Calculator
Enter investment data
Date of agreement:
Date of calculation:
Invested amount:
USD
Interest rate:
% per year
Investment duration:
years
Calculate!


Fit and simulate mixtures of von Mises-Fisher distributions.
| Version: |
0.2-4 |
| Depends: |
R (≥ 3.0.0) |
| Imports: |
skmeans (≥ 0.2-10), clue, slam (≥ 0.1-43), stats |
| Suggests: |
lattice, tm (≥ 0.7-5), vcd, SnowballC, HSAUR2, colorspace, corpus.useR.2008.abstracts |
| Published: |
2018-09-26 |
| Author: |
Kurt Hornik [aut, cre],
Bettina Grün [aut] |
| Maintainer: |
Kurt Hornik <Kurt.Hornik at R-project.org> |
| License: |
GPL-2 |
| NeedsCompilation: |
yes |
| Citation: |
movMF citation info |
| Materials: |
NEWS |
| In views: |
Cluster, Distributions, NaturalLanguageProcessing |
| CRAN checks: |
movMF results |


|
That's wrong......funny, but wrong. From<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Subject: Fw: I'll just use the hand dryer thanks Date: Mon, 22 Jun 2009 09:57:41 -0500 Hotmail® has ever-growing storage! Don’t worry about storage limits. Check it out. |


Nam Nhat Nguyen
1 2 3 4 5 6 7 8 9 10Kevin
HTML stands for Hyper Text Markup Language It is the core language of the world wide web and is used to define the structure and layout of web documents by using various tags and attributes Although a fundamental language of the web, HTML is a static language - content created with it does not change HTML is used to specify the way webpages look, not how they function.
One particular book which is recommended reading is The Street Lawyer by John Grisham. This book is about a lawyer who begins re-evaluating his priorities in life when a bad incident occurs within his law firm. Consequently, he becomes acquainted with the inner city streets, and realizes the harsh existence of the homeless, and vows to give them a chance in the courts. The Street Lawyer is a great book. It is well written and interesting. Other books by John Grisham include The Firm, The Pelican Brief, and The Client.
12 = 1 22 = 4 32 = 9 42 = 16 52 = 25 62 = 36 72 = 49 82 = 64 92 = 81 102 = 100 112 = 121 122 = 144 132 = 169 142 = 196 152 = 225 162 = 256 172 = 289 182 = 324 192 = 361 202 = 400


NMM organized annual summer picnic at Chalco Hills, Omaha, NE. A fun evening with friends and family with lots of games and activities for everyone with awesome food. Watch the pictures here.
View PicturesGdui Padwa of 2019 was celebrated with lots of fun, great performances and delicious food by NMM. Check out some awesome moments!
View PicturesDiwali 2018 was celebrated with lots of fun, food and music by NMM. Check out some awesome moments!
View PicturesNMM celebrated Ganesh Utsav 2018 with even greater enthusiasm having all the volunteers participating in Mahaprasad preparations with a special big Ladu for auction. "Dhol-Tasha and Lezim" was in its full swing during the RathaYatra with increasing participation of devotees making the complete event a great success!
View PicturesNMM Organized a workshop on Scratch Prgoramming for kids with help of facilitator Ishma Sultania. Kids got a chance to learn basics of programming and showed lot of interest in learning more about it!
View PicturesNMM organized annual summer picnic at Zorinsky Lake Park. A fun evening with friends and family with lots of games and activities for everyone with awesome food. Watch the pictures here.
View PicturesThis year NMM came with a different concept of celebrating Diwali. Members from different communities came forward for their active participation in various cultural activities. The main attraction were kids performers and anchors who did a fabulous job throughout the function. This event was filled with fun and sumptous dinner after the function. Overall it was a great event. You all can download the informative power point presentation, highligthing the importance of diwali and also photos of this event.
Download Powerpoint View PicturesThis year NMM organized Diwali Diya painting workshop for kids and adults. It involved Diya painting for adults taught by Mrs. Gauri Abhijit Pimprikar. Also, kids activity involved making paper lanterns. You can view the pictures of the workshop in the link below.
View PicturesAs every year, this year also NMM continued with its tradition of organizing and making this Ganeshotsav a huge success alongwith serving Mahaprasad with the help of its volunteers.The main attraction this year was Ratha yatra accompanied by "Dhol-Tasha and Lezim". You all can view the pictures of this great event here
View Pictures Day 1 View Pictures Day 2NMM organized annual summer picnic at Chalco Hills recreation park. There were various activities for kids as well as adults with sumptuous traditional food cooked by the volunteers. Watch the pictures here
View PicturesNMM conducted Coffee Painting Workshop with help of Mrs. Gauri Pimprikar. Adults and kids had a wonderful weekend morning and they enjoyed this unique art. Watch the pictures here
View PicturesNMM celebrated Gudi Padwa on March 28th at The Hindu temple with various cultural activites. To get glimpse of those moments see more pictures.
View Pictures


Groupon attended the National Restraunt Association Tradeshow in Chicago. Groupon used this opportunity to introduce the new restaurant POS features and pricing.
Working Bikes is a nonprofit in Chicago that collects and repairs unwanted bikes. Some bikes are sold to support the organization and others are sent to people around the world in need of transportation. This brochure educates the public about Working Bikes' mission.


h
> Writing Good QuestionsJuly 31, 2014
Asking good questions is key to getting the support you need. In this post I'll talk about some strategies for asking good questions and how to apply this advice.
> How to Ask Good Questions
Basic template for a good question or bug report
- Informative title that indicates the problem and may also include the programming language
- Context: You will need to include the programming language, probably the operating system and any other constraints.
- What you did (steps to reproduce): This is where you explain what the code looks like and where your problem is occuring. You should also explain what you have already done to try to answer your own question. You may need to explain you're bigger-picture goal so that people can understand why you're trying to do what you're doing (they may advise you to take another course to meet your end goal). This is where you will want to include sample code.
- What did you expected to happen: Explain your intended output and what you expected to result from the code.
- What happened instead: This may include error messages.
Tips
- Imagine you're trying to answer the question. If you review your question from this standpoint, you may come across additional items that need clarification. You may also see ways that the question may be confusing to other people. Are there extraneous details that may lead the responder to focus on something other than what's central to the problem?
- Be specific and be concise: This can be a hard balance to strike as you want to provide as much information as possible to get your desired answer without people asking you questions about things you've already tried. BUT, you also want the questions to be short enough that you don't lose you're audience. You will probably need to write out or think out what you're asking and then proofread/re-formulate your question so that you are providing the necessary information and so that you aren't confusing yourself or the person or people who may respond to your question.
- Proofread: We all make typos and spelling mistakes. Clean these up to prevent distractions and so that you're responder doesn't have to do additional work to decipher your grammar.
> Examples: How well do they follow the template?
Below we'll look at two questions from Stack Overflow and evaluate them on how well they meet the four criteria outlined in the template above. While neither example is perfect, the first provides very little explanation while the second is much more explicit as to what is being attempted, what has been tried, and where (s)he is struggling. The second example also indicates that not all criteria in the template are essential for the question to be effective and for there to be sufficient explanation.
Example 1
Title: How to use push with sub-arrays?
- Informative title: While the title is specific and concise to the problem, it does not specifically mention JavaScript.
- Context: There is no context given, but this may be unnessary given that the question deals strictly with code. However, it would be useful to mention at least somewhere (other than just in the tag) that this problem is with JavaScript.
- What is your goal? The goal is not explained. Some explains of what the author is trying to accomplish are provided, but does not make explicit their desired output.
What have you already tried? The author does not say what (s)he has tried. (S)he asks if something is possible, but does not say that (s)he has tried to run the code and found that it does not pass.
Sample code: The sample code shows what the author has done with minimal comments for context. - What did you expect? Since there is no explanation as to what has been tried or to what the goal is, we have to infer expectation from the sample code.
- What happened instead?
Example 2
Title: How to get the index of an object inside an array of objects?
- Informative title: Similar to Example 1, the title is specific and concise to the problem but it does not specifically mention JavaScript.
- Context: The first line of the question makes it explicit that s(he) is working in JavaScript. No other context is given, but as stated for Example 1, it may be unneccessary.
- What is your goal? The goal is stated in the question at the bottom - s(he) wants to know the index of the object without having to define the id property.
What have you already tried? The author explains how s(he) is currently approaching the problem and how they are doing it. S(he) also explains where the problem is occuring when using #sort.
Sample code: There is some sample code to accompany the explanation. - What did you expect? S(he) does not propose an alternative solution, so it is not clear how they expect it might be accomplished.
- What happened instead? Again, there isn't an explanation for what an alternative solution might look like, but it is clear what s(he) is ultimately trying to accomplish.
> Resources
- Stackoverflow: How do I ask good questions? (also see the links at the bottom of this article for additional resources)
- Joel on Software: Painless Debugging


§328-63 Injunction. Any violations of this part may be enjoined or abated in a suit filed and prosecuted in the circuit court of the State by the department of health. [L 1967, c 206, pt of §1; HRS §328-63]


./getpeers
[{"isLP":"<IP_ADDRESS>","remoteport":7782,"netid":0,"session":0}, {"isLP":"<IP_ADDRESS>","remoteport":7782,"netid":0,"session":0}, {"isLP":"<IP_ADDRESS>","remoteport":7782,"netid":0,"session":1536849429}, {"isLP":"<IP_ADDRESS>","remoteport":7782,"netid":0,"session":1538610071}, {"isLP":"<IP_ADDRESS>","remoteport":7782,"netid":0,"session":1539014186}, {"isLP":"<IP_ADDRESS>","remoteport":7782,"netid":0,"session":1539014186}]
the 2 new FRs are showing up on getpeers from the bobs


Monday afternoon You're back at your desk after being bombarded with questions on IFRS 1 by the Board that morning. Out of nowhere, your boss, the CFO, Garrett appears at your office doorway, looking like a man on a mission.
Are you clear about identifying the voluntary exemptions that could affect the adoption of IFRS?
We need to consider the voluntary exemptions from compliance with each IFRS in our first-time adoption. All our subsidiaries must analyse these exemptions for us to decide which exemptions to apply and how we will apply them.
Well explain all the voluntary exemptions to our subsidiaries and then ask how these will affect their business. Please compose an email to this effect. I want to see the findings by mid-week at the latest...


About Me
My name is Maria Francis-Moullier, and I am enrolled in the University of Arizona Coding Boot Camp in order to learn web development in order to start a career in that field. I have always liked working with computers. In my undergraduate career, I studied Computer Science and Political Science. In my Computer Science classes, I learned some C and Java programming. Now I'm excited to gain new skills and work with more modern platforms.
Most recently, I worked at Intuit for 8 years, in the TurboTax and QuickBooks Online departments. I did a lot of data analysis work, using Excel, Access and SQL to develop new metrics and report out to management on customer pain. My team was able to synthesize data from a number of different sources to create insights that had not previously been available. I also worked on the QuickBooks Online Defect team, taking reports of bugs in the code that came in to front line support and processing them for the developers to fix. My duties included training customer support agents at various locations around the country.


We're an Student Organization that facilitates student involvement in off-campus hackathons and organize related on-campus events.
Sponsor 1
Sponsor 2
Sponsor 3
Sponsor 4
Sponsor 5
Sponsor 6
Built By: Josh Beers, Anne Joseph, Danielle Battle
Background By: Mark Stiller
Copyright © Team E.V.I.L 2020


{{ template "layout/base.html" . }} {{define "head"}}
| Common Name | Real Address | Virtual Address | KB Received | KB Sent | Connected Since | Username | |
|---|---|---|---|---|---|---|---|
| {{.CommonName}} | {{.RealAddress}} | {{.VirtualAddress}} | {{printkb .BytesReceived}} | {{printkb .BytesSent}} | {{.ConnectedSince}} | {{if eq .Username "UNDEF"}} - {{else}} {{.Username}} {{end}} | X |


This Javascript solution allows tables to shrink on small devices without sacrificing the value of tables — comparison of columns. Adapted from the ZURB plugin of the same name.
| Header 1 | Header 2 | Header 3 | Header 4 | Header 5 | Header 6 | Header 7 | Header 8 |
|---|---|---|---|---|---|---|---|
| row 1, cell 1 | row 1, cell 2 | row 1, cell 3 | row 1, cell 4 | row 1, cell 5 | row 1, cell 6 | row 1, cell 7 | row 1, cell 8 |
| row 2, cell 1 | row 2, cell 2 | row 2, cell 3 | row 2, cell 4 | row 2, cell 5 | row 2, cell 6 | row 2, cell 7 | row 2, cell 8 |
| row 3, cell 1 | row 3, cell 2 | row 3, cell 3 | row 3, cell 4 | row 3, cell 5 | row 3, cell 6 | row 3, cell 7 | row 3, cell 8 |
| row 4, cell 1 | row 4, cell 2 | row 4, cell 3 | row 4, cell 4 | row 4, cell 5 | row 4, cell 6 | row 4, cell 7 | row 4, cell 8 |
Add data-spy="rtable"
to the .table-responsive
wrapper to trigger the plugin.
Call the responsive table via Javascript:
{% highlight js %} $('.table-responsive').rtable() {% endhighlight %}Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-
, as in data-backdrop=""
.
| Name | type | default | description |
|---|---|---|---|
| breakpoint | string | 768 | Sets the window width at which the responsive styling kicks in. |


--- layout: post-index title: description: "A PL Ph.D. Student." tags: [Jekyll, theme, themes, responsive, blog, modern] comments: false --- {% for post in paginator.posts %} {% if post.quote %} {% else %}


We optimize solutions!
- embrace clicks-and-mortar schemas
- engage proactive relationships
- e-enable leading-edge networks
- engineer distributed action-items
- architect innovative web services
- generate clicks-and-mortar channels
- iterate revolutionary systems
- enhance viral technologies
- enhance transparent web services
- innovate 24/7 methodologies
- grow synergistic portals


Vincent
Full-Stack Developer
Low hanging fruits grabbing developer with over 12 years of experience in nursing.
Yingqi
Full-Stack Developer
Aspiring Front-end Developer with over 4 years of finance experience, loves watching NBA games and enjoy sharing idea.
Jonathan
Full-Stack Developer
Striving software developer with 8 years of sales experience in luxury apparels, high jewellery and automobile.


Evolution 🌱
Grow the Habitat by signaling your top priorities and interests.
-
Topics
-
Members
-
HBT Votes
Features & Upgrades✨
Improvements & Bugs 🐛
Extend the Habitat and it’s ecosystem by upvoting most desired milestones and upgrades. You can easily check the progress of each issue and feature. Feel free to reach out or comment on the issue, if you want to support and earn HBT.
Welcome to the Feature Farm 0.5 🌾
For now you can only vote on pre-determined milestones to reach Habitat v1.0. Have a look at our Roadmap for more info.
v1 Milestones 🔥
We believe in the wisdom of the crowd. Prioritize existing proposals and improvements by simply upvoting your favorites. You can also suggest new topics to improve Habitat with features, design solutions or simply by reporting bugs.


SEER is a pilot application of study undertaken by Udgam Mehetre as part of MSc Computing Practicum at Dublin City University.
Supervised by Dr. Alexander O'Connor and Dr. Fred Hollowood, the study aims to understand the importance of explanations in recommendation systems.
To proceed, please login to your Gmail account by clicking below.
Note: Please read the instructions before continuing, if you are here for the first time.


Car
Body
Door1
Glass
Metal
Door2
Glass
Metal
Door3
Glass
Metal
Door4
Glass
Metal
Chassis
Wheel1
Wheel2
Wheel3
Wheel4


DevStats
This is a toolset to visualize GitHub archives using HA Postgres databases and Grafana dashboards.
Everything is open source so that it can be used by other CNCF and non-CNCF open source projects.
The only requirement is that project must be hosted on a public GitHub repository/repositories.
Project is deployed using Equinix bare metal Kubernetes nodes and deployed using a Helm chart.
It uses many more CNCF projects under the hood.
Author: Łukasz Gryglicki
Projects:
DevStats API, documented here.
| Hardware for this site is graciously donated by |
|


DOC
RedGL Example
JavaScript 3D library
example
/
testCase
/
document
/
github
This project is maintained by
Redcamel


Lessons Learned from Powerlifting
I’ve been lifting for 1.5 years now, and it’s become one of the best investments in my life. In this blog post, I’ll share the 9 most important lessons that I learned.
I previously wrote a blog post about my gym journey. What I’ve come to realize was that my biggest transformation wasn’t physical, but rather mental.
1. Mental confidence.
If I don’t believe I can lift a weight, then I probably can’t lift it. Before I attempt my heavy lifts, I always try to visualize myself doing the set and replaying that picture in my head. I’ve been able to transfer this skill into many other aspects of my life, where I try to mentally visualize success.
When I first started lifting, I had a bunch of thoughts in my head that might sound familiar to all gym goers. “I don’t know how to lift. I’m scared. I’m so weak. People are going to judge me.” Now that I’ve conquered this fear with lifting, I’ve become less scared to try new things. For example, I’ve always been terrified of dancing, but last week I tried salsa dancing for the first time. I didn’t care what people thought about me and I had a great time at the event.
Here’s my favourite quote about lifting:
That weight when squatting isn’t pressure. It’s adversity. Remember that feeling. Hold it, picture it, grasp it, bottle it. That fear is you pushing yourself way you of your comfort zone. You’ll get that same fear doing anything worth doing. Anything that’s intimidating and challenging. When you squat you are transcending your adversity and fears. The weight is all of your doubts and fear manifested into a barbell and some weights. When you squat, you’re praying. For the strength and willpower the transcend your limits, for the ability to rise and get back up.
2. Think long-term.
When I squatted for the first time, I was whobbly with the 45lb bar. Now, I can squat 315lbs for 5 reps. During this journey, there were times where I was lifting with my ego, and tried to go for unnecessary short-term personal records. This sometimes resulted in stalling, or even injuries. With an injury, your one month of good progress might suddenly become two months backwards in progress.
While I still do celebrate small short-term victories every now and then, it’s the long-term mentality that I value the most. Assuming a steady and injury-free progress, I’ll be a heck lot stronger in a year from now than I am today.
3. Time management.
I spend about 10 hours a week lifting and commuting to and from the gym. Although it’s a large time investment, I’ve actually gained more productive time by being better at managing my time. I usually go to the gym in the mornings, so this forces me to sleep early and wake up early. During busy weeks, I make sure I focus on getting my work done, so I never have to skip a gym day.
4. Progress is non-linear.
In my first few months, I experienced the phenomenon called ‘beginner gains’, where I went up 5 lbs on my lifts every workout. Gaining strength is a lot harder to come by now.
In terms of my physical appearance, it changed quite a bit month-over-month in the first 9 months. After that phase, monthly changes were less noticeable. For anyone that wants to get started with lifting, the good news is that you can achieve a great physical transformation in under a year.
Over a 10-20 year scale, I believe strength progress should be logarithmic.
5. Train smart, not hard.
Strength progress is not directly proportional to the amount of effort you spend training. You should come prepared with a plan that includes progressive overloading, and sick to the plan. Don’t be that person who goes to the gym, does random lifts, and makes no progress over months.
I’ve also learned that more days of training doesn’t necessarily result in better progress than less days of training, i.e. 6 days vs 4 days. It’s possible to overtrain, which negatively affects your progress by not getting enough rest.
6. Focus on one thing.
“I want to gain strength, be lean, and build muscle.” While it’s not impossible to achieve that statement, it’s definitely very difficult to achieve naturally. Instead of trying to achieve everything, I would recommend to just stick with one thing. For months, I was running a program that promoted both powerlifting and bodybuilding. Though I did get a bit of strength, and some size, I felt like it wasn’t ideal for progress overall. After I switched to a program that focused exclusively on strength, I increased my squat by 45lbs in 10 weeks.
7. Lifting is only 20% of the work.
The remaining 80% comes from proper dieting, staying consistent, getting enough rest, and training smart. If you lift and don’t eat well, you won’t get great progress. If you’re trying to lose weight and don’t change your eating habits, you won’t get far.
Abs are made in the kitchen, not the gym.
8. Social environment.
By design, the gym is a community of people that share similar interests. It’s a great way to make friends. If you’re ever looking to make new friends or bond with existing friends, the gym is an awesome place to go to.
9. Be obsessed.
This lesson doesn’t apply to everyone. Since discovering powerlifting, I’ve become obsessed with it. I want to constantly improve myself in all aspects. I record my workout videos, and watch them to see where I can improve my form. I preach lifting to my friends and co-workers. I’ve written two blog posts about lifting. You get the point. Whether this obsession is positive or negative, I’m genuinely happy to have discovered something that makes me so passionate. 😄


Your Home for Real Estate.
For Sale
For Rent
Sold
Search
Open Homes in
New York, NY
Request Info
View Home Details
Tue May 27, 1pm to 3pm
Open House
$299,000
408 W 25th St #4-RE
- Chelsea
Apartment
Sun Jun 1, 2pm to 4pm
New
Open House
$1,895,000
50 Orchard St #3C
- Chinatown
2 bd, 2 ba
1,268 sqft
Condo
Sun Jun 1, 2pm to 3pm
Open House
$675,000
340 W 55th St #2D
- Clinton
900 sqft
Coop
Wed May 28, 6pm to 7pm
Open House
$965,000
630 W End Ave #1
- Upper West Side
2 bd, 1 ba
Coop
Homes for Sale in
New York, NY
$2,500,000
165 Duane St #3B
- Tribeca
2 bd, 1 ba
Coop
$2,250,000
2nd Avenue and East 17th Street
- Gramercy Park
2 bd, 2 ba
1,110 sqft
Apartment
$750,000
540 W 49th St #302S
- Clinton
521 sqft
Condo
$435,000
900 W 190th St #6J
- Fort George
1 bd, 1 ba
760 sqft
Coop


Central London Hatchery and Conditioning Centre
-enter-
-pick a class-
alpha
beta
gamma
delta
epsilon


OpenUrl -nCoV entry cathepsin CrossRef cells teicoplanin protein &; SARS-CoV coronavirus activity cell cleavage infected using virus Abstract TMPRSS luciferase pseudoviruses used FREE Figure Text intracellular sequence novel -nCoV. HIV-luc/-nCoV Science respiratory MN, new receptor sequences spike various China GraphPad Teicoplanin Web acute alignment dalbavancin incubated measured post-infection. protease ANOVA Prism acid amino cells. including inhibit one-way results severe shown syndrome vancomycin viruses *P<; -nCoV, ./s--- ACE Coronavirus HEKT Med National Ordinary SARS SEM. analysis. calculated cellular concentrations. different early host important infection mean medium multiple proteolytic pseudoviruses. site specifically target test viral AY, Program Research based drug effect fusion glycopeptide infection. inhibitory required software. -nCOV ./pnas. Cathepsin Chemical Download Engl Gram-positive Huh Lancet Open Wuhan, activation antibiotics antibiotics, antiviral clinical data data-hide-link-title=""> data-icon-position="" endosome figure fresh generated genome height identified incubation indicated inhibits measured. pneumonia potently representation repress routinely-used showed siRNA significantly stack structure tab transfected treatment washing


I had been anticipating getting salvia in the mail for two weeks now. I had tried regular salvia leaves once before, achieving nothing more than a *stoned* feeling. When I received my products in the mail, I located a bong and sat down to hit a small bowl in my room.
I had 4 friends standing with me, all of whom are experienced with LSD and the like, but had never heard of Salvia before I told them about it. I had prepared myself by reading about salvia on the internet, and told them what to expect (typically users of salvia will forget they smoked salvia, and will act confused). I lit the small bowl (25 mg 10X enhanced leaf) and inhaled the whole thing in one bong hit.
My heart was racing. Not from the salvia itself, but from anticipation of it, and hearing how strong it could be. What came next is strange, but in a way similar to an LSD trip.
I started feeling stoned, and was waiting for the effects to come on. Before I knew it I had launched into the salvia dimension, but had difficulty figuring out what I was experiencing.
I looked at my friends who were all standing near me waiting for me to say something. Behind them I saw my doorway, but my friends were the doorway and the door. This was confusing, so I looked to the other side of the room, and I saw images of my friends all standing side by side, as if they were now the wall. When I stared straight ahead, I 'knew' or 'perceived' rather than saw, millions and millions of people, all stacked upon each other like blocks, for miles ahead as far as I could see.
Soon it felt like the salvia trip was wearing off, so I turned to my friends to talk to them, but when I looked at them, it was like looking at a rolodex. My friend standing there was the 'top paper' in the rolodex, and there were images of him protruding from his front and back. This happened every time I looked at one of my friends, but didnt seem to happen if I looked at an object, nor did it feel like it was happening to me (I wasn't aware of my own body most of the time, except when I launched into salviaworld, I felt my head droop but could not make myself move it). The trip took around seven minutes, but feels shorter.
The two disappointing things about salvia are:
1. The stronger 5X and 10X extract needed for even mild trips are expensive, and last only a short time.
2. Unlike LSD or MJ, you don't really remember that you have taken a drug, so that you can't really appreciate the effects as you experience it.
I would experiment with salvia more, especially because it is legal, and next time I would lie down and hold the smoke as long as I can. Also, I am going to try to retain consciousness as I trip, so that I can *understand* as I experience.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


Nathan Leung
About
Portfolio
Contact
Portfolio
Hangman
RPG Game
Trivia Game
Rutgers Info Widget
Rock Paper Scissors
Connect with Me


setwd("~/Desktop/tidytuesday/data/2019/2019-12-24")
library(readr)
library(dplyr)
library(ggplot2)
library(sentimentr)
library(kableExtra)
library(spotifyr)
library(genius)
library(purrr)
songs <- read.csv("christmas_songs.csv", stringsAsFactors = F)
lyrics <- read_tsv("christmas_lyrics.tsv")
Let’s see how basic sentiment analysis classifies these Christmas hits. Luckily, I already have this code ready to go from my R Ladies Lightning Talk.
allSentiment <- sentiment(lyrics$lyric)
lyrics$id <- 1:nrow(lyrics)
lyrics2 <- merge(allSentiment, lyrics, by.x = "element_id", by.y = "id")
tt <- lyrics2 %>% group_by(track_title) %>% summarise(meanSentiment = mean(sentiment)) %>% arrange(desc(meanSentiment)) %>% head(5)
kable(tt) %>% kable_styling()
| track_title | meanSentiment |
|---|---|
| Silent Night | 0.6897360 |
| Sing Noel | 0.5814179 |
| God Rest Ye Merry Gentlemen | 0.3192399 |
| Hark! The Herald Angels Sing | 0.2859315 |
| O Holy Night | 0.2756963 |
tt <- lyrics2 %>% group_by(track_title) %>% summarise(meanSentiment = mean(sentiment)) %>% arrange(meanSentiment) %>% head(5)
kable(tt) %>% kable_styling()
| track_title | meanSentiment |
|---|---|
| You’re A Mean One, Mr. Grinch | -0.1200570 |
| This Cold War With You | -0.0752970 |
| To Each His Own | -0.0490823 |
| Come On Into My Arms | -0.0465882 |
| I’ll Break Out Again Tonight | -0.0404023 |
There is a big peak at zero and then plenty of positive sentiment songs, but I would have expected more. However, this is just some basic analysis, so a more sophisticated approach might yield more like we expect.
lyrics3 <- lyrics2 %>% group_by(track_title) %>% summarise(meanSentiment = mean(sentiment))
ggplot(lyrics3, aes(meanSentiment)) + geom_histogram() + theme_minimal()
tt <- lyrics2 %>% filter(track_title == "You're A Mean One, Mr. Grinch") %>% select(sentiment, lyric) %>% arrange(sentiment) %>% head(5)
kable(tt) %>% kable_styling()
| sentiment | lyric |
|---|---|
| -0.5833333 | You’re a bad banana with a greasy black peel |
| -0.5833333 | You’re a bad banana with a greasy black peel |
| -0.4472136 | You’re a nasty, wasty skunk |
| -0.4472136 | You nauseate me, Mr. Grinch |
| -0.4472136 | You’re a crooked, jerky jocky |
What makes “Silent Night” so positive? Repetition! Free idea: analyze the repetition of the holiday hits.
tt <- lyrics2 %>% filter(track_title == "Silent Night") %>% select(sentiment, lyric) %>% arrange(desc(sentiment)) %>% head(5)
kable(tt) %>% kable_styling()
| sentiment | lyric |
|---|---|
| 1.06066 | Sleep in heavenly peace, sleep in heavenly peace |
| 1.06066 | Sleep in heavenly peace, sleep in heavenly peace |
| 1.06066 | Sleep in heavenly peace, sleep in heavenly peace |
| 1.06066 | Sleep in heavenly peace, sleep in heavenly peace |
| 1.06066 | Sleep in heavenly peace, sleep in heavenly peace |
Now let’s compare these songs to the songs on the Stoudt Christmas CD. This CD was lovingly curated by my dad, and I have listened to it every Christmas that I can remember, from in the car driving across Pennsylvania to see family to while decorating the tree. This year I don’t get to hear it played from the real CD at home, so I had to make a Spotify version. Check it out here. Usually I’m all for a good shuffled playlist, but this one has to be listened to in order, because TRADITION.
As soon as I hear those opening lines of Paul McCartney’s “Wonderful Christmastime” I know it’s holiday time!
blogdown::shortcode("youtube", "94Ye-3C1FC8")
spotify_client_id <- "" ## put yours here
spotify_client_secret <- "" ## put yours here
access_token <- get_spotify_access_token(client_id = spotify_client_id, client_secret = spotify_client_secret)
stoudtChristmas <- get_playlist_tracks("0bso6lvKInn3myZ65vCSyj", authorization = access_token)
safe_lyrics <- safely(genius_lyrics)
artists <- unlist(lapply(stoudtChristmas$track.artists, function(x) {
x[1, "name"]
}))
track_name <- stoudtChristmas$track.name
lyricsStoudt <- mapply(safe_lyrics, artists, track_name, SIMPLIFY = F)
didItWork <- lapply(lyricsStoudt, function(x) {
x$error
})
sum(unlist(lapply(didItWork, is.null))) ## 14 of 21 have lyrics
setwd("~/Desktop/tidytuesday/week52_2019")
save(lyricsStoudt, file = "lyricsStoudtChristmas.RData")
Unfortunately, this Bruce classic got dropped.
blogdown::shortcode("youtube", "76WFkKp8Tjs")
setwd("~/Desktop/tidytuesday/week52_2019")
load(file = "lyricsStoudtChristmas.RData")
test <- lapply(lyricsStoudt, function(x) {
x$result
})
allL <- do.call("rbind", test)
allSentiment <- sentiment(allL$lyric)
allL$id <- 1:nrow(allL)
allL2 <- merge(allSentiment, allL, by.x = "element_id", by.y = "id")
tt <- allL2 %>% group_by(track_title) %>% summarise(meanSentiment = mean(sentiment)) %>% arrange(desc(meanSentiment)) %>% head(5)
kable(tt) %>% kable_styling()
| track_title | meanSentiment |
|---|---|
| Peace On Earth / Little Drummer Boy | 0.2620499 |
| Christmas Wrapping | 0.2461397 |
| Feliz Navidad | 0.2355009 |
| Rockin’ Around the Christmas Tree | 0.1862966 |
| White Christmas | 0.1810358 |
tt <- allL2 %>% group_by(track_title) %>% summarise(meanSentiment = mean(sentiment)) %>% arrange(meanSentiment) %>% head(5)
kable(tt) %>% kable_styling()
| track_title | meanSentiment |
|---|---|
| Blue Christmas | 0.0289615 |
| Jingle Bell Rock | 0.0459830 |
| Snoopy’s Christmas | 0.0695365 |
| I Saw Three Ships | 0.0697308 |
| I Saw Mommy Kissing Santa Claus | 0.0698132 |
How does the Stoudt family Christmas album compare? We’re pretty positive (in red) in comparison to all of the hits.
allL3 <- allL2 %>% group_by(track_title) %>% summarise(meanSentiment = mean(sentiment))
ggplot(lyrics3, aes(meanSentiment)) + geom_histogram() + theme_minimal() + geom_histogram(data = allL3, aes(meanSentiment), fill = "red")
Happy Holidays!


LegitPoll
Create a new Topic
Vote for a created Poll
View My Votes
signout
Create Topic
Start Date:
End Date:
Options:


--- notes: | **Only** use `flat` when there is no ambiguity whether or not it's a button. --- Default Default Primary Primary Destructive Destructive Flat Flat


(Route : Message Menu, Copy Command)
This dialog box allows you to copy a message from one location to another.
With one or more messages highlighted in the thread window, select the Copy command on the Message menu. From the Copy Message dialog select the topic you want to copy the message(s) to. Note that if the destination topic is not a local topic then the message(s) will be posted to that topic when you next connect.