Networking, sockets, and UDP Streaming fun! Part II


Yesterday, in my arrogance I spoke about some old UDP audio streaming logic I found online yesterday. I suggested that I could see where the choppiness problems were and fix them. Today I couldn’t help myself. I dove in and ran the code between two Mac computers to hear how it sounded. I was amazed that the code worked at all without any modification! Hi, I’m Cliff. You’re here because you wanna hear how it sounds to break your voice up into tiny little ones and zeroes on one device then reassemble them on another. I’m here because I’m just fortunate enough to be able to do this task. Picking up from yesterday I can proudly announce that I have indeed solved the mystery of choppy audio! It took about 20-30 minutes of copyin/pasting the original code and tweaking it to sound natural. My goal is to give you the answer to the mysterious choppy problem but…! Before I do so, let’s try to understand what the code is actually doing. There are two components, a server and a client.

The Server
We’ll Look first at the server. It starts off in the main() method and prints information about the audio system’s connected devices to the console.

    Mixer.Info minfo[] = AudioSystem.getMixerInfo() ;
    for( int i = 0 ; i < minfo.length ; i++ )
    {
     System.out.println( minfo[i] ) ;    
    }

It then looks to see if the Microphone audio line is supported before proceeding.

if (AudioSystem.isLineSupported(Port.Info.MICROPHONE))

This code merely detects whether there is any sort of “microphone-like” input attached to the computer.

It then opens a target data line for the microphone and starts it.

      DataLine.Info dataLineInfo = new DataLine.Info( TargetDataLine.class , getAudioFormat() ) ;
      TargetDataLine targetDataLine = (TargetDataLine)AudioSystem.getLine( dataLineInfo  ) ;
      targetDataLine.open( getAudioFormat() );
      targetDataLine.start();

These API calls [above] create a special DataLine.Info object instance which describes the format of the audio we wish to capture from the microphone. We call a getAudioFormat() method where the details of the audio format are encoded and returned in a special AudioFormat object instance. Without going into too much detail, understand that audio can come in many shapes and sizes depending on if you want stereo, mono, high fidelity or whatever. The AudioFormat class models things such as sample rate sample size, number of channels, etc. The format is given to the DataLine.Info constructor which creates an instance that we pass to the AudioSystem API via the getLine() method. At this point we have a connection to the microphone which we can open() and start() to capture audio samples.

How Audio works
For those of you who are very green to programming and/or audio I’ll explain briefly how audio, or sound in general works in computer systems. This all may seem pretty complicated but audio is one of the simplest concepts you can learn and is actually pretty cool when you understand it’s basic building blocks. Sound is merely the vibration of matter which our ears detect using little tiny hairs. The speed of the vibration makes the different noises that we hear. The vibrations come in various wave forms with different frequencies. Computers record and create sound using a process called digitalization. This is where frequencies, which are analog in nature, are converted to and from digits. It captures digital audio by using a microphone which is a piece of hardware that measures vibrations, or wave forms in the air. It takes a series of samples of the intensity of the wave at specific intervals and it creates or synthesizes audio by sending recorded samples to a speaker which includes a paper cone that vibrates based on the size of the digits in the sample. In short, the bigger the digits are in the sample the more intense the paper cone vibrates. You can think of the digits 16 as causing a small vibration where the digits 128 would cause a much more intense vibration of the paper cone inside the speaker. If a bunch of samples are sent quickly to cone the vibrations happen quickly, if they are sent slowly then the vibrations occur slowly. The combination of the speed and intensity of the vibrations of the paper creates noise or sound that we hear. I’m over-simplifying and glossing over a lot but that is the basics of sound. The samples and sample speed are the key to sound!

Going back to our example, the guts of our server are below:

      byte tempBuffer[] = new byte[1000] ;
      int cnt = 0 ;
      while( true )
      {
      targetDataLine.read( tempBuffer , 0 , tempBuffer.length );
      sendThruUDP( tempBuffer ) ;
      }

Here we see a byte buffer is created (with a strange not-round length of 1000 instead of 1024) and we enter a loop where we continually pass the buffer between two methods, targetDataLine.read() and sendThruUDP(). The first method reads a block of samples from the microphone, which (as described above) measures the vibrations in the air and writes these samples to the buffer. The second method sends the buffer of samples over UDP to the client.

The Client
We’ll now turn our attention over to the client. The client is a RadioReceiver which extend Thread. As it turns out, this is unnecessary complexity as there is no work being done other than playing back the captured audio samples. We can safely ignore the Thread part and pay attention to the code inside of the run method, which is invoked indirectly by the call to r.start() in the main method below.

    public static void main(String[] args) {
  
    RadioReceiver r = new RadioReceiver() ;
    r.start() ;
  
    }

