Code

Working with All Star Code in NYC to empower minorities to get into development

Sometimes it is great to work for a large company that gives you opportunities to do some good. I am currently in New York to run a workshop with All Star Code in our offices. Originally Aaron Gustafson was supposed to also be part of this but he got sick. Instead I am happy to work with Rachel White, Claudius Mbemba and Adina Shanholtz to help All Star Code.

Originally All Star Code approached me to get a bulk order for Surfaces for their students to work with. When I heard that their curriculum was involving Git, Node, Web Development and Debugging in Browsers and the stack was Sublime Text and Chrome Devtools I offered a small change. So now we’ll be teaching the teachers of All Star Code’s next course how to use Visual Studio Code and do all the development and debugging inside that one. My main driver there was that Code is open source and thus the students don’t need to get another license.

If you wonder what All Star Code does you can head over to the Decoded Chats blog, where I interviewed Mahdi Shadkamfarrokhi, their head of curriculum.

If you prefer to have an audio version, you can download it here (MP3, 18MB)

Here are the questions I asked:

  1. You work for All Star Code. Can you give us a quick introduction what that is and what you do? (00:13)
  2. How low are the numbers of developers that came from a minority background? What are the main reasons? (01:40)
  3. Do you think that by teaching communication skills together with technological skills you become more interesting for someone with a less privileged background? Is selling technology skills as a part of a whole package more successful? (02:49)
  4. The program has been running for quite a while. Is there a success story you are really proud of? (04:20)
  5. You learn a lot by teaching as you can’t fake it – you have to know. Do you find that it is easier to keep your skills up-to-date by running this program? (04:46)
  6. What are the biggest barriers for your students to get into development? Is it hardware access? Connectivity? The style and language of documentation out there? (06:14)
  7. I learned a lot because when I started computers didn’t do much and you had to program. Do you think that nowadays kids are less inclined to learn as computers are more seen as a consumption device? (07:47)
  8. There is a vast amount of online courses to choose from when it comes to learning how to program. Many of them decayed a bit after the first round of funding dried out. How do you find great and trustworthy resources? (10:10)
  9. A lot of creativity happens on the web but these makers don’t know or don’t get into professional development. Where do you go to find people for your course? (12:04)
  10. Do you see Open Source and services like GitHub to host, document and discuss your projects as an opportunity for newcomers? (14:49)
  11. How can people help you? Are there ways to volunteer? (18:07)

I’m very excited to be working on this.

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

js13kGames: Code golf for game devs

How much is 13 kB? These days a couple of kilobytes seem like a drop in the ocean. Rewind back to the dawn of video game history, however, and you’ll soon realise that early pioneers had to work with crazy limitations.

The beloved Atari 2600, for example, had a measly 128 bytes of RAM with cartridges supplying an additional 4 kilobytes. As the saying goes: constraints inspire creativity. The annual js13kGames competition channels creativity by challenging aspiring game developers to create a game using just 13,312 bytes, zipped.

A coding competition for HTML5 game developers

Js13kGames is an annual online JavaScript competition for HTML5 game developers that began in 2012. The fun part is the file-size limit, set to 13 kilobytes. Participants have a whole month (August 13th – September 13th) to build a game on the given theme – in 2015, the theme was Reversed.

js13kgames banner

Thanks to our friends and sponsors, this competition offers plenty of prizes, includes a panel of expert judges, free t-shirts, and other goodies, shipped worldwide for free. But winning is only one of the benefits of participation. There’s lots to be gained from being a part of the js13kGames community. People help each other if they’re stuck on something, share their tools, workflows, tips, and tricks. Plus, the constraint of a limited time frame helps you finish a game, and trains your skills in the process.

Last year’s winners

Thirteen kilobytes is not enough even for a low resolution image. The small screenshots on the entries pages are usually bigger than the games themselves! And yet, you may be surprised by what can be achieved in such a small size. Take a look at some of last year’s winners for inspiration:

Wondering how such features are implemented? I’ve interviewed the winners, asking them to share some of their secrets to success. They share tooling and techniques for game development with extreme constraints. And if you’re craving more details: all games are on GitHub, so you can dig through the source code yourself.

RoboFlip

RoboFlip

Eoin McGrath describes some aspects of his workflow for RoboFlip:

“The final entries can be zipped. Zip compression works much better on a single file than multiple files, so the best thing to do is inline all images, concatenate files, minify your JavaScript and remove any white space. Thanks to task runners like Grunt and Gulp this process can be largely automated. Check out the Gulp file that I used. A simple gulp build command takes care of all the heavy lifting and lets me know how much valuable space I have left.”

Gulp build task in action

Graphics

“First off, forget about high resolution sprite sheets with lots of animation frames. Simplicity is the key. A lot can be achieved with procedural generation or SVGs. I personally went for a retro-style pixellated look. First, all images were created at tiny resolutions (from about 6×6 pixels) in GIMP. I then encoded them in base64 and used the Canvas API to redraw them at a larger scale.”

Scaled up sprites

“Another handy trick I used was to run all images through a function that replaced non-transparent color values with white.”

Damage frame for crate sprite

“This proved a cheap and effective way to have damage frames available for all sprites.”

Sound

“A game with no sound effects is like coffee without the caffeine. Obviously, there is no way you can fit a single .mp3 or .ogg file into your game with the given limitations. Thankfully, there is jsfxr, which is a very nice library you can use to create some 8bit styled beeps.

For the musically inclined you can also have a stab at creating a soundtrack
using the Sonant-X library – check out this awesome playable example.”
(You may need to hit “Play Song” to initiate.)

Road Blocks

“One of the things I love about the js13kGames competition is the artificial limitation it places on you in terms of what you can achieve,” writes Ash Kyd, a game developer from Australia.

“I find as an indie dev, with more open-ended projects it’s possible to get bogged down by all the possibilities and end up with nothing to show at the end, whereas setting some hard limits makes you more creative in terms of what you can accomplish.”

Road Blocks

“Thanks to the filesize limitation, Road Blocks is a fundamentally simple game and didn’t require a massive amount of coding work. As a result, a lot of my time was spent polishing the gameplay and smoothing rough edges during the competition, which resulted in a higher quality product at the end of the month.”

Behind Asteroids – The Dark Side

“Js13kGames is a great opportunity to discover and experiment with cool technologies like WebGL or Web Audio — and improve your skills. With a 13 kB limit, you can’t afford to hide behind a framework. Also, obviously, you shouldn’t use images but try to procedurally generate them. That said, it’s up to you to find your style and use the tricks that suit you. Don’t fall into doing all the tricks right away – prototype first and compress your code at the very end,” advises veteran game developer and js13kGames winner Gaëtan Renaudeau.

Behind Asteroids

“One of the interesting tricks I’ve found to save bytes is to avoid object-oriented style. Instead, I just write functions and use Arrays as tuple data type – I’ve used this technique in the past for a previous js1k entry.

This is the third year I’ve participated in the js13kGames competition and the third time I’ve had fun with WebGL. My 2015 submission is a remake of Asteroids where you don’t actually control the spaceship but you instead send the asteroids. This is my take on the Reversed theme.

On desktop, the game is implemented by typing – a letter is displayed on each asteroid and you have to type it at the right moment. On mobile, it simply turns into a touch-enabled game.

The game is paced with different levels from beginners to more experienced players who control the spaceship which you must destroy with the asteroids. The spaceship controls are driven by an AI algorithm.”

How the game is rendered

“The game uses hybrid rendering techniques: it is first rendered on Canvas using basic 2D shapes and is then piped into multiple WebGL post-processing effects.

The 2D Canvas drawing involves circles for particles and bullets, polygons for asteroids and spaceships, and lines for the procedural font as the path of each letter is hardcoded. Game shapes are drawn exclusively with one of the 3 color channels (red, blue and green) to split objects into different groups that the post-processing can filter – for instance, bullets are drawn in blue so we can apply specific glare effects for them. This is an interesting technique to optimize and store different things into a single texture as the game is in monochrome.

The different effects involved in the WebGL post-processing are detailed in this post-mortem. The important goal of this final step is to graphically reproduce the great vector graphics of the original arcade machine.

A background environment map where you see a player reflecting into the arcade game screen is also added in the background. It is entirely procedurally generated in a Fragment Shader.”

Summary

You can employ a myriad of approaches to shave precious bytes off your code base. These range from the fairly well known to the more obscure. There’s an article on How to minify your HTML5 game over at Tuts+ Game Development, and you will also find a nicely curated list of tools and other materials at js13kGames Resources page.

I hope you’ve enjoyed this brief tour of js13kGames landscape and some of the winning code golf tricks past winners recommend. Tempted to give it a go this year? The 2016 competition starts in just a few days – on August 13th. Join us! It’s not too late to start coding.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Learning to code for the Web: The MDN Learning Area welcomes you!

