How to scaffold JavaScript Web Application in seconds using YEOMAN ? (example with Backbone Marionette)

Hey guys,

Today I want to discuss an issue that I have been recently facing, and how to solve it.

The issue is:

How to set up a new JavaScript web app as quickly as possible and start developing, instead of worrying about dependencies and digging into configuration files trying to tie different libraries together ?

If you are a Rails developer, you will understand what I mean. In Rails you can scaffold your application and have a mockup that you can start building on in seconds. I haven’t been able to find such tool for JavaScript web apps… Until now…..

My colleague Tim showed me a tool today, that does the job for you.

The tool is called: YEOMAN .

YEOMAN uses 2 other tools for JavaScript that should be in a must-have list for any JavaScript Web Developer.

They are:

a. Grunt  – JavaScript task runner
b. Bower –  A package Manager for Web

The good thing is that to develop simple Web App with YEOMAN, you don’t even need to know how to use those tools, because YEOMAN does everything for you. However, I highly encourage you to read documentation for both tools, because they will make your JavaScript development SO MUCH EASIER!

Finally, after this long intro, let’s get to setting up our first JavaScript Backbone Marionette application using YEOMAN.

Before you start:

You need to have: Node.JS and NPM. To be honest, if you are planning to develop web apps – you will need them anyway.

You can find how to install Node.JS and NPM here .

When you have Node and NPM in place, you need to:

1. Install Bower and Grunt.  using NPM:

npm install -g grunt-cli
npm install -g bower

Tip: ‘-g’ in npm install makes element that you have installed  - global, so you just need to install it once, and use it  for multiple applications.

2. Install YEOMAN

npm -g install yo

3. Install YEOMAN generator for Marionette.JS

npm install -g generator-marionette

4. Install Mocha Generator that Marionette Generator uses:

npm install -g generator-mocha-amd

5. Create Web App Folder, Scaffold Marionette Application using YEOMAN Generator:

mkdir WebAppTest
cd WebAppTest
yo marionette

Expected output: (If you need any components I said no to, please put Y instead of ‘n’:

_-----_
 | |
 |--(o)--| .--------------------------.
 `---------´ | Welcome to Yeoman, |
 ( _´U`_ ) | ladies and gentlemen! |
 /___A___\ '__________________________'
 | ~ |
 __'.___.'__
 ´ ` |° ´ Y `
Out of the box I include HTML5 Boilerplate, jQuery, Backbone.js, Marionette, Handlebars, Require and Modernizr.
 [?] Would you like to install the full express app or simply the marionette generators? Yes
 [?] Would you like to include MongoDB for storage? No
 [?] Would you like to include Socket IO for real time communication? No
 [?] Would you like to include Baucis for REST? No
 [?] Where do you want the Bower components installed? (bower_components) ENTER

Note: this will take a while,  but in the end YEOMAN will create a web app, put all necessary dependences and even tests. Isn’t it amazing ?

6. Run your application:

grunt

This will load your browser and you will be able to see this screen:

Screen shot 2014-02-24 at 12.40.06 PM

So here you have your scaffolded Marionette application that includes Handlebars.JS templates and Unit tests.

Of course it doesn’t stop on Marionette, there are plenty of generators for YEOMAN allowing you to scaffold many web apps of your choice.

That’s it for today,

Try it and let me know how it goes!

Anatoly

Posted in Backbone.JS, Handlebars.JS, JavaScript, Marionette.JS, open-source, Programming Languages | Tagged , , , , , , , | 2 Comments

RAILS, HAML : How to put Checkbox and label on the same line, with translations

Hey guys!

Today I have decided to share with you little secret, that can save you quite some time, while writing templates with HAML.

While creating a form for one of the projects, I needed to put a checkbox within the same line as label and also I had to make my label a “translation”.

I googled and the closest which I was able to find was: http://stackoverflow.com/questions/9774555/nesting-ruby-on-rails-haml-checkbox-in-label-tag

However, It didn’t really solve my “translation” problem.

Initially my code looked like this:

= simple_form_line do
  = f.label t('.send_email')
  = f.check_box :send_email, class: "checkbox"