The run method below declares a byte array which is used in a while loop. Inside the while loop we load the byte array variable with the result from the receiveThruUDP() method. This method attempts to capture sample data sent over the network and return it to the caller. In short the byte array is loaded with the samples captured from the network which were originally captured and sent from the server. We then pass the array of samples to a method called toSpeaker. This method eventually hands the samples to a Java API called SourceDataLine.write(). This Java API will eventually send the samples to the speaker which causes the paper cone to vibrate and recreate the sound on the client. See the run snippet below:

    public void run()
    {
        byte b[] = null ;
        while( true )
        {
           b = receiveThruUDP() ; 
           toSpeaker( b ) ;
        }        
    }

That’s the basics of how the whole operation works. There’s not a terribly large amount of code and I haven’t described the UDP networking pieces at all. I’ll continue this series explaining UDP next. in the mean time, keep looking to see if you too can figure out where things are slowing, **ahem**, chopping up. Keep in mind how I explained the key components of audio, sample intensity and the frequency, or speed of the samples.

Networking, sockets, and UDP Streaming fun!


I’ve been tinkering with robotics lately and itching to put a camera on my Bluebot so I can watch it from my wristwatch as I drive it around. That got me looking for info on how to stream video from one device to another. Hi, I’m Cliff. You’re here because you probably want to have a device spew data out into the sky then receive it from another device using a UDP network connection. I had done UDP video streaming about 4-5 years ago as a prototype for my wife’s salon business and that time I got extremely lucky. She wanted a way to stream video from a webcam over the internet and I didn’t know where to start. I went low level and wrote a UDP video client/server in Java. I’ve since lost the code but it wasn’t good code. (It was a dirty hack where I was exceeding the practical size for each packet… and I don’t think the UDP stuff even worked. I think I converted to TCP at the last minute! There was a time limit for my experiment and I came in literally one second before time was up!)

Flash forward to today where I again have the need to stream video over the network. I found an old abandoned post on a Java forum where someone wrote a choppy Audio UDP client server. I don’t know why but I think this example, as crude as it is, looks pretty cool! The guy who posted the code wanted to know why the audio sounds so choppy. I looked at the code and found the problem in about 30 seconds without compiling, or even trying to run and listen to it! The problem is obvious, so I’m going to post the code here for you to read and ponder. I’ll try to work through a solution in my free time.

The server below attempts to record audio from the microphone and stream it via UDP to a client.

The Server:

public class MicPlayer {
 
    private static final String IP_TO_STREAM_TO   = "localhost" ;
    private static final int PORT_TO_STREAM_TO     = 8888 ;
 
    /** Creates a new instance of MicPlayer */
    public MicPlayer() {
 
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    Mixer.Info minfo[] = AudioSystem.getMixerInfo() ;
    for( int i = 0 ; i < minfo.length ; i++ )
    {
     System.out.println( minfo[i] ) ;    
    }
 
 
    if (AudioSystem.isLineSupported(Port.Info.MICROPHONE)) {
    try {
 
 
      DataLine.Info dataLineInfo = new DataLine.Info( TargetDataLine.class , getAudioFormat() ) ;
      TargetDataLine targetDataLine = (TargetDataLine)AudioSystem.getLine( dataLineInfo  ) ;
      targetDataLine.open( getAudioFormat() );
      targetDataLine.start();
      byte tempBuffer[] = new byte[1000] ;
      int cnt = 0 ;
      while( true )
      {
      targetDataLine.read( tempBuffer , 0 , tempBuffer.length );
      sendThruUDP( tempBuffer ) ;
      }
 
    }
    catch(Exception e )
    {
    System.out.println(" not correct " ) ;
    System.exit(0) ;
    }
    }
 
 
 
    }
 
 
    public static AudioFormat getAudioFormat(){
    float sampleRate = 8000.0F;
    //8000,11025,16000,22050,44100
    int sampleSizeInBits = 16;
    //8,16
    int channels = 1;
    //1,2
    boolean signed = true;
    //true,false
    boolean bigEndian = false;
    //true,false
    return new AudioFormat( sampleRate, sampleSizeInBits, channels, signed, bigEndian );
    }
 
 
    public static void sendThruUDP( byte soundpacket[] )
    {
       try
       {
       DatagramSocket sock = new DatagramSocket() ; 
       sock.send( new DatagramPacket( soundpacket , soundpacket.length , InetAddress.getByName( IP_TO_STREAM_TO ) , PORT_TO_STREAM_TO ) ) ; 
       sock.close() ;
       }
       catch( Exception e )
       {
       e.printStackTrace() ;
       System.out.println(" Unable to send soundpacket using UDP " ) ;   
       }
 
    }
 
 
}

The client below attempts to receive the UDP packets and push them into the speakers for output:

The client:

public class RadioReceiver extends Thread {
 
    private static final String IP_TO_STREAM_TO   = "localhost" ;
    private static final int PORT_TO_STREAM_TO     = 8888 ;
 
    /** Creates a new instance of RadioReceiver */
    public RadioReceiver() {
    }
 
    public void run()
    {
        byte b[] = null ;
        while( true )
        {
           b = receiveThruUDP() ; 
           toSpeaker( b ) ;
        }        
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
 
    RadioReceiver r = new RadioReceiver() ;
    r.start() ;
 
    }
 
 
    public static byte[] receiveThruUDP()
    {
       try
       {
       DatagramSocket sock = new DatagramSocket(PORT_TO_STREAM_TO) ; 
       byte soundpacket[] = new byte[1000] ;
       DatagramPacket datagram = new DatagramPacket( soundpacket , soundpacket.length , InetAddress.getByName( IP_TO_STREAM_TO ) , PORT_TO_STREAM_TO ) ;
       sock.receive( datagram ) ; 
       sock.close() ;
       return datagram.getData() ; // soundpacket ;
       }
       catch( Exception e )
       {
       System.out.println(" Unable to send soundpacket using UDP " ) ;   
       return null ;
       } 
 
    }
 
 
     public static void toSpeaker( byte soundbytes[] )
     {
 
      try{  
      DataLine.Info dataLineInfo = new DataLine.Info( SourceDataLine.class , getAudioFormat() ) ;
      SourceDataLine sourceDataLine = (SourceDataLine)AudioSystem.getLine( dataLineInfo );
      sourceDataLine.open( getAudioFormat() ) ;
      sourceDataLine.start();
      int cnt = 0;
      sourceDataLine.write( soundbytes , 0, soundbytes.length );
      sourceDataLine.drain() ;
      sourceDataLine.close() ;
      }
      catch(Exception e )
      {
      System.out.println("not working in speakers " ) ;
      }
 
    }
 
 
    public static AudioFormat getAudioFormat()
    {
    float sampleRate = 8000.0F;
    //8000,11025,16000,22050,44100
    int sampleSizeInBits = 16;
    //8,16
    int channels = 1;
    //1,2
    boolean signed = true;
    //true,false
    boolean bigEndian = false;
    //true,false
    return new AudioFormat( sampleRate, sampleSizeInBits, channels, signed, bigEndian );
    }
 
 
}

Again, the complaint was that the audio sounds choppy and nobody on the abandoned thread could answer why. I wish there wasn’t a registration for posting because I so want to answer the obvious but I don’t want to fill out my email and register a user name and etc. Can you see where the problem is? I may be getting ahead of myself so I should actually see if the code compiles and works at all!

Open Source – How can I be down?


You recently downloaded a library from NPM but you’re not satisfied. You want to be like the cool cats from Silicon Valley. Hearing all the buzz about git forks, pull requests, commits and rebasing has you feeling left out. Maybe you were sitting at lunch with some coworkers and watching them buzz about sending a bug fix into MongoDB or maybe you just felt you really should try your hand at fixing a small bug but where do you start? How do you get down? Hi, I’m Cliff. You’re here because you don’t know if you fit in with the open source hype since you’re just starting your coding story. I’m here to tell you that you might already be an open source contributor without even knowing it. Getting involved is a lot easier than you think. If you haven’t seen my earlier post on open source give it a read as it explains exactly how to donate a small piece of code to an unsuspecting victim.

Let’s talk about what it means to contribute to open source. The sneaky not so often discussed truth is that if you have a Bitbucket or Github account and any snippet of code uploaded to it then you are already an open source contributor! The mere act of uploading source code to a public service like github is what open source is all about. You might not feel like Linus Torvalds but that’s because your project(s) have not amassed a heavy following. The simple action of uploading code to Github opens that source code up to the public and anyone else with a Github account can then improve on it. Improvements can be given via Facebook, Twitter, email, a phone call, etc. They do not have to come in a formal Github fork, push, pull request. When you send an improvement you are contributing to the project. If you need help working through some code that you have uploaded to Github or Bitbucket you can place a phone call to someone who has experience and they can download your code, run it and make suggestions. The barrier to entry is really just that low!

Let’s talk about contribution a little more. One of the bigger intimidating factors with open source is not knowing how to jump into somebody else’s project and add value. Let’s face it, if most people were to clone a major project like the Ruby compiler or even gulp, or JQuery they would get lost! However, if you paired with someone at your same level with not much source hanging on Github you might find a pleasant surprise! In my earlier post I found such a project to demonstrate how simple it is to get involved. The focus was on any individual who wanted to start collaborate on another project. This time around I want to explain how it feels when others collaborate on your project. The beauty of git based projects is that they are bi-directional. That means contributions can flow in both directions.