As an aspiring developer or as a teacher looking to extend your knowledge of code, it can be difficult to know where to start with web technologies. In this blog post, we’ll be discussing why we have created the Mozilla Developer Network Learning Area to help solve common learning challenges and get you up and running with web development.

The aim of the Learning Area is to take beginners from “beginner to comfortable”, with HTML, CSS, JavaScript, and other core web technologies. Once you’ve worked through the early parts of the Learning Area, you should have enough knowledge to be comfortable using the rest of the Mozilla Developer Network (MDN) site. In addition to helping you on your learning journey, we anticipate that the Learning Area will extend our readership and contributor base, and in turn improve SEO on the site.

Why the new Learning Area?

Learning the craft of web design and development (and all the related disciplines) has been a hot topic for as long as we can remember. Many web education initiatives and resources have been worked on over the years, and many related problems have largely moved sideways rather than forwards:

  1. There is a shortage of skilled junior web creators coming into the industry.
  2. Traditional educational establishments often tend to be behind the curve in understanding the industry they are sending their students into. It is challenging to keep courses relevant and up-to-date. Many private code schools have appeared to fill the gap left by a lack of quality learning materials for beginning web builders.
  3. The above point is perhaps not so surprising when you consider that industry standards and best practices evolve very quickly, and also that web is somewhat of an orphan — it doesn’t comfortably fit into traditional technical departments like Comp Sci/Software engineering (too many “soft“ skills), or design departments (too much code and scary stuff like that). As a field of study, web is very much a hybrid.

Note: Many of the effective web-related courses at universities that “get it” are found in tangentially-related departments such as business and journalism. And speaking of the “bad” courses, teachers generally do care and want to improve things, but don’t necessarily have the knowledge or time to rapidly iterate on curricula. And the curricula are often slow to change because of bureaucracy.

It is MDN’s wish to help with such problems by producing a reliable set of beginner’s learning materials that will help students understand the technologies the web is built on, and how to use them to create accessible cross browser websites/apps. The MDN Learning Area aims to:

  • Make effective material whether the students are self-directed learners, or part of a structured class.
  • Structure the material loosely so teachers can use it as supplementary material on top of their own curricula, or a basis for new curricula. Too much structure makes the material limiting and not very flexible.
  • Cover a core minimum viable product consisting of HTML, CSS, JavaScript, accessibility, and server-side development basic concepts. The material should represent a standard for web learning and best practices. If enough educators use it, it will provide much needed consistency.
  • Regularly review the material to keep it up to date.

Note: We also want to make the publishing license permissive enough so that others can easily grab and use it in any way they desire. The default MDN license is cc-by-sa, which means that others can republish the content as they wish, as long as they credit the original author, and any modifications are published under the same license as the original, thereby keeping it freely available. The associated code examples are licensed under CC0 (anyone can use them as they wish without restriction).

Where are we now?

While we continue to add to the MDN Learning Area content, there is already plenty of modules that beginners can start to use. For a start, we have a complete beginner’s learning module for those who have no previous experience and only basic computer literacy: Getting started with the Web.

The next stage in the learning journey is our Introduction modules, which teach the real basics of the technologies. So far, we have one for both HTML and CSS:

To follow on from those, we have some further HTML and CSS modules, which aim to go beyond the basics and expand on some of the core applications of those technologies:

Each module has a number of articles to discuss the important features and techniques involved, plus an assessment or two at the end to test your comprehension of those teachings.

We also have a well-developed Glossary, and a list of standalone articles that address specific topics related to the main Learning Area thread, but don’t directly fit into the core learning stream: see common questions.

Future work

The latest module being written is CSS layout, which will cover all of the layout techniques currently in use on the modern web, with advice on what they should be used for.

Future content for the site will also include modules on core server side development basics, accessibility and JavaScript, and possibly other topics too.

Call to action

We are always looking for contributors to help write and otherwise shape the material — with such a small team of writers, it takes time to create all the material. Having extra people on board also helps with making for a better rounded set of ideas, feedback and styles.

If you feel inspired and want to help with contributing to the LA — whether with writing, translating existing material, tech review, copy editing, or other kinds of feedback, please get in touch! We are always happy to curate outside contributions, as it leads to a more rounded, collaborative effort.

We are also really interested in hearing from potential students and teachers that might want to work through the materials and provide feedback on their learning experience.

