FavIconX : Make progress bars out of favicons.

Last week on my NAS I found some old code that I had created about 2 years ago. It was a small (7kb) vanilla library that enabled you to make progress bars out of your browser tab icons. I never released it because it was so similar to piecon. However it seems that piecon hasn’t been updated for the past two years. Since my library has a bit more configuration options, I thought I could brush up some documentation and open source it for anyone to use.

FavIconX is now yours to play with.

Cheers!

How AngularJs will save JavaScript from its $ sign

I usually never rant about other programmers, considering myself only an average programmer. But as a community of developers, I think we are doing an awful job of helping people understand that jQuery != JavaScript. And I think that AngularJS will be a great asset in that regard.

The ever-amazing jQuery
I won’t say it enough: jQuery is an amazing piece of work and I cannot remember or imagine how we ended up building front-end code without it back in the days. It has saved us as developers at a time when every browser was going left and right: in 2006, Internet Explorer 6 was still leading the dance even though it didn’t comply with a bunch of basic w3c standards (boxing hell, transparency hacks, etc.). Firefox was on the rise and Chrome wasn’t to be released until 2 years later. jQuery provided us with the most powerful tools to master the DOM without ever worrying about the browser. It was simply revolutionary. We were also very lucky that its creator, John Resig, only 22 at the time, made it clear from the start that his library would stay completely open sourced, distributed with no strings attached. I want to emphasize that because it deserves to be praised. This was 8 years ago. There was no GitHub. Open source projects weren’t the latest fashion that it has become today. But unlike other people who were more interested about money than about improving the web, John stayed true to his word and conviction by being an advocate of open source software. Like a few others, he is one of the great hackers of our generation who have revolutionized our industry.

JavaScript sucks, jQuery is so cool
jQuery’s success was not only caused by its licence model or its cross-browser dom manipulation power, it was also caused by the fact that JavaScript was (and still is) an unpopular and misunderstood language.

If you ever get a chance to look at client source code from the websites that were built at the time, you will quickly see why people despised JavaScript. Everyone (including me) was doing it wrong, with files scattered everywhere using hundreds of differant coding style. There was no structure. Things could be done a thousand ways and noone would tell you which was the right one. People would randomly create variables on the global scope with very precise names such as data or i. There were memory leaks everywhere. There was no need for jslint, no need for convention, no need for a grumpy old man to tell you what to do. Noone ever bothered to create very clean JavaScript code. It was just something that people usually rushed at the end of the dev cycle in order to produce some quick and dirty client-side effect or field validation. It wasn’t even considered a real language, something that you could put on a resume or that you could brag about.

I’ve always believed that anyone can produce the crappiest code with any programming language or framework. Yet I think that some languages make it easier than others, PHP and JavaScript being the first 2 that come to mind.

The truth is: people didn’t like JavaScript because they didn’t understand the language. They looked at it as some trivial scripting language that anyone could code by typing random keys on a keyboard. People did not take the time to learn the subtleties of the language because they despised it. This is why jQuery came out so strong. People were seeing it as an escape from JavaScript, something that would replace its ackward and aweful syntax. DOM manipulation became easy, and it could be done properly without worrying much about anything else. jQuery was just so cool.

$(2 + 2)
From that point on, jQuery was adopted into every single website out there. And any website who didn’t use it would have been foolish not to do so. This was at the time when people would test each browser version number and specify which was supported. Chrome was released and butchered the old version numbering traditions by going from Chrome 1 to Chrome 8 in less than a year. It became impossible to go by without using jQuery’s hassle-free cross browser code. And yet, while jQuery solved many issues for us at the time, it didn’t address the most important one: people were still coding in JavaScript without knowing anything about JavaScript. All the complex parts of the language were wrapped and hidden so that anyone could build clean client code using the library. How many times have I wished that jQuery’s scope management hadn’t been left out to die, forcing people to keep references of this and that everywhere. (kudos to ExtJS for doing the exact opposite by the way)