Let’s revisit the tipcalc project. I originally found a small improvement I could make then sent a pull request to the unsuspecting developer. I’ll frame a story around the way open source would work in the real world. Now suppose I was using that project as part of my own larger project. For example, if I were to host the tipcalc on a web host from within a public NodeJS express app and I wasn’t as familiar with the front-end HTML development work. I have a copy or fork of the original project and I could create an entire backend to serve the page. Over time the original developer, after accepting my earlier commit would have finished the project adding the ability to split checks and changing the look and feel of the page.

What if she were to help me enhance my site? She could contribute her updates back to me in the form of a pull request following the same steps I listed in my first article. I would then navigate to my fork of the project in github and notice an incoming pull request.
pull-request-notification
I could click on the pull request tab and see a summary of what she is trying to contribute. Clicking the actual pull request would give me a detailed list of the individual updates (or git commits) that were made since I last copied the project as well as a big green button to merge the updates into my forked copy of the project.
view-pull-request
merge-pull-request
There’s an indicator that let’s me know if the pull request can be merged without conflicts and a section to add comments to the pull request. I would use the comment section to give feed back to the contributor and/or say thanks for collaborating with me.

As you can see it is quite simple to accept changes in this basic case. Of course I have simplified this most basic case and there is more to sharing code and merging others work. I am merely attempting to clarify the overall workflow and demonstrate how low the bar to entry can be for newcomers. It’s always a good idea to pair with someone at your same level so you both could learn to collaborate with git together. In my case I felt obligated to pick on someone I knew had been working diligently with a very clean source base and easy to follow project. There are other such examples out there and the more you share the more others may share with you.

Getting into open source


“I sho’ would like to contribute to open source, but I suck at git! I mean who has time to cherry-pull a request? How do I append my commits?” Does this sound like you? Are you enthusiastically intimidated by the vast wall of Hi, I’m Cliff. You’re here because you want to “cherry-pull” your github thing-uh-muh-whats-it. I’m here because I used to feel the same way, intimidated by git and social coding. How do the experts do it? Why come I can’t do it? I wanna be cool like the kids in the bay area. Today I plan to show you a simple example using someone who is not yet aware that she will be my guinea pig. In case you are not aware, there’s an initiative circling the web called #100DaysOfCode where folks write code for 100 days straight and share their progress. I happen to be involved in a group of terrific #CodeNewbie people who are all doing the same. Many of them are early in their career and/or experience yet are extremely passionate about what they are doing. Each individual works their own Github repository. I chose to grab a random Github project from this group and submit the infamous Pull Request while explaining the process in its entirety.

The lucky winner of my random drawing, thus the guinea pig and recipient of my unsolicited assistance, is Angela Andrews (@ScooterPhoenix). Her repository is a rather interesting restaurant Tip Calculator where she is currently working on the details of splitting the check between guests. The code is relatively simple as it is early in the challenge. I’m going to assume only a passing familiarity with git and github in my article meaning you should have at least heard of Github and the git software while having a basic understanding of what it’s used for. With that understanding we begin, as anyone would begin in open source, by visiting the repository and perusing the Readme.

When starting your own Github project you would usually create a Readme as the first file added to your project. The Readme is a special file, usually having an “.md” extension, that is rendered when you first load the home page of a Github repository. It is a text file you can fill with details describing the project. You may use a special programming syntax called “mark-down” to format the text in any way you like, such as adding boldness to the font, colors, hyperlinks, images, etc. You can think of Mark-Down as a different kind of HTML. In my case I won’t need to create a readme. Instead I will collaborate with our unsuspecting participant by getting a copy of the repository under my Github account. We use the special term, “fork” to refer to a copy that someone obtains of of a git repository. I click on the “fork” button on the project’s home page to create this special copy under my account.
fork screenshot
github-forking-screenshot

Now I own a publicly visible copy of the original repository and can do whatever I please without damaging the original or upsetting the original project creator. The concept of ownership is important because I am now responsible for whatever changes I make to the source code. If someone finds my fork and decides to use it then they are obtaining the copy that I choose (or choose not) to maintain. If the original project owner decides to make further changes to the project then it is up to me to update my copy by pulling those new changes in. That does not mean that the entire project belongs to me, only that there is a potential for me to create an entirely new product based on the original idea. I will cover ownership in more detail later but the important thing to understand is that I have taken ownership of a copy of the project.