The best ways to get in touch with us are:

We also have a Trello board that gives an idea of currently available writing projects.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Mozilla ? Rails Girls Summer of Code

Mozilla is working hard to support and advocate for diversity in the tech industry. On that note, we are proud to announce our support and sponsorship of the Rails Girls Summer of Code program, 2016 edition!

Rails Girls Summer of Code & Mozilla

Rails Girls Summer of Code (RGSoC) is a fellowship program conceived to bring more diversity in tech, and open source in particular. It provides a three-month paid scholarship for members of teams of two to work on and contribute to an open source project of their choice. If you want to know more about the program be sure to check out Anika Lindtner’s talk on the motivations behind it and results so far:

There are two Mozilla-mentored projects this year accepting applications:

Servo

Servo is Mozilla’s nascent browser engine, completely re-written from scratch with modern requirements in mind (e.g. high parallelization and security). Servo also has one more trick up its sleeve, and that is Rust. Rust is a low-level programming language, that besides its merits in memory safety, speed, and concurrency, is highly praised for its vibrant and inclusive community. This, and the fact that teams are not required to have any Rust-experience to apply, make Servo a really nice fit for the program.

Check the Servo project page on RGSoC.

Despite what’s implied in the original name (Ruby and Rails), in the last few years a wide variety of open-source projects and languages have participated in RGSoC, including projects in Ruby, Python, JavaScript, Rust, and Lua. These days, there is great diversity in the range of projects as well as in the teams themselves.

Tween.js

Tween.js is no exception. Created by Soledad Penadés, Mozilla DEVANGENEER, Tween JS provides a small but powerful and efficient tweening (interpolation) library in JavaScript. It can used in a variety of applications, from games to animations to libraries. Teams applying for this project will have a chance to maintain and improve the library while exploring and experimenting, as well as increasing their webby skills.

Check the Tween.js project page on RGSoC.

Team applications are open until Sunday 10th of April.
Apply here, or contribute to the project and help a team gain the chance to get involved in open source.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

WebProfessionals.org Code of Ethics

Professional organizations and associations throughout history establish some sort of standard of operation or minimum standards of conduct which are considered acceptable for the profession and the members they represent. A generally agreed upon Code of Ethics can define the overall aim of the profession, and the ideals to which Web professional workers aspire.

As a membership supported organization for practicing and aspiring Web Professionals, we should adhere to a “higher standard.” We should “set the bar” for professionalism for our members. As such, we propose an adherence to a code of ethics and we invite you to participate in on the discussion.

Essentially, we should define our roles, rights and responsibilities in our relationships with other practicing professionals, those who rely on our services, and those who teach the next generation of Web professionals. Although we have espoused these since our inception, we have not formalized our “code of ethics” and we believe it’s  time to do so.

Why is this important now?

Today the world wide web plays an essential role in commerce, government, research, education, medicine, communication systems, entertainment and many other areas of our world. Web professionals who contribute to the development, design, implementation, analysis, specification, maintenance and evaluation of the many different applications of Web systems have a significant impact on society, making beneficial contributions to the customers they serve. However, some of these impacts may be less than positive for some clients.

To ensure that their efforts will be used for the the common good, Web professionals should commit themselves to making practicing within the of the profession a beneficial and respected one, including promoting an ethical approach to their practice.

As practicing professionals (and teachers), we are often in positions of great influence. Our students and clients look to us to guide them through a complex process. At a minimum, we should commit to a standard of conduct which should be generally agreed upon. Although we recognize that our Code of Ethics are not enforceable by law, we hope and should at a high level expect everyone to adhere to the highest standards when working in our field.

Why do we need it now?

As I recently mentioned on our blog, the lines are blurring for web professionals, tools are evolving rapidly; many Web professionals are expected to be experts in many different disciplines which increasingly challenging for both the practitioner and the customers we serve.

At the end.of the day, we need to be responsible to our clients and to our profession to be honest when we are not an expert in a given area. For our own sake, the sake of our clients and the sustainability of the profession we  should consider of putting those clients when appropriate in touch with another professional who may specialise in the areas we are the weakest.

Furthermore, we should refrain from trying to “be all things to all clients.” We need to clearly identify our strengths and clearly communicate those to our clients. For example, those who know me, know that I am “graphically challenged.” I would never try to develop a logo for a client. Instead, I would contract graphic artists I know and have them design the logo. While this is an obvious example, we often see web professionals try to interpret website analytics with limited knowledge of the underlying statistics and associated math.

