Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday, September 10, 2014

Object Orientation


Here's the audio version of this blog post:



These are objects
What is an object?  In real life, a lot of things are objects.  Plants, bicycles, cars, pets, bananas, thoughts, really anything!  Even people could be considered objects (bear with me here).  The question "what is an object" raises some philosophical issues, but it is clear that objects play a large role in our daily lives.

Because objects are so pervasive in our perception of the world, we can say we experience life in an object-oriented way.  For example, take the sentence "I'm going to the store".  Here, "I" refers to the person object that is going to the store.  The store could be interpreted as a destination object, which implies that there is also an origin object.  The subject of our example may plan on driving his car object to the store, or riding a bike object.  At the store, a person can buy food objects.

This example again raises the question, What is an object?
Let's define some criteria for object-ness:

  • An object must have characteristics
    • Tangible characteristics:
      • Color, size, weight, location
    • Non-tangible characteristics:
      • Emotions, personality traits, powered on, powered off
  • An object must have actions
    • Things that it can do or things that can be done to it
      • Run, walk, eat, drive
      • Power on, power off
      • Paint (change color)
      • Grow
  • An object must be identifiable
    • It must be a distinct entity
      • I can have two pens of the same model, but I still have two different pens
Notice how we never specified that an object must physically exist.  Our criteria for an object could include thoughts, conversations or mathematical formulas.

Because objects are so omnipresent in life and the human experience, things we create will reflect this object-oriented way of thinking.  Humans can easily think of problems in terms of objects, so we created many software tools to describe and interact with objects.  Programs that simulate icebergs melting or control aircraft scheduling patterns can be developed in an object-oriented way.

Not how it is
So, this means when we write most programs, it is easiest to write them in an object-oriented way.  This results in minimal effort on the programmer's part.  Well designed object-oriented programs read more like a description of the real world than arcane source code.









Alright, let's see some code.

class Pig:
    #definition for Pig object
    def __init__(self, weight, age, name):
        #a pig has weight (lbs), age (years) and a name
        
        #assigning parameters to pig object
        self.weight = weight
        self.age = age
        self.name = name
    
    def oink(self):
        print "Oink!"
        
    def sayHello(self):
        print "Hello, my name is " + self.name + "."

#make a new pig named Spider pig that weighs 40 lbs.
#and is 3 years old
SpiderPig = Pig(40, 3, "Spider Pig")

#make spider pig introduce himself
SpiderPig.sayHello()

#make spider pig oink
SpiderPig.oink()

Here's a link to an editable and runnable version of that example.