The Git Command Line Client
The next step is to download the source code to my development computer. I do this with special software called a git client. People often confuse the git client software with the github website because they both have git in the name and they both do similar things. The differences may not be obvious but it might help to understand that the “git client” is a set of programs that you run directly on your development computer while github.com is a web site that we all use to view and interact with open source repositories that have been uploaded by ourselves and others. The “git client” programs come in several different variations with the most popular and most intimidating being the git command line program. The git command line program enables you to run git commands from within another program (called a terminal or command program) and it requires a bit of understanding of how terminal programs and command lines work. There are other more newbie friendly git clients available, some of which have a Graphical User Interface (GUI) or are bundled as part of an IDE. (An IDE is a term that describes a program source code editor like Visual Studio, Xcode, or Eclipse.) I will use the git command line program to in today’s example so bear with me. (The details of downloading and installing a git command line program for your computer can be found here. Also note that the command line program comes bundled with a git GUI program.)

Cloning the repository
The act of cloning a git repository simply means copying the repository and all of its working files to your development computer. After forking the project I am taken to the forked copy under my account. If you blink you might miss this subtle but important detail because the page looks exactly like the original but it adds the detail of being associated with my personal github account. The URLs to the page and all the source code under it will all reflect my user account rather than the account the original project owner. I click green “Clone or download” button to find a special clone URL.

I open terminal on my Mac (on windows you would start the “command” program which can be found in your start menu), change my working directory to an empty one and run a git command to download or copy the source code from my fork: git clone https://github.com/cliff76/tipcalc.git
The special URL seen here is found on the webpage of my forked copy NOT the original. It’s important to understand that I am downloading and working from my forked copy rather than directly off the original because it is one of the strengths of git. It is also one of its more confusing aspects because many people are more familiar with the idea of working directly against an original set of files. Instead, you work with a downloaded copy of you forked copy of the original. That is a copy of a copy of the original! I stress this point because I’ve heard so many people express fear and doubts about destroying the original project which is actually pretty difficult to do. (That’s not to say it is impossible, just that it would need to be a pretty intentional action from both the project owner and the contributor.)

After the clone command completes you can feel free to examine the files that were copied to your development computer. The index.html file is usually the starting point for any web application and this one his no different. In my case, I open this file in my web browser (by double clicking the icon in Finder, my file explorer) and play with the app. After entering an amount in the total bill amount form field you can adjust the tip percentage by either clicking one of the options next to “Tip Percentage” or by sliding the “Tip Percentage” slider. The app works beautifully! While toying, I noticed that selecting one of the options does not automatically adjust the slider to the selected amount. Now I decide to put on my open source contributor hat and go to work! (You could do the same with many of these earlier Github projects!)

I open the HTML file in my favorite program editor (I always use IntelliJ Idea for everything but for some reason I decided to use TextMate2) and search for the fields I am interested in, the radio option buttons and the slider control. I notice that they each call a JavaScript function named “tipCalculate()” whenever you interact with them. I then look at the JavaScript file named “scripts.js”. I find the JavaScript function’s definition there and read through it. The function takes the tip percentage as a whole number as its parameter and the bill amount as it’s second parameter. It uses these two values to compute the tip amount. It then updates the tip amount next to the slider with the computed value.

Armed with this understanding, I would like to add the capability of adjusting the slider to reflect the tip amount when this function is finished. I could add a single line of code to set the value of the slider at the very end of the function but then I would have a situation where any attempt to manually change the slider’s value calls into this function which will automatically change the value of the slider which could trigger a call back into to the function which would change the slider which would call back into the function which would… you get the point? This is a common problem called recursion where a function creates some side effect that triggers a call back into the same function triggering the side effect and eventually causing a loop that never ends. Rather than fight with recursion I decide to create a new function named, “updateTip()” that does the EXACT same thing as the “tipCalculate()” function.

function tipCalculate (slider, bill){
    var tip = document.getElementById('tipamount');
    var total = document.getElementById('billAmount');
    var slideval = document.getElementById('slideval');
    var bill = parseInt(document.getElementById(bill).value);

    var prcnt = slider * .01;

  if (bill == null || bill == '') {
    tip.innerHTML = 'Please enter an amount';
    return false;
  }
  if(isNaN(bill)) {
    tip.innerHTML = 'Please enter a number';
    return false;
  }

  if(bill >= 0){
    tipToLeave = (bill * prcnt);
      tip.innerHTML = '$' + (bill * prcnt) .toFixed(2);
        slideval.innerHTML = slider + '%';
        total.innerHTML = '$' + (bill + tipToLeave).toFixed(2);
  }

}

function updateTip(slider, bill){
    var tip = document.getElementById('tipamount');
    var total = document.getElementById('billAmount');
    var slideval = document.getElementById('slideval');
    var bill = parseInt(document.getElementById(bill).value);

    var prcnt = slider * .01;

  if (bill == null || bill == '') {
    tip.innerHTML = 'Please enter an amount';
    return false;
  }
  if(isNaN(bill)) {
    tip.innerHTML = 'Please enter a number';
    return false;
  }

  if(bill >= 0){
    tipToLeave = (bill * prcnt);
      tip.innerHTML = '$' + (bill * prcnt) .toFixed(2);
        slideval.innerHTML = slider + '%';
        total.innerHTML = '$' + (bill + tipToLeave).toFixed(2);
  }

}