.send_email in this case is a translation from my eng.yml file which equals to “Send credentials to user by email”.

The code produced this output:

Image

However, what I needed my checkbox and message to be on the same line. This is how I was able to solve it:

= simple_form_line do<
  %label.checkbox{ :for => "send_email" }
    = f.check_box :send_email, class: "checkbox"
    = t(".send_email")

(Sorry if wordpress screwed indentation!!!)

And here is how output looks like:

Image

That’s it for today!

Have a wonderful day!

Regards,

Anatoly

Posted in Programming Languages, Rails | Tagged , , , , , | Leave a comment

How to make a contact form with Bootstrap 3 ? (JQuery/PHP/HTML5/JqBootstrapValidation)

Hey guys!

Today we will talk about such essential feature for any website as contact form. Recently, while working on one of the projects, I had a pleasure combining couple of very nice tools (Bootstrap 3 + JQuery + jqBootstrapValidation), which resulted in minimalistic , but powerful contact form, that would be a good addition to any website.

Contact me form

VIEW DEMO          CODE

In this post I will walk you through the process of developing this form. Also if you just want to put it in your website, just pulled from my github repo and have fun.

Sounds good ?

Let’s start.

When I was developing my form I had in mind following goals:

- Minimalistic design
- Track person’s contacts for future communication
- Send form information directly to my email
- Validate input – client side and server side
- Show success when form is sent, or provide alternative method if something went wrong

As you might see – nothing special. I would love if somebody else would provide me this solution yesterday, when I was working on my project – this could save me some time! :)

Let’s divide our workflow into sections:
- Required Libraries
- UI
- Client-side Validation, JQuery – PHP Interaction
- PHP (so called server side)

Required Libraries

We will require following libraries :
- Botostrap 3
-  jqBootstrapValidation

So all you need to do is just download necessary files and put them in.

After getting Bootstrap and jqBootstrapValidation our website tree will look like this:

-
- –  css
- – - bootstrap.min.css
- – js
- – - bootstrap.min.js
- – - jqBootstrapValidation.js

Let’s move to the UI part.

UI

For the UI we will use Bootstrap 3 and some attributes from jqBootstrapValidation.js . I won’t cover Bootstrap 3 components as it will take far too long, but if something is unclear, please shoot me an email and I will clarify that for you.

So in the root of our website we need to create file form.html .

Final version of /form.html will look like this:




Contact form for your site by Anatoly Spektor
  <!-- Bootstrap CSS -->
  	<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen" />


<!-- Contacts --></pre>
<div id="contacts">
<div class="row"><!-- Alignment -->
<div class="col-sm-offset-3 col-sm-6">
      <!-- Form itself -->
<form class="well" id="contactForm" name="sentMessage" novalidate="">Contact me
       <!-- Full Name -->
<div class="control-group">
<div class="controls">
	    <input class="form-control" id="name" type="text" placeholder="Full Name" required="" data-validation-required-message="Please enter your name" />

</div>
</div>
        <!-- Email -->
<div class="control-group">
<div class="controls">
		<input class="form-control" id="email" type="email" placeholder="Email" required="" data-validation-required-message="Please enter your email" /></div>
</div>
        <!--Message -->
<div class="control-group">
<div class="controls"></div>
</div>
<div id="success"></div>
 <!-- For success/fail messages -->
 <button class="btn btn-primary pull-right" type="submit">Send</button>

</form></div>
</div>
</div>
<pre>
 <!-- JS FILES -->

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><script type="text/javascript" src="./js/bootstrap.min.js"></script>
<script type="text/javascript" src="./js/jqBootstrapValidation.js"></script><script type="text/javascript" src="./js/contact_me.js"></script>




Sorry for this formatting, it’s hard to put code into WP, please find formatted version of form.html here

If you are familiar with Bootstrap – this code is pretty straightforward.

There are couple of important things I would like to point out:

  1. Since we are using jqBootstrapValidation, we need to put novalidate attribute into our form tag, otherwise HTML5 validation will clip jqBootstrapValidation validation.
  2. To change color/style of your error messages just change “.help-block” CSS class
  3. data-validation-* classes are used to specify custom message when user does something incorrectly. You can find more about those here.
  4. jqBootstrapValidation library looks at input and textarea tags and automatically puts validation if needed. For example if there is a “required” attribute, it automatically will put error message if the field is empty.