If a Webprofessionals.org member works for you full time, part time or by contract, you should expect them to:

  1. Be open and truthful. Although we cannot guarantee that all of the members of the Webprofessionals.org community subscribe to this code of ethics, as a professional association we aspire to instill in our members and non members alike the highest ethical standards.
  2. Respect and protect your intellectual property. As web professionals and more specifically WebProfessionals.org members it’s our responsibility to protect the intellectual property rights of others including personal data and all electronic media and files. As web professionals we have a duty and a fiduciary responsible to protect the integrity by adopting and implementing best practices of our customer’s data and to keep it secure. We should keep client information confidential (whether we have signed a nondisclosure agreement or not).
  3. Be responsive. As web professionals we owe it to our clients and stakeholders to respond to inquires in a timely manner.  WebProfessionals.org members should candid about their  available response time and communicate that to customers in advance. It is important we set proper expectations in all communications with our clients and peers.
  4. Written communications: As Web professionals it is our responsibility to effectively communicate to our clients and stakeholders.  When making request of the customer or when making promises put them in writing.  Despite our best efforts, disputes sometimes happen. Having a well documented and agreed upon relationship will serve both parties. This should include all conversations about who does what and when, work to be performed, timelines, cost and change orders.

Why is this important to Web Professionals?

As practicing professionals,  it is important we be recognized for the time, money, and effort we have devoted to staying current in a rapidly changing technology field. We recognize that we have specific areas of expertise and we need to convey those to our customers. We also need to formalize how we will interact with peers. It is to no one’s benefit to have deceitful practices or to promise more than one can deliver. The whole of our profession is harmed when there are such “bad apples.”

Why is this important to consumers?

You are hiring a professional (or committing to learn from a professional teacher). If you are planning to comparison shop and base your decision solely on price, we wish you all the best with that. Designing web sites is a complicated process. Do not hire an amateur. Practicing professionals have years of experience in user experience design, search engine optimization, accessibility, and a host of additional skills. When you meet with an amateur, you will likely find they ask a limited number of questions. They may also not be able to share their overall process. They may even offer to do some initial work for free. Practicing professionals will ask a host of questions to better understand your business goals and objectives and how a website can help you realize these. They will share their overall process and help you better understand why aspects such as user experience design need to be conducted. They will also not do work for free. As a professional, they have spent a great deal of personal time and money keeping their skills up to date (no small feat in today’s rapidly changing field). You are paying for their expertise and current knowledge.

Why is this important to those who teach the next generation?

As teachers, we have a special responsibility to stay knowledgeable as technology changes. We also need to focus on a solid foundation and understanding of these technologies so our students have a firm basis to learn. We also need to encourage our students to develop a habit of lifelong learning. We should not provide all the answers, but should point our students in the proper direction and encourage them to think for themselves. This field changes so quickly, it is not possible to keep up on all aspects of these technologies. We need to recognize that and show our students how to learn. We do our students a disservice if we provide all the answers and “spoon feed” all the materials. We should point them in the proper direction and mentor as needed so they develop the necessary skills to succeed.

For customers

When you work with a web professional, ask them if they have signed a code of ethics. Ask your teacher as well (if you are an aspiring web professional).

Best always,
Mark DuBois, Community Evangelist and Director of Education

The post WebProfessionals.org Code of Ethics appeared first on Web Professionals.

View full post on Web Professional Minute

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Slimming down the web: Remove code to fix things, don’t add the “clever” thing

Today we saw a new, interesting service called Does it work on Edge? which allows you to enter a URL, and get that URL rendered in Microsoft Edge. It also gives you a report in case there are issues with your HTML or CSS that are troublesome for Edge (much like Microsoft’s own service does). In most cases, this will be browser-specific code like prefixed CSS. All in all this is a great service, one of many that make our lives as developers very easy.

If you release something on the web, you get feedback. When I tweeted enthusiastically about the service, one of the answers was by @jlbruno, who was concerned about the form not being keyboard accessible.

The reason for this is simple: the form on the site itself is none insofar there is no submit button of any kind. The button in the page is a anchor pointing nowhere and the input element itself has a keypress event attached to it (even inline):

screenshot of the page source codeclick for bigger

There’s also another anchor that points nowhere that is a loading message with a display of none. Once you click the first one, this one gets a display of block and replaces the original link visually. This is great UX – telling you something is going on – but it only really works when I can see it. It also gives me a link element that does nothing.