What that change I can open the index.html and call this function form the slider’s “onchange” attribute instead of calling “updateTip()”. I also need to give the slider an id so that I can locate it with the JavaScript function document.getElementById('slider'). The new code looks as follows:

<input id="slider" class="range-style" max="100" min="0" step="1" type="range" value="0" data-com="" />

Then I can add the one line at the end of “tipCalculate()” to set the value of the slider knowing that the slider itself will never call this function.

function tipCalculate (slider, bill){
    var tip = document.getElementById('tipamount');
    var total = document.getElementById('billAmount');
    var slideval = document.getElementById('slideval');
    var bill = parseInt(document.getElementById(bill).value);

    var prcnt = slider * .01;

  if (bill == null || bill == '') {
    tip.innerHTML = 'Please enter an amount';
    return false;
  }
  if(isNaN(bill)) {
    tip.innerHTML = 'Please enter a number';
    return false;
  }

  if(bill >= 0){
    tipToLeave = (bill * prcnt);
      tip.innerHTML = '$' + (bill * prcnt) .toFixed(2);
        slideval.innerHTML = slider + '%';
        total.innerHTML = '$' + (bill + tipToLeave).toFixed(2);
  }

  document.getElementById('slider').value = slider;
}

I test this by saving both the “index.html” file and the “scripts.js” file and refreshing my browser to load both files again. It works like a charm but I’m not happy! I have to functions that do almost the EXACT same thing because I copied all of the code from one function into the other. Copied code is a problem in any software project and I KNOW I can do better. Instead of copying the code I can call the new “updateTip()” function from the “tipCalculate()” function! That way if anyone ever needs to change the way it works changes only need to be made in one spot. The final code in “scripts.js” looks like so:

function tipCalculate (slider, bill){
	updateTip(slider, bill);
	document.getElementById('slider').value = slider;
}

function updateTip(slider, bill){
    var tip = document.getElementById('tipamount');
    var total = document.getElementById('billAmount');
    var slideval = document.getElementById('slideval');
    var bill = parseInt(document.getElementById(bill).value);

    var prcnt = slider * .01;

  if (bill == null || bill == '') {
    tip.innerHTML = 'Please enter an amount';
    return false;
  }
  if(isNaN(bill)) {
    tip.innerHTML = 'Please enter a number';
    return false;
  }

  if(bill >= 0){
    tipToLeave = (bill * prcnt);
      tip.innerHTML = '$' + (bill * prcnt) .toFixed(2);
        slideval.innerHTML = slider + '%';
        total.innerHTML = '$' + (bill + tipToLeave).toFixed(2);
  }

}

After testing the change and verifying my computer doesn’t decompose I commit the change! I use the terminal commands
git add . && git commit -m "Connects the slider's value to the radio buttons that set the percentage."
This is two commands, the first adds all of my changes to a staging area to be picked up by a commit and the second command performs the actual commit. A git commit records all of the changes you made to your local repository. Most newbies feel afraid or ashamed at this point because of fear of breaking the project and upsetting the owner or because of imposter syndrome. You want to commit all the time, it’s perfectly safe and highly recommended! Remember what I said above about working against a copy of a copy of the original? You WILL NOT BREAK THE ORIGINAL! (I promise!) Finally I run one more command,
git push origin master
This pushes the changes recorded in my local copy of the repository up to the forked copy under my github account. (I still have not broken or touched the original!) These changes will now be visible from github.com to anyone who visits my forked copy.

I am ready for the final part of my ritual! I am ready to tell Ms. Angela about my hard work! I hope she likes the change and does not decide to send the National Guard to my door or demand repentance! This final ritual comes in the form of a pull request! This is the magic art that all the cool kids in New York talk about all day. They’re all, “I did a PR on the Mahogany project but then project lead said I had to rebase my commits on top of the latest from develop and I was like fa reeeeaaaallllzzz???!!” And you’re all, “What’d he say? PR a wooden table and something about second base but who’s on 1st? I don’t know???”

The All Mighty Pull Request
The most difficult part of contributing to open source is now behind me and I am ready to explain the most exciting and beloved series of steps. Because my changes have been recorded on my development computer and then pushed to my personal account I can share them with the original author via a few mouse clicks. Furthermore, these changes can become part of the original just as easily. I visit github.com and view my forked copy of the project to find the “new pull request” button under the number of commits counter.
click-new-pull-request
Alternatively you can drill into the pull requests tab and create a new pull request from there.
click-pull-request Clicking that button gives you a screen with a big green create pull request button that you can click to create your first pull request. Simply fill in the comment box with details of what changes you made or why you would like your changes to be combined with the original project, click the green button and you’re off!
create-pull-request