The programming language I used to write that example is called Python (named after Monty Python's Flying Circus).  If you want a more in-depth introduction, check out my blog posts Python Intro and Python Intro Part Deux.  I also wrote an introduction to Java, another object oriented programming language.

Tuesday, August 19, 2014

How to use OAuth with MEANJS

Nodejs logo
Hello, this is a short tutorial on how to use OAuth with meanjs.  It can be followed using another framework, but there are some mean-specific tips in here.  You probably do need node, though.







  • To use oauth with meanjs, you should find a library that has already implemented the handshaking for you (googleapis and Twit)
  • A note about OAuth 1 vs 2:
    • OAuth support is fragmented
    • Lots of node libraries support both
    • Not all services support 1 or 2
  • Note: if you plan on using user-based authentication along with application authentication, it is much easier to use the existing passport integration that meanjs already has in place
    • This makes obtaining session tokens much easier
  • Most often, these libraries will provide easy-to-use interfaces (APIs) where keys are passed as a config object
    • demoTwit.png
    • All you need to do is put in your keys where they are needed
  • To get access tokens, most of the time you need to create a new app
  • These instructions are pretty straightforward usually
  • The callback url can be found in config/env/development.js under the object whose service name you are using
  • Note: if you use a non-standard port on your app, you must specify that port in the callback url (127.0.0.1:3000/callback/)
  • A note on twitter’s api app creator:
    • For some reason, twitter doesn’t like localhost to be in the callback url, so you need to specify localhost using 127.0.0.1 eg
    • 127.0.0.1:3000/auth/twitter/callback
  • This will give you one or two application-specific tokens or secrets
    • These application-specific keys are used to authenticate your app
    • If you need per-user authentication as well, read on
  • To fill in the per-user authentication tokens, you need to interface with passport and the existing meanjs framework for these things
    • These session keys can be obtained from the user object after authenticating eg
var providerData = req.user.providerData || req.user._doc.additionalProvidersData.twitter;

   var T = new Twit({
       consumer_key: config.twitter.clientID,
       consumer_secret: config.twitter.clientSecret,
       access_token: providerData.token,
       access_token_secret: providerData.tokenSecret
   });

  • The branch googleApiDemo of my fork of extra-mean has a demo of something like this, feel free to use it as an example
  • Any questions?  Leave a comment or email me at macsj200@gmail.com

Wednesday, October 30, 2013

My github projects

I've been working on some github projects lately.  You should check them out at http://github.com/macsj200.

Friday, September 6, 2013

Intro to Java

A while ago, I wrote a series of Java tutorials.


To see the rest of the tutorials, navigate to https://drive.google.com/#folders/0B11WQbRQEj5FREllbmJoX2VGaEk.

Python Intro

repl.it
So you've finally decided you want to learn to program.  Or maybe you know how to program but you want to learn Python.  In either case, this tutorial is for you!  This is for complete Python beginners.



Python logo
Before you can write and use any Python, you need to find an application that will run your code.  For expediency's sake I will skip over installing and running Python natively; we'll use repl.it (a free online interpreter) instead.  This guide is written for Python 2, so if you have Python 3 installed just use repl.it.  Navigate to repl.it, click the languages button (the leftmost button in the top right corner of the screen) and set it to Python, then click anywhere in the area of the screen on the right side with the blue background.  Now let's write some code!

To start off, type:
print "Hello world!"
and press Enter.

You should see this:






You just added to a 41 year old tradition and wrote your first Python program!  Well done.
The "Hello World" example illustrates the usage of Python's print statement.  To print a string (a collection of zero or more characters delineated by quotation marks, like "Yolo swag", "hello", "5.24" or "D"), type print followed by the phrase you wish to print enclosed in quotation marks.  Here are some more examples of print:
print "Size matters not - Yoda"
print 42
print "It's a great day to be alive!"
Play around with the interpreter.  See what works and what doesn't.  Try printing numbers, fractions or punctuation.  Try using single quotation marks on strings.

Python (like every other good programming language) lets us save values to variables for later use.  Think of a variable like a box.  A box can hold books, toys or video games and a variable can hold strings, integers and doubles (plus much more).  To save a value to a variable, type a variable name followed by an equals sign (=) followed by the value you wish to save.  For example:
x = 42
Now the variable x holds the value 42.  We can verify this by printing x:
x = 42
print x
You can print variables in much the same way that you can print numbers or strings.  Try the above example, then play around with the interpreter.  Here are some more examples to help you get the hang of the syntax:
the_answer = 42
price = 1.95
userName = "macsj200"
x = price
elephant_name = "Dumbo"
Try setting x to a different string, or a number.  Try creating other variables.  Try setting x equal to another variable.  Try printing variables before you create them.  Use the print statement to see the results of your actions.

Python variables must start with a letter and be only one word, but other than that name then whatever you want.  It is a good idea to get into the habit of giving your variables meaningful names, like speed or priceOfIitem or number_of_cans instead of x or zs.  Food for thought: what is the difference between print x and print "x"?

Click here to go to Part 2

List Comprehensions in Python

Python logo
Why hello there fellow netizens!  It's good to finally have been forced to start a blog because I certainly have a lot to share with the world.  This post will serve to be a short expose on a wonderful feature of the Python programming language (named after the t.v. show "Monty Python's Flying Circus") called List Comprehensions.  It's essentially a severely under-appreciated extension of Python's famous lists.  Before we jump in to the rest of the post, I suggest you familiarize yourself with Python lists using my demo on repl.it or the official Python docs if you don't already know how they work or need a refresher.


Ok, now let's start comprehending some lists! Say we have a list, x_list, that contains [1, 2, 3] and we want y_list to contain the value of each element of x_list squared.  That is to say, we want y list to contain [1, 4, 9].  Python makes this a very easy task indeed.

We could do it the schmuck way with a for loop:
x_list = [1, 2, 3]
y_list = []
for n in x_list:
    y_list.append(n * n)
print y_list

But, of course, Python supplies us mortals with List Comprehensions (a delightfully abbreviated syntax):
x_list = [1, 2, 3]
y_list = [n * n for n in x_list]
print y_list

Both versions print [1, 4, 9], but the List Comprehensions version is indisputably more elegant.  One thing I fail to understand is why the developers decided to make "Comprehensions" plural, but such is life.