Once the complaint got heard, the developers of the site took action and added an autofocus attribute to the input field, and proudly announcing that now the form is keyboard accessible.

Now, I am not having a go here at the developers of the site. I am more concerned that this is pretty much the state of web development we have right now:

  • The visual outcome of our tools is the most important aspect – make it look good across all platforms, no matter how.
  • As developers, we most likely are abled individuals with great computers and fast connections. Our machines execute JavaScript reliably and we use a trackpad or mouse.
  • When something goes wrong, we don’t analyse what the issue is, but instead we look for a tool that solves the issue for us – the fancier that tool is, the better

How can this be keyboard accessible?

In this case, the whole construct is far too complex for the job at hand. If you want to create something like this and make it accessible to keyboard and mouse users alike, the course of action is simple:

  • Use a form elment with an input element and a submit button

Use the REST URL of your service (which I very much assume this product has) as the action and re-render the page when it is done.

If you want to get fancy and not reload the page, but keep all in place assign a submit handler to the form element, call preventDefault() and do all the JS magic you want to do:

  • You can still have a keypress handler on the input element if you want to interact with the entries while they happen. If you look at the code on the page now, all it does is check for the enter button. Hitting the enter button in a form with a submit button or a button element submits the form – this whole code never has to be written, simply by understanding how forms work.
  • You can change the value of a submit button when the submit handler kicks in (or the innerHTML of the button) and make it inactive. This way you can show a loading message and you prevent duplicate form submissions

What’s wrong with autofocus?

Visually and functionally on a browser that was lucky enough to not encounter a JavaScript error until now, the autofocus solution does look like it does the job. However, what it does is shift the focus of the document to the input field once the page has loaded. A screenreader user thusly would never ever learn what the site is about as you skip the header and all the information. As the input element also lacks a label, there isn’t even any information as to what the user is supposed to enter here. You sent that user into a corner without any means of knowing what’s going on. Furthermore, keyboard users are primed and ready to start navigating around the page as soon as it loads. By hijacking the keyboard navigation and automatically sending it to your field you confuse people. Imagine pressing the TV listings button on a TV and instead it just sends you to the poodle grooming channel every time you do it.

The web is obese enough!

So here’s my plea in this: let’s break that pattern of working on the web. Our products don’t get better when we use fancier code. They get better when they are easier to use for everybody. The fascinating bit here is that by understanding how HTML works and what it does in browsers, we can avoid writing a lot of code that looks great but breaks very easily.

There is no shortage of articles lamenting how the web is too slow, too complex and too big on the wire compared to native apps. We can blame tools for that or we could do something about it. And maybe not looking for a readymade solution or the first result of Stackoverflow is the right way to do that.

Trust me, writing code for the web is much more rewarding when it is your code and you learned something while you implemented it.

Let’s stop adding more when doing the right thing is enough.

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Teaching people to think about code instead of acing a test

One of my biggest bugbears with education, learning and teaching – especially online – is the focus we have on testing people by giving them multiple choice questions or having them fill out a very specific and rigidly defined test. This is a remnant from school education, where it is important to compare pupils and to also make it easy to measure the success rate and effectiveness of the teacher. Overly simplified, our school systems are designed to create new professors, not people who use the knowledge elsewhere. Ken Robinson covered this nicely in his TED talk How schools kill creativity and Salman Khan (founder of Khan Academy) ran with it in his TED talk as well.

The problem with rigid tests is that they can be gamed. I knew quite a few students and interviewees who learned information by heart, aced tests and came out not remembering a single thing let alone being able to apply the knowledge in a different scenario. The learned the what, but not the why.

calvin finds a loophole in a test

Job interviewers make the mistake of having a fixed set of questions and then compare different applicants by how they fared. This is not only boring for the interviewer, it also doesn’t tell you much about how the person you interview ticks. And in the end you want to work with that person, see them grow and apply their problem solving skills in various different scenarios. At Yahoo we had a great way of doing this – we gave people a code exercise that encompassed creating a small web site from a photoshop comp. We told them what the thing should do and then let them decide how to approach it. We looked at the result they sent us and if it worked nicely, we invited them to an interview where the first half hour or hour was them explaining to us why they approached solving the problem in a certain way, what their frustrations were, and how they cut corners and why. We learned a lot about the people that way, because programmers who can explain what they did are people who can code.