#100DaysOfBullying – Coding by force?


I started this 100 days of coding challenge that has been going around the net recently. I’m not sure how/why I got roped in. (Actually, that’s not true… I have clear recollection. I was pressured into it by a dear friend who shall remain shameless!) The idea is that you write code for 100 days straight and network with friendly folks who are doing the same while sharing what you’re doing. Hi, I’m Cliff. I’m here because I was convinced (bullied) to participate in the challenge. You’re probably here because you’re new to coding and you want to be down with everything that’s going on. Now that introductions are over let me begin with a few disclaimers just in case you are unfamiliar with how I operate.

I’ll start by saying the challenge is a great idea and I am super excited to participate in it. Also I highly encourage you spread the word to others. I didn’t really understand what it was about at the beginning but now I’m involved and it’s a thrill. I have no hard feelings towards those who encouraged (harassed) me early on and if your life story resembles anything written here it is purely a coincidence. (Don’t message me with the, “how dare you make this sound like a bad idea?” I am all about the challenge and these is mostly just jokes, ok?) Even as much as I love the community and idea of social coding there is something that bothered me early on that I couldn’t put my finger on until now.

It wasn’t the way I got conned into participating. It wasn’t anything to do with the rules or the challenge at all. It was my inability to start. I honestly couldn’t figure out how I would participate or what I would do. I was trying to give the correct answer and I was coming up short. After various failed attempts at crafting the proper contribution and planning my perfect participation I finally just settled on doing what I do best, sitting and hacking together random code, libraries and APIs. It wasn’t until I stopped trying to plan my project that I was able to begin my project. It wasn’t until I stopped analyzing my approach that I was able to remember why I’m here in the first place! That desire to have the right answer was getting in the way of my ability to do the thing that was most important and it bothers me!

I hung out in the #CodeNewbie Twitter chat that same day when I saw the same desire several times in different community members. There was talk about, “I don’t have time” and questions like “where do I begin?” as well as people saying “I lack focus/direction”. All of this banter ignores the core driving factor behind the entire challenge, IT SHOULD JUST BE FUN! I never need to find time or a set of directions when playing my favorite video game and I always know where to begin. Why should the challenge be any different? At what point did we all stop enjoying ourselves and put on the responsibility garments of deadline driven politically correct practical software engineering and what do these garments have to do with the event?

I remember a time where I could just mash buttons on my keyboard without stressing over “a useable project”, “a deadline”, or “the right way to code a project”. It was a time when I would see something cool in an iSeriesNewsNetwork or JavaWorld article, type it into my terminal and tinker with this new thing without ever having any practical need or use case for it. It was a time when I would always have a tech book or magazine tucked under my arm and a time when I would dream of angle brackets stabbing me in the middle of the night. In these days I would merely discover stuff for no reason then there would just so happen to be a need for that discovery mere days later. It would sort of work like, “we have to update every Java class in this project with a VERSION string” and I would remember the trick I just read about using AntLR with the token rewrite engine a day prior. I would have experiences where someone needed a Excel spreadsheet converted to a web page from a non-Microsoft platform and I would draw from the blog post I read 2 nights earlier on the Apache POI project with stuff I got out of my XSLT Michael Kay red book then immediately cobble together some code that did exactly that. There were times when dabbling in random stuff like reverse ssh tunnels to get my Amarok music player running over a remote X11 session (with absolutely no audio) to show on my Mac would allow me to rescue a demo gone horribly wrong due to HTTP proxy issues.

My point is that I never wrote code to earn a paycheck. I never wrote code to meet a deadline. I never used to code for any objective other than the fact that I knew how to cobble together weird mis-matching technologies to make something work. Every project was never a project that was given from a manager. Instead it was a rehashing of an experience from only days prior where I was tinkering with some flashy thing on my Linux Beryl desktop trying to make it work & look like OS X or whatever. Everything I did originated out of a passion to play with computers. It was never planned, mandated or even organized. And now I find myself struggling to plan and organize something that felt mandated at first. It was not fun!

Some of the people chiming in on the Twitter chat sounded like they were setting themselves up for a work assignment. They sounded like they were forcing themselves to do the challenge because it would be somehow good for them. It is all wrong! It bothered me so much that I decided to write about it. What is supposed to be a passionate experience of 100 days spent coding is becoming 100 days spent bullying yourself to finish a project… Some of you are so focused on the end result that you’re robbing yourself of the entire experience.