And so it was that everyone’s toolbox was soon to be only filled with this all-in-one hammer called jQuery. You have a JavaScript problem? jQuery is the answer! Just look at StackOverflow’s JavaScript questions and answers. Every “vanilla” (I’m not found of that word…) JavaScript question is answered or tagged with a jQuery answer, making it even more complex to differenciate one from the other. jQuery started as a helper library. It became an imposed non-requirement. It’s been said a thousand times:

when all you have is a hammer, everything starts to look like a nail.

At that rate, I was predicting that people would soon do simple math using the $ sign. I would have bought some candles for Brendan Eich. This is where I am ranting about our community of developers. We need to do a better job of helping people understand that jQuery is not JavaScript. We should not answer with jQuery when it is not needed. We should also provide JavaScript answers to jQuery questions when jQuery has nothing to do with the problem. It is our duty to help others understand the language more, as it is quickly becoming the most important programming language in the world. We need to help people open up jQuery’s source code, understand its magic methods like $.extend or $.ajax, or how it manipulates the DOM. Just like 10 years ago, anyone today who has only done object-oriented programming will be thrown off by JavaScript’s prototype-based language and dynamic typing. But if one starts digging into what makes JavaScript unique, understanding the concepts of closures, anonymous functions, first-class functions, class-less syntax, he/she will immediately realize how beautiful, complex, and powerful JavaScript can be.

AngularJs to the rescue!
It seems hard for Google to create something that isn’t amazing. Their quality standards are part of what makes the internet great today. AngularJs came out late 2010. With about 2 releases a month using entertaining codenames like sneaky-seagull or barefoot-telepathy, it quickly started getting recognition as a new way to build complex, rich and unified single-page applications. As of today, it is one of the hot and trending tag you want to put on your resume.
Of course there have been other breakthroughs with the JavaScript usage, such as its usage on the server side. But the unique thing about AngularJs is that when designed correctly, your app should not include both angular.js and jquery.js. When designed correctly, AngularJS makes jQuery obsolete by taking care of the DOM manipulation in its own way. And as people stop using jQuery, they once again have a chance to dig into the wonderful world of JavaScript they had once despised.

Don’t misread me. I’m not saying that people should forget jQuery and replace it with AngularJS. It would be of no worth to replace an all-in-one tool with another. But as people strive to have multiple tools in their toolbox, they might end up realizing that they don’t need a sledgehammer to crack a nut.

CodingGamers

I have been thinking about a new game concept for a while. It targets a niche community so if you are part of that community I would love to hear your feedback as I make progress on this hobby project.

This post will be long because it describes the gaming concepts. No TL;DR; sorry.


Title: CodingGamers
Genre: Educational / RPG / Small games
Description: Programmers and Gamers will meet on this platform to create and play games with an RPG flavor, retracing the history of computer Gaming.
Inspirations: Game Dev Story, Upgrade Complete, CodePen, PlayMyCode, and the recently discovered awesome Untrusted

Starting up
Registration is free and is done through Tw / Fb / G+.
The user starts the game with the following stats:
– money: 150₲ (virtual currency)
– # games made: 0
– reputation: 0
– game company: none
– experience: 0
– year: 1980 (first era of time)

The virtual currency ₲ is used to:
– purchase/upgrade a more recent computer
– play games compatible with the acquired hardware
– purchase a game engine to create better games
– enhance a game engine

The objective of the game is to unlock all perks, advance through the years and reach the hall of fame with a stellar game. A user is both a gamer and a game developer.

Eras of Time
– There are 5 eras of time (1980, 1982, 1985, 1989 and 1992) that can be unlocked once the user reaches a certain amount of XP points.
– Experience is gained by shipping the games one creates and by finishing games others created.
– The site’s bootstrap theme, the available hardware and games reflect the era that the user is in.

WebSite Presentation
Once registered, the user can login to his homepage.
Dashboard Tab : stats about the user’s company, his game sales #, his gaming stats, his friends stats, gaming news, game ads
Tseam Library Tab : library of all the games the user has purchased with ₲.
Coding Lab Tab : library of all games in current development
Dry’s Electronics Tab: shop where the user can purchase new computers, parts, and game engines.
iShopGame Tab : shop where the user can purchase games developed by the other users.

Whether or not the user will be mostly a player or a programmer, he cannot do anything until he has purchased his first computer, which is why he starts off with some ₲. Initially the user is set back in 1980. He can only purchase the most basic computer:

– Computer Name: IBN Personal Computer
– Requirements: 100₲ + year > 1979
– Specs: 1-bit display (black&green), 80×24 characters display, 8kb memory
– Upgrades available: memory up to 32Kb: 4kb = 20₲

The user is then led back to the homepage where he can:
#1/ start playing games that his computer can handle
#2/ start his own game company and career as a game developer

#1 : Playing Games
The user goes to the Games Shop where he sees all the games that have been released by other users and which match the era/period that he is in. Each game has a price (₲), a description, a cover image, user rating, the developer’s reputation (overall rating on the games released), and finally hardware requirements.

(Games can be sorted by name, # sales, release date, company, rating. Some games are grayed out as the user might not have the required specs to play them such as unsufficient memory, etc.)

Every time the user purchases a game, 50% of the ₲ goes to the developer.
The game gets added to the user’s game library where the user can play it, complete it, and then rate it.

The user gains experience by completing other user’s games and rating them once he has completed them. (ratings make up for the developer’s rep) Once he has enough experience, he may advance to the next era: the website theme is modernized, more advanced computers and parts can be purchased. The new hardware allows the player to play games with higher requirements.

#2 : Creating Games:
The first time the user goes into the Coding tab, he will be required to create his game company with a permanent name and custom-made pixel-art logo. (which will be displayed at the start of the games he makes)

He will then see all the current games that he has in development.
He can edit or create a new game.
Should he decide to create a new game, he is first asked to select one of his computers to develop the game on as well as a game engine to use. This choice cannot be changed after for that game.
The user is then taken into a CodePen-like environment where he uses the game engine to produce a full game.

Game Engines
Game Engines need to be bought to build games with. They require a certain type of hardware before purchase.
The better the engine, the more features it has (palettes, fonts, collision, music, sounds, etc.)

Example for first available engine:

– Name: 7UPERTXT-NG-3000
– Price: 30₲
– Required Tech: IBN Personal Computer
– Great For: Tiny Text-Based Games
– Speed: 5 FPS
– Available API methods to interact with display:
void write(txt, [x], [y], [color])
string input(txt, [x], [y], [color], callback)

Each game engine tech is a subset of a full custom yet fairly simple HTML5 game engine.
Each game engine comes with its manual (basically the API doc). New engines include descriptions / tutorials of the new API methods that were unlocked.

Programming
Coding is made in javascript and will use the API methods provided by the selected engine version.
Once a computer and game engine have been selected, the user enters into creative mode with an editor on the left and the results on the right.
Each game is required to have an ending. The length of the source code (# characters) is limited by the computer memory specs. Developers will not be able to write source code that exceed the amount of his computer.
Gamers cannot play games whose source codes exceed the memory amount of their computer

Assets have to be hard-coded in the game code. Images will be arrays of color pixels matching a given palette.
Musics will be transformed from string (http://keithwhor.com/music/, http://en.wikibooks.org/wiki/QBasic/Appendix#PLAY)
Sounds will be fetched from a provided sound library.
This means that the entire game can be exported as a single file and used freely elsewhere.

Once the game is ready for release, the player submits a unique title, a game type, an uploaded squared 256×256 image logo and a selling price in ₲. He can also purchase an ad campaign that will give his game more visibility to the other users (it appears in people’s dashboards, gets promoted in the Game Store, etc.)
The requirements for gamers to buy the game match the developer’s machine specs.
The developer can also decide to open-source his game so that others can view the source code freely.

The game is then in green-light beta, meaning that they have to be approved by the website’s mods before being public.
Website mods will have to play the game to moderate it (check if ending possible, no hacks, no spam…) and then assign the amount of xp gained when completed. Once approved, the game is released and appears in the store. Developers gain XP when a game goes gold, they also gain ₲ from game sales.
With enough XP, they can advance to the next era. The ₲ allows them to purchase better computer, computer parts, game engines, and make better and more expensive games.

Proof of Concept:
Here is a simple hangman game created with the most basic game engine / game computer combo. You can see that the main game loop is already in place and the rendering is done by the engine. The code is updated live and should be running in its own frame for security.

Additional Notes:
Users can gain additional ₲ by promoting the site (social network shares), getting referals (new users), or simply being active: logging in, reviewing
games, etc.
A game that reaches a certain amount of sales is called a hit. These games can have sequels which have benefits (people who game good score to the original game are notified of the new release, etc.)
Every week a new game theme is given. At the end of every week, one game from each era is selected to get a theme award.
Once a game has been released, it cannot be re-edited. Code is view-only. Bugs remain bugs. This is the floppy disk era. Release when bugfree!
Every month a high-end game is selected to be elected to the Hall of Fame (another front page tab) and the programmer wins the game.
Everything reflects the era the user is in: the web app interface, the code editor, the games, etc.
The Game Engine API will be open sourced on GitHub

Technical Notes:
Executing someone else’s javascript is always a bit frisky… We’ll have to take the same disposition as jsfiddle / codepen.

Possible computer specs according to the accessible eras:
Computer Name: IBN Personal Computer
Requirements: 100₲ + year > 1979
Specs:
– 1-bit display (black&green)
– 40×24 characters display (320×192)
– 8kb memory
– 1 simultaneous keys
Upgrades available:
– memory up to 16Kb: 4kb = 20₲ for ex.

Computer Name: ZED Spectrum
Requirements: 300₲ + year > 1982
Specs:
– 2-bit display CGA (8 colors)
– 80×48 characters display
– 16kb memory
– 2 simultaneous keys
– music 1 channel support
– up to 16 simultaneuous sprites

Upgrades available:
– additional fonts
– additional palette
– memory up to 32kb

Computer Name: AGIMA 1000
Requirements: 500₲ + year > 1985
Specs:
– 3-bit display EGA (64 colors)
– 320×200 pixel display
– 32kb memory
– 3 simultaneous keys
– mouse support
– music 1 channel support
– sound 1 channel support
– up to 32 simultaneuous sprites

Upgrades available:
– additional fonts
– additional palette
– additional sounds
– memory up to 64kb

Computer Name: 386SX25
Requirements: 1000₲ + year > 1989
Specs:
– 4-bit display VGA (256 colors)
– 320×200 pixel display
– 128kb memory
– 4 simultaneous keys
– mouse support
– music 4 channel support
– sound 4 channel support
– up to 64 simultaneuous sprites

Upgrades available:
– additional fonts
– additional palette
– additional sounds
– memory up to 1028kb

Computer Name: 486DX2-66
Requirements: 2000₲ + year > 1992

Specs:
– 4-bit display VGA (256 colors)
– 640×480 pixel display
– 512kb memory
– 4 simultaneous keys
– mouse support
– music 8 channel support
– sound 8 channel support
– up to 256 simultaneuous sprites

Upgrades available:
– additional fonts
– additional palette
– additional sounds
– memory up to 4096kb

Javascript inheritance without loosing class names

There are a LOT of articles out there that talk about Javascript inheritance, or even object-oriented javascript in general. There’s been thousands of frameworks that have provided javascript with the notions of encapsulation, classes, etc. This is probably because prototype-based programming is not intuitive to all those who work regularly with object-based languages such as java, php, ruby, c#, etc. Just look for object-oriented javascript stuff on github, you’ll find thousands of open-source frameworks / snippets… So why do people bother so much about turning javascript into something it’s not?

Well my personal thought is that it’s actually a good exercice. It really helps one understand and appreciate the depths of the prototype-way of thinking. In fact, I think that all javascript developers should create their own $.extend framework so that they may discover the subtleties and power of prototypes.

Anyways… I was reading some of the most famous inheritance scripts out there, starting out with this bright snippet from John Resig. I also went through the sources of the most appreciated related github projects (ooliboorja to credit a few) and quickly realized that all of them shared a big issue, which is best described in one of John’s comments : “@Justin: I don’t think there’s a reasonable way to actually assign a name to the classes, which is unfortunate.”

The problem

There are two ways to define a class in javascript:

1. var myclass = function(){...}
2. function myclass(){...}

Even though they may look alike, those 2 methods are very different :

1. creates a function that doesn’t have a name (anonymous function) and assigns it to the variable myclass
2. declares the function named myclass

It is important to note that “you cannot change the name of a function, this property is read-only.”. In other words, once you have started using an anonymous function to create your class, you will never be in control of the class name.

The impact

Let’s take John’s Resig’s code snippet and apply it in the console:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },
  dance: function(){
    return this.dancing;
  }
});
 