That’s all I can think of, if you have additional questions, please send me an email, or ask me in the comments below the post.

Client-side Validation, JQuery – PHP Interaction

So now we have finished the design of our form. Next step is to activate jqBootstrapValidation library, pass users data to PHP, which will send an email and finally show something to the user.

Most of these is done in one tiny JQuery function.

Here it is (file js/contact_me.js):

/*
  Jquery Validation using jqBootstrapValidation
   example is taken from jqBootstrapValidation docs
  */
$(function() {

 $("input,textarea").jqBootstrapValidation(
    {
     preventSubmit: true,
     submitError: function($form, event, errors) {
      // something to have when submit produces an error ?
      // Not decided if I need it yet
     },
     submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit haviour
       // get values from FORM
       var name = $("input#name").val();
       var email = $("input#email").val();
       var message = $("textarea#message").val();
        var firstName = name; // For Success/Failure Message
           // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
	   firstName = name.split(' ').slice(0, -1).join(' ');
         }
	 $.ajax({
                url: "./bin/contact_me.php",
            	type: "POST",
            	data: {name: name, email: email, message: message},
            	cache: false,
            	success: function() {
            	// Success message
            	   $('#success').html("</pre>
<div class="alert alert-success">");
 $('#success > .alert-success').html("<button class="close" type="button" data-dismiss="alert">×")
 .append( "</button>");
 $('#success > .alert-success')
 .append("<strong>Your message has been sent. </strong>");
 $('#success > .alert-success')
 .append('</div>
<pre>
');

 		  //clear all fields
 		  $('#contactForm').trigger("reset");
 	      },
 	   error: function() {
 		// Fail message
 		 $('#success').html("</pre>
<div class="alert alert-danger">");
 $('#success > .alert-danger').html("<button class="close" type="button" data-dismiss="alert">×")
 .append( "</button>");
 $('#success > .alert-danger').append("<strong>Sorry "+firstName+" it seems that my mail server is not responding...</strong> Could you please email me directly to <a href="'mailto:me@example.com?Subject=Message_Me">me@example.com</a> ? Sorry for the inconvenience!");
 $('#success > .alert-danger').append('</div>
<pre>
');
 		//clear all fields
 		$('#contactForm').trigger("reset");
 	    },
           })
         },
         filter: function() {
                   return $(this).is(":visible");
         },
       });

      $("a[data-toggle=\"tab\"]").click(function(e) {
                    e.preventDefault();
                    $(this).tab("show");
        });
  });

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
     $('#success').html('');
  });

For the most part I have took the function from jqBootstrapValidation examples. However, there are couple of things particularly interesting to us.

jqBootstrapValidation allows to overwrite submit on success behaviour, which I am doing in this case. If user submits everything without errors – I do a POST request to the file bin/contat_me.php with name, email and message.

File contact_me.php, which we will code in the next section, sends me an email with everything that user filled in. Also, I check If I am able to connect to this file, in this case I send back “Message sent successfully” to the user, otherwise I give an error telling user to email me directly ( use cases: for example if mail server is down, if validation on server side failed, if permissions to php file are incorrect etc) .

There is not much to add, but if you have any questions regarding this function do not hesitate to ask.

PHP (so called server side)

Finally, we got to the last piece of this puzzle. I have a php file that does some validation on the data received from form and sends me an email.

Here is my PHP file ( bin/contact_me.php )

<?php 
// check if fields passed are empty 

 if(empty($_POST['name'])   ||    
    empty($_POST['email'])  ||
    empty($_POST['message'])||   
    !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))    
  { 	
       echo "No arguments Provided!"; 	return false;    
  } 
	
  $name = $_POST['name']; 
  $email_address = $_POST['email']; 
  $message = $_POST['message']; 	 

 // create email body and send it	 
 $to = 'me@myprogrammingblog.com'; 
 // put your email 
 $email_subject = "Contact form submitted by:  $name"; $email_body = "You have received a new message. \n\n". 				  
                   " Here are the details:\n \nName: $name \n ". 				  
                   "Email: $email_address\n Message \n $message"; 
 $headers = "From: contacts@myprogrammingblog.com\n"; 
 $headers .= "Reply-To: $email_address";	 

 mail($to,$email_subject,$email_body,$headers); return true;			 