Then I had all kinds of crazy questions and got to thinking the whole idea was wrong. I mean, why am I spending my time trying to complete a 100 day assignment? Do I plan to only code for 100 days? What happens on day 101? Will I no longer be an engineer? Will I suddenly turn blue, shrink to a 10th of my size and be on the lookout for Gargamel? Where would I find one of those noodle shaped stocking caps that bend forward slightly but never fall of the head? I code everyday professionally, shouldn’t I get credit for that? Who is collecting the credit? Can the credit be exchanged for an Xbox One when I’m finished? It got LL weird and Again, I overanalyze and missed the obvious!

Here’s a radical idea if you are taking the challenge and feeling lost or stuck. Don’t plan a coding project or do anything work related. Just break out your favorite IDE, programming language or framework and start tinkering. Don’t obsess over what the end result will be because that is not the point at all. I am in day 2 or 3 of the challenge and my project has a generic name and absolutely no purpose! I still don’t know what it does or will do, all I know is that I am having a blast tinkering with Azure, NodeJS, Express, Facebook and Twitter APIs. (I might even throw in some TypeScript and write my build system with Yarn!) For the first time in a long while I finally feel the way I did back in 2000-2005 when I would read my RPGIV programmer’s manual in the laundromat.

How to suck at programming #D – Build a terrible web experience


You have a home grown site devoted to delivering information. Maybe this information is news-like containing important product updates or company statuses and decisions. Maybe the information is more comical like attire articles bashing celebrities. Whatever the case, your site is rather important to people on the other side of the internet. These other-side people wish to download your content using the typical web browser. Hi, I’m Cliff. You’re here because you suck at programming. I’m here because I’m not much better. Together we can all learn how to build a decent web experience by example of what not to do. That’s the general idea. Now, back to our story.

Your site begins to trickle in visitors. First there are a few in your immediate LinkedIn or Google plus circle that know you. Then there are more stragglers arriving by word of mouth. You eventually reach what you deem to be critical mass of 75 unique visitors a day! Time to beautify and monetize! You investigate and research various JavaScript magic files that offer everything from Twitter integration to animated puppies that trample paw prints across the page content as they walk. You find things that feel plug and play giving you incoming traffic analysis and other files that embed ads from 3rd party vendors. You add two to a few then sprinkle four then more. Eventually you arrive at what you decide is the perfect pages. It demonstrates your site building prowess by integrating daily polls, half-screen popup ads that engage visitors with mini games because people get bored just reading the news don’t they? The occasional spider will lower itself from the top of the screen during Halloween covering 45% of the top article and scare the bejeezus out of people who are unexacting!

Your design was originated around the now defunct Opera core engine but you have since tweaked it to sort of work with WebKit and Safari. Still you spend most of your time using FireFox and you don’t even own a Mac so what’s the point? Mobile responsive design is out the window because nobody can enjoy your interactive mini-game popups on a smaller screen! Meanwhile your site continues to pickup traction as it gets Tweeted, re-Tweeted, and shared all across social media. Your visitors continue to increase as do the number of JavaScript widgets. More visitors must mean more interactive content is necessary, shouldn’t it?

The occasional visitor that arrives from a Facebook share on mobile is stuck as your main content, the article which was linked in the share appears beneath the fold which is primarily occupied by the awesome interactive Tide commercial which is bringing in a whopping $.05 per view and making the site un-scrollable as an unnoticed side effect. It takes over 1.5 minutes to load your top banner over mobile and half of your visitors close the page since they never even see the content they visit for rendering your stat counter pointless.

If you want suck at programming, ignore the principles of minimalistic and mobile responsive design and dazzle your visitors with interactive sorcery. You’ll accumulate page hits but nobody will ever know what your site has…

Evidence of TDD in the Bible (Eph 1:4 NLT)


I read a scripture this morning which shows clear evidence that God practices some form of Test Driven Design. Bear with me as it may sound non-obvious or one huge stretch. Just read Ephesians 1:4 NLT where it says:

Even before he made the world, God loved us and chose us in Christ to be holy and without fault in his eyes.

The key phrase is Before he made the world… That is before he wrote the code of humanity he chose us. Again, this may be counter-intuitive, but think about it. He chose us… he designed who we were to be before we existed. That is, he designed our outer interface or the blueprint for who we were to be in advance of implementing us. Y’all probably think I’m playing but I don’t kid around when it comes to scripture. This particular passage strikes me in a certain way as it’s the first I’ve read that clearly paints a connection from my faith to my coding practices. I’ve always known there was a pattern between what I study at church and the how I practice development but I couldn’t put my finger it. Then this passage jumps right out of the good book and describes the connection.

No long winded rant is necessary for tonight’s post, I believe the word says enough as it is written. Think about it.