This is why I am very happy to see that some people are creative enough to approach teaching to code differently than others. There are quite a few new resources out there that teach coding by describing problems and asking the learner to write code that then gets validated in a worker thread (in the case of JavaScript). Code Combat for example is a beautiful product using that approach.

Yesterday I was super happy to see that Mozillian Brian Bondy who took in onto himself to create a series of videos explaining how to contribute to Firefox at codefirefox.com added a series of small coding exercises to this endeavour.

Instead of telling you to “create variable a and assign the value foo to it as a string” the exercises on codefirefox.com are task descriptions like

Create a new variable declaration and initialize it with a literal value in one statement.

This teaches you the lingo (you might have to look it up to understand the question but you now what a declaration is afterwards) and allows you to choose what you want to do. You creatively code instead of answering a question. There is a text editor embedded in the page that analyses what you do and if you manage to get a task done, ticks it off for you. All you do is code instead of following yet another “next lesson” button navigation.

Even better is that Brian released the framework that allows you to create tests like that. Under the hood it uses Acorn by Marijn Haverbeke in a web worker to analyse the code and test it against assertions you defined in a simple API.

var c = new Codec();
c.addAssertion("x = 3;");
c.addAssertion("x++", { blacklist: true, otherProps: "hi" });
c.parseSample("if (x) { x = 3; }", function(err) {
  console.log('whitelist hit? ' + c.assertions[0].hit);
  console.log('blacklist hit? ' + c.assertions[1].hit);
});

The codefirefox exercise module code is available on GitHub.

I am very excited about this and hope that some people will take this on. Brian is doing a great job with this and more is to come.

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Protecting your Firefox OS App code

One question we get asked quite often about developing web applications using HTML5, CSS3, and JavaScript, is about how to conceal code. Reasons range from preventing cheating, protecting intellectual property, hiding encryption algorithms and others. Since JavaScript is executed on the client side, even on Firefox OS, the users can get access the code if they have the skills and spend the time. But don’t get the wrong idea! Applications on Android, iOS and most mobile platforms can be reverse engineered with effort and the right tools.

We will present some measures that make it harder for copycats to reveal your application’s code. In various degrees they will increase the effort, skills and tools required to get the code.

Compressing your code

This is the starting point for most developers. Compressing your code reduces the file size by removing what the browser doesn’t need to run your application. It starts by stripping comments and unnecessary white space. This is a good first step as comments usually reveal a lot of information on how the code is working.

The next level is shortening names of local variables and functions, the so called mangling. As this removes the meaning on those symbols, it further reduces readability.

More advanced compression tools, like UglifyJS, will actually parse your JavaScript to analyze and transform it. This allows not just renaming local symbols but also rewriting conditions and loops into shorter expressions, joining variable declarations (hoisting) and removing unreachable code. The resulting file is not only smaller and less readable but in many cases also faster.

You can take this one step further with the Google Closure optimizer in Advanced mode. The tool allows settings for all the aforementioned transformations. Advanced mode is the most aggressive and requires greater consideration when used, to ensure that the output runs just as the input. It will rename, inline and even remove functions, properties and variables, so you need to make sure to either reference all symbols correctly or annotate them. The extra work pays off as the result is highly compressed and even gains a performance boost. As an example, let’s see what can happen to this code:

document.onload = function() {
  var shareImage = document.querySelector("#share-image");
 
  function share() {
    var imgToShare = document.querySelector("#image-to-share");
 
    if (!imgToShare.naturalWidth) {
      alert("Image failed to load, can't be shared");
      return;
    }
 
    // Create dummy canvas
    var blobCanvas = document.createElement("canvas");
    blobCanvas.width = imgToShare.width;
    blobCanvas.height = imgToShare.height;
 
    // Get context and draw image
    var blobCanvasContext = blobCanvas.getContext("2d");
    blobCanvasContext.drawImage(imgToShare, 0, 0);
 
    // Export to blob and share through a Web Activitiy
    blobCanvas.toBlob(function (blob) {
      var sharingImage = new MozActivity({
        name: "share",
        data: {
          type: "image/*",
          number: 1,
          blobs: [blob]
        }
      });
    });
  };
  shareImage.onclick = share;
};

Once we’ll run this code through Google Closure, the code will look like:

var b=document.querySelector("#share-image"),        
c=document.querySelector("#image-to-share");b&&c&&       
(b.onclick=function(){if(0<c.naturalWidth){      
var a=document.createElement("canvas");a.width=c.width;     
a.height=c.height;a.getContext("2d").drawImage(c,0,0);       
a.c(function(a){new MozActivity({name:"share",       
data:{type:"image/*",b:1,a:[a]}})})}         
else alert("Image failed to load, can't be shared")});

Of course, the further you are writing custom logic, the more the code will be obfuscated, as the tools cannot change names from reserved word, or core functions. There are many tools online, and you can choose the one that fit your need. Most web frameworks offer interchangeable libraries and build steps that bundle and compress your JavaScript sources. For smaller projects your IDE, like Sublime Text, can be extended with packages available.

Using Emscripten

Did you remember that we said JavaScript is interpreted code? Well, you can bend that rule. Mozilla’s Emscripten tool compiles C and C++ to JavaScript. The output isn’t JavaScript as you know it. It behaves more like native code and manages its own memory (stack and heap) in pre-allocated typed arrays. This reduces garbage collection and makes inspecting the memory harder. The output also benefits from asm.js, a highly optimizable subset of JS, that runs on all modern browsers. If you are moving your app from native to the web you can just convert your existing libraries. But even if that doesn’t apply, moving your protected code into a C/C++ library that you compile to JavaScript is the best option to get blazing performance with the added benefits of obfuscation.

Using a web service

Compression and compilation isn’t the safest solution as people still have access to your code: it’s just a bit harder to understand the logic. On the other side, one technique that moves the code to a place you have more control over is to use a web service. Your secret logic would run as a server-side script that your application will call when needed. Someone might be able to inspect the in- and outgoing data but there is no way they will be able to view your logic without access to your server. The major downside is that this feature will be only available when the user is online.

Let’s see a simple example on how you can achieve this with a Firefox OS app, and a Node.js script: let’s say we would like to hide our super exceptional fantastic code to do the addition to two numbers. Here is a simple node.js script (the goal is not to teach node.js, but show you a working basic example):

"use strict";
var express = require('express');
var app = express();
 
// Set up express to parse body
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
 
// Only one route for web service
app.post('/', function(req, res) {
    // Convert parameters from request body
  var firstNumber = parseInt(req.body.firstNumber, 10);
  var secondNumber = parseInt(req.body.secondNumber, 10);
 
  if (isNaN(firstNumber) || isNaN(secondNumber)) {
      // Bad request, fail with 400 status
      return req.send(400);
  }
 
  var result = firstNumber + secondNumber;
  res.send({'result': result});
});
 
app.listen(8000);

Now in your app, you’ll call this script by sending the values you want to add, and the script will return you the result. Of course, users can see the call you make, and the results you’ll get, but they won’t be able to see the magic behind the hidden function.

"use strict";
var firstNumber = 4;
var secondNumber = 5;
 
var data = new FormData();
data.append("firstNumber", firstNumber);
data.append("secondNumber", secondNumber);
 
var xhr = new XMLHttpRequest({mozSystem: true});
xhr.open("POST", "http://fharper-nodejs.nodejitsu.com", true);
 
xhr.onload = function() {
    // Parse the response and do something with it
    var response = JSON.parse(xhr.response);
    console.log(response.result);
};
 
xhr.onerror = function() {
    console.log("Magic failed");
};
 
xhr.send(data);

This code is just showing the web service pattern and not best practices. As any server, it still needs security measures to prevent exploits. Make sure you mask the request and response data by using a secure HTTPS connection. Control client access to your service by checking the Referrer and Origin HTTP headers but don’t trust what you see as they can be faked. You can limit replaying request with malicious parameters by using adding a secret time-limited or single-use token. As you can see, having your code in a web service is keeping it off the client but opens different attack vectors you need to consider.

Be proactive

Choose the technology you want: you will make it harder to copy your code, but there is never a way to hide your idea. You need to be proactive: you need to be one of the best in your domain. Show your expertise, innovate, add features faster than the competitor do, be relevant for your market, and believe in what you do. How many knock offs of Angry Birds can you find on the web or on any marketplace/store? I don’t have the exact number, but I can definitely say with a lot of confidence, that it’s many! Rovio had an amazing idea, and they were the first to make it a reality: they are always innovating with brand new levels, new games with the characters we like, and more. You, your children, myself, we want to play to the original one, not the copy. Replace Angry Birds with any app or games you like, and you’ll understand what I mean.

You have access to an amazing platform that open the web like never before: take advantage of it, build that app you want, and make your idea a reality!

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)