var Ninja = Person.extend({
  init: function(){
    this._super( false );
  },
  dance: function(){
    // Call the inherited version of dance()
    return this._super();
  },
  swingSword: function(){
    return true;
  }
});
 
var p = new Person(true); 
var n = new Ninja();

Both object’s class names are ‘Class’:

p.constructor.name; // 'Class'
n.constructor.name; // 'Class'

While this may not be a problem when dealing with small examples, it becomes a huge PITA when debugging a big javascript project based on anonymous functions. Try making an HTML5 game with it and you will see how fast it gets on your nerves. hence I looked at about 20 different pieces of code but the same issue / code pattern was there. In fact I haven’t seen any framework that could provide me with ninjas beeing Ninjas and persons beeing Persons (did I miss it along the way??).

So last night I wrote my own little inheritance snippet. It uses dynamic function naming to circumvent the issue above:

moo.js

There are a couple of objectives I wanted to achieve:

– achieve basic inheritance
– allow subclass methods to override / call upon their super methods
– have classes retain their class names
– support for event management

The code is released under the MIT licence. Feel free to use it at your convenience. I think it can be very useful for games or other object-oriented programs. It’s been tested with jasmine.

Project home with its documentation
Source code hosted on github

I’m sure it can be improved and i’m always open for feedback and criticsm so if you’ve got something to say, use the comments section below or create an issue in the github project.