?>

As you might see my PHP file is even more simple. Of course you can add extra validation on top of it. For my use case I am just checking if fields are not empty and if email has correct format. If everything is correct, I create an email and use PHP’s mail function to email it.

That’s it.

You can find all these files here.

I hope this function will be useful for you!

Regards,

Anatoly

Update:

F.A.Q

(Thanks a lot to Corey Russell  for resolving some of the occurring issues)

Q:  I see “Sorry <Name> it seems that my mail server is not responding… Could you please email me directly to….”

A:  1. Go to line 26 of the contact_me.js file you have. There you’ll see the url for contact_me.php. Make sure that url is correct. I think by default it is pointing to a folder called bin.
2. If you try it from your desktop it won’t work as it doesn’t have a php server/client installed.

 

Posted in Bootstrap, HTML5, JavaScript, Jquery, open-source, Programming Languages | Tagged , , , , , | 86 Comments

How to find if a number is power 2 ? (Bitwise and Iterative) [Python Script]

As I have promised, I continue answering your questions.

One of the readers of myprogrammingblog.com wrote me an email asking How to find if a number is power 2 ? He also asked me to write a bitwise solution as well as an iterative  solution using Python. There are many examples of these kind of questions in the Internet, but I thought it would be nice to put one up here too,  since person asks.

Ok, here we go !

So first solution  is the bitwise one .

In this solution we will be using legendary bitwise operator AND (&). This solution is based on the unique property of all power 2 numbers having only one bit set to one and all other bits to zero. So number-1 will remove this one bit making expression equal to zero, if the number is power of two. You will notice that there is special case – number != 0 . If you put 0 into expression below, you will see that despite 0 being not power of two, expression will return true. So to eliminate special case, I just made sure that number is not zero.

Here is the function itself :

# Bitwise version
def powTwoBit(number):
  return (number & (number-1) == 0) and (number != 0)

Second solution is easier to understand if you are not a big fan of bitwise operations, since it uses regular looping and is based on the property that any number that is power of two has –  divisible by two without a remainder. So in this solution I loop and divide number by 2 until number is not equal to 1. If one of these divisions shows me that division produced a remainder, I know that number is not power of two. I also take into account special case – number must be positive.

#Iterative version
def powTwoIter(number):
	isPowOfTwo=True;
	while (number != 1 and number > 0):
		if(number%2):
			# can do return here as well
			isPowOfTwo = False
		number=number/2
	return isPowOfTwo and (number > 0)

So here they are – 2 solutions of how to find if a number is power of 2 in Python. I have put this code into myprogrammingblog.com github repo together with Unit Tests. So feel free to use it.

Of course there are many other solutions. For example you can create an array of power 2 values, sorted from least to greatest (the range that corresponds to the problem you are trying to solve) and use a binary search to find if your number corresponds to one of those in the array.

 Choose whatever works for you!

Regards,

Anatoly

Posted in open-source, Programming Languages, Python, Useful Functions | Tagged , , , , | Leave a comment

How to check if a number is ODD or Even ? [PHP function]

Hey guys!

Long time no seen! Today I had a pleasure of going over myprogrammingblog emails, where many users have asked me to show solutions to different problems. Sorry for not being able to respond earlier, as I had whole bunch of things going on.

From now on, at least for a month, I will be regularly (read as 1 time in 1-2 days) posting some code examples for the problems you have asked me to take a look at. By the way, if you have any interesting problems, which you would like to share with me, please email me at: myprogrammingblog@gmail.com .

Quick Update:

I have opened myprogrammingblog Git repo, where I will be posting code examples discussed in this blog.

Repo URL is :

https://github.com/myprogrammingblog/myprogrammingblog.com/