Javascript declarations and assignments

This week I was chasing a javascript bug. At qualys we heavily rely on extjs, and we have a few thousands javascript files that have to live together. The bug ended up being in the following lines:

    ...
    renderer: function(layer, text){
        var tag = node = Ext.apply({
            color: '#FCFCFC',
            background: '#666666'
        }, layer);
        tag.text = tag.text || text;
        if(node.disabled){
            tag.style = "color: #CCC !important";
        }
        return tag;
    },
    ...

Can you see what’s wrong?

The issue comes from the first line, an unconvenient mix of declarations and assignments:

var tag = node = Ext.apply({...})

The developer thought he was initializing 2 local vars called tag and node.

Let’s take something simple:

    function test(){
        var a = b = 2;
        alert(a, b);
    }
    test();
    alert(b);

In the first line, javascript starts by evaluating b = 2. This is an assignment of 2 to the variable b. Because b does not exist, javascript creates a new global variable b and attaches it to the current context, window. (note that this would throw a ReferenceError exception if we were in strict mode).

A quick ref to ECMA-262 shows that assignments return the value that was just assigned. You can double check that in your console eval(b = 2); returns 2.

So now the compiler has evaluated the first expression and now reads var a = 2 since 2 was evaluated. This correctly creates a local variable a containing the value 2 through a declaration, or more precisely a VariableStatement. note that eval(var b = 2); returns undefined.

Anyways… don’t mix up var a = [value] with a = [value] as they are completely different expressions that evaluate to different values and can create unexpected surprises…

Magicsuggest 2 release

I was so caught up with different projects, work, family, the move to the us… That i hadn’t touched that plugin for almost 9 months… I finally decided to make it a priority to fix what needed to be fixed and improve what had to be improved.

So here comes 2.0.0:

– Flexible responsive design
– Full support of bootstrap 3
– An entire new home with a showcase, tutorials, an amazing documentation full of examples, etc.
– A bunch of fixes and improvements.

Drop me a line if you use it in your bootstrap forms!

Cheers

MagicSuggest 2.0.0:
Homepage
Demo
Documentation
Tutorial
Licence

Copying json objects into the clipboard

At qualys we often work with complex json objects that we have to debug. I just found out that chrome dev tools include a copy command that allows to copy any variable into the clipboard. This can be useful to retrieve full json objects:

copy(JSON.stringify(obj))

The object can then be displaying in a nice formatted way using a plugin within sublime or using an online formatter.