Now, back to business.

One of the readers ( I am not posting names/nicknames since some people don’t like to be addressed publicly) asked me:

How to check if a number is ODD or Even ?

To solve this problem I will use nice operator, available in most popular programming languages (e.g C/C++/Python/Java/PHP/JavaScript…you name it…) called modulo (%) .

Modulo – finds the remainder of the division.  That’s exactly what we need!

We know that EVEN numbers are those that can be equally (read without a remainder) divided into two groups. By using modulo we can check if the number divided by two does not have a remainder, than it is an EVEN number, otherwise it is ODD.

Bored already ? Here is the code (since no specific language was required, I have used PHP):

<?php

/*
 * Description:
*		This small function returns true if passed number
*                     is divisible by two, false if not.
*
* @author: Anatoly Spektor
*/
function isEven($number) {
	$isEven = false;
	if (is_numeric ($number)) {
		if ( $number % 2 == 0) $isEven = true;
	}
	return $isEven;
}

?>

In case you need Unit Tests for this function, they are available in the repo.

Thank you for sending me your questions!

Regards,

Anatoly

Posted in GitHub, open-source, PHP, Programming Languages, Useful Functions | Tagged , , , , , , , , | 3 Comments

Eclipse SWT drops GTK support of versions less than 2.10

Hey guys,

I have some very exciting news on the GTK-SWT front. Finally, SWT drops support for GTK versions older than 2.10, which means that we will have cleaner code.

I have started cleaning SWT from old GTK code, if you are interested how this work goes, you can follow it here.

Have a great weekend! ;)

Cheers,

Anatoly

Posted in Eclipse Development, Fedora, My Work, open-source, OS, Red Hat, RHEL, SWT | Tagged , , , , , , , | 2 Comments

SWT: Datetime Widget on top of Spinner [ Progress Report]

What is the problem with DateTime widget ?

Datetime is an SWT widget that shows DATE/TIME/CALENDAR, so overall very useful widget!

In current version of SWT  it looks like this:

datetime_old
So as you might have guessed DateTime  is a Composite of Text, Button with Arrow Up and Button  with Arrow Down. All this elements are separate widgets that are brought together to work synchronously at the time when widget is created. The problem is that creating a separate widget for every element and making all these widgets work together takes a lot of resources.

Also, If I use some weird GTK+ theme (Gnome-Cuepertino in screenshot) my Arrows on the buttons become invisible:

weired_theme

Finally, if we take a look at other widget with similar functionality (Spinner photo below) we may see that it has different buttons, so there is no consistency between widgets in SWT.

spinner_gtk2

Is there an alternative solution ?

One of the possible solutions that we (Red Hat Eclipse Team) have proposed is to use Spinner widget as a back-end for DateTime widget.

Why to use Spinner ?

1. It has 2 buttons and a Text area, and all this works together by single widget. (Less resources required)
2. Spinner buttons are part of the Spinner itself, so they won’t disappear if you change to some weird theme3. Spinner and DateTime will have similar look, which will create consistency

So the next question would be:

What was being done on this front ?

I have been working on  migrating the  DateTime widget to Spinner couple of months ago, but due a lot of other work that was supposed to be done and long review time, this work was put into a shelf. However recently, when most of the crucial work on GTK+ 3 was done, I have decided to come back to it, and some significant progress was achieved.

So here is the first look of how DateTime may look when running on top of Spinner:

Theme Adwaita (GTK+ 2):
datetime_newAs you might see it still has Text area and Buttons, but they act as a single widget this time. (less resources needed)

So if I try to look at the same widget using some weird GTK+ theme (again Gnome-Cuepertino), you still can see buttons:

weired_theme_new_Datetime

Finally if we take a  look at the  Spinner widget  next to DateTime widget:

one_next_to_spinnertwo_next_to_one_DateTime

You can see the consistency :)
I will continue working on it, and hopefully soon it will take its place in the SWT family.

I will keep you updated!

Regards,

Anatoly

Posted in Eclipse Development, Fedora, My Work, open-source, OS, Programming Languages, Red Hat, SWT | Tagged , , , , , , | 1 Comment