Monthly Archives

October 2013

Infographics

How Secure Are We When We Log Onto The Internet?

October 31, 2013

You can live in the safest parts of the country and never once be exposed to burglary or theft. Yet the safety provided by a police patrol or neighborhood watch evaporates once you connect to the modern-day version of the Wild West: the World Wide Web. The Federal Trade Commission reports that as many as five percent of adults experience identity theft, topping the list of complaints each year since the statistics were first tracked. How can you make sure that you stay safe when you log in and out of a web browser?

 

netsafety.jpg

Hacking, From Start To Finish

The main way that hackers can break into your email, your social media, your PayPal account, and all other aspects of your personal life stems from the sole security feature: the password. While the password should be a strong bulwark against online intrusion, too few people realize how easy it is for a hacker to crack a simple password. If your password consists of a simple word -- such as "password" -- it may fall into the wrong hands in a matter of minutes, if not seconds. Ars Technica launched a study into password protection and reported that any password under six characters can be hacked in a single day. Beyond six characters, however, the difficulty of hacking increases exponentially. Longer passwords with letters, numbers, and characters minimize this facility.

Networks And Opportunities

How worried are you about the security of an Internet connection itself, compared to the security of your activity on said Internet connection? The information you enter while connected to a WiFi network may be up for grabs, even if you encrypt data and use strong passwords. Hackers can check the strength of a wireless connection by simply browsing open connections on their mobile phone. Consulting firm Security Evaluators concludes that nearly all wireless routers have zero security on their broadcast signals, allowing anyone to tap in and see the pages that every user has pulled up. Encrypt your wireless signal by configuring your router (the manual includes instructions on how to do so) to transmit using Wi-Fi Protected Access, or WPA2.

Mobile Platforms

Since the Internet no longer is constrained to a desktop computer, users have to be careful about their laptop, tablet PC, e-reader, and mobile phone whenever they plug in. Symantec released their annual Internet security report in 2013 and found that one in three mobile-targeted attacks succeed in stealing information. Strange texts, such as gibberish words and characters are a sure-fire sign of an attempt to upload a virus onto a smart phone. Delete texts and emails from unknown sources immediately, without opening them. Check through call logs to make sure that no unauthorized calls or texts have gone out from a phone.

Identity Theft Solutions

Shredding documents, changing passwords, and never responding to fraudulent emails can all go a long way towards identity theft protection. Get professional help with ID theft by utilizing the services of LifeLock or other similar companies in order to proactively prevent hacks, cracks, and phishing. 24/7 monitoring of hardware and sensitive data is essential so that you can be sure you are protected around the clock, remotely or plugged in.

Computer Programming I, Problems, Python

Find the Properties of list in Python - Part II

October 29, 2013

A couple of days ago I wrote an article about Finding the Average, Min, Max and Mode of a list in Python otherwise known as the Properties of list in Python. I thought it was very straight forward and a good educational experience - and it was. However, I was pointed out a few things I would like to clarify and official address. I apologize if I mislead anyone, please see this as an effort to make it up.

  1. The purpose of that article, this one, other articles and future posts is a recording of my experiences and educational drills. Posts are inspired by my day to day activities and questions I often get from students and co-workers. If you have any doubt as to my motives of writing and usefulness of my articles you are free to express them. Also, I suggested you read The Captain's Manifesto to get a better understanding of the Captain and what this blog is about.
  2. Naming a variable list is bad practice. I agree. That was a bad decision on my part. As s python coder, or any other language, variables should not carry the name of a datatype.  For more information I suggest you take a look at the Style Guide for Python Code.
  3. In the article, I failed to mention that we are re-writing some built in function. Python has the functions sum(), min() and max() built in. At there very basic form, they require an iterable datatype, which for now you may consider as a sequence, a list or a tuple. You can read more about these function on the Python Built-In Page.
  4. As of now, everything I write is write and tested under the assumption of Python 2.7.3. I will most likely not update to Python 3 until I must. I feel like the changes introduced in Python 3 are counter productive for Python. For my purposes and the educational element, Python 2.7.3 works better. If I wanted the constrains Python 3 introduced I would have picked another language for implementations on this blog. I actually may move on to introduce C and Java before I get to Python 3. Then again, some minor modification can be made to make every piece of code on here compatible with Python 3.
  5. One liner function such as this one are awesome and highly encouraged: (Thanks Jacob!)
 number, mode = max(dict((k, data.count(k)) for k in data).items(), key=lambda i: i[1]) 

Last but not least, Nico tried to post as a comment an updated version of the code combining all of these ideas, but the indentation got messed up. We all know that Python uses indentation for association of blocks of code, so it makes it a big deal. Here is a copy of the full Code to Compute Average, Min, Max and Mode of a List (or tuple)  in Python:

def average(my_list):
    return sum(my_list)/(len(my_list)*1.0)

def mode(my_list):
    a, b = max(dict((x, my_list.count(x)) for x in my_list).items(),
    key=lambda i: i[1])
    return a,b

def main():
	my_list = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]
	print "The average element of the list is: " + str(average(my_list))
	print "The minimum value in the list is: "   + str(min(my_list))
	print "The maximum value in the list is: "   + str(max(my_list))

	mode_k = mode(my_list)
	print "The mode of the list is: "  + str(mode_k[0]) + " with the mode of: " + str(mode_k[1])
	print "The range of the list is: "   + str(max(my_list)-min(my_list))

if __name__ == "__main__":
	main()

This code will output the same result as we had before:

list_data_2_output
That's all! Happy hacking everyone.
Computer Programming I, Programming Languages, Python

Compute the Average, Min, Max and Mode of a List in Python

October 24, 2013

Lists are by far the most common data type you will use in Python. I wanted to take a few minutes to see how easy Python make the use os lists. I also want you to notice how much ground we can cover by just thinking about these properties of a list. In this article we will talk about lists, functions, searching, return values, data tpes, diconaaries, try-catch try-except blocks and more interesting Python techniques.

So we will be finding the average, min, max and mode of a list. I won’t go into different theories on how to efficiently find these, but rather straight forward approach. Let us start by an assumption that all the values in our list are going to be integers and the data is already stored in a variable named list. As before, we will be using Python 2.7, here is a copy of Python2.7 documentation if you need it. Coming from that we can start by saying our main function looks like this:


def main():

	list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99]

	avg(list)
	min(list)
	max(list)
	mode(list)

This will simply call 4 different functions that will each find and print what we are looking for. First, lets go over some list basic properites. In all these function we will use for loops to iterate over the elements of the array. Lucky Python has a simple syntax that allows us to have a variable in the for loop that will take the values of the array.

What does this mean? You will recall that arrays have 0 indexing property that allows us to access the elements in the array directly. If we were to have the syntax list[0] is our example, the value will correspond to 3. the syntax list[1] will have the value 4. We can access each element individually and directly. We can use this to change values in the array. If we were to have list[0] = 55 in our code, the value of list[0] will change to be 55. Here is an example code:


list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99]

print list

print list[0]
print list[1]

list[0] = 55

print list[0]
print list

This code will output:

wpid-list_index_exampe_python-2013-10-24-15-30.png

Notice that the values of the list have changed after the assignment. Now let us recall the for loop syntax and properties in Python. The syntax is for element in sequence. That means that we need to provide a name of a variable, in this case element and a sequence such as a String, List, Tuple, etc. So if we wanted to print the numbers 1 to 10 in Python, we will need a list sequence with the numbers in a list and then we can just print element. Like this:


for element in [1,2,3,4,5,6,7,8,9,10]:
		print element

And the output:

wpid-1_to_10_python_for_loop-2013-10-24-15-30.png

Cool. However, what if we need the numbers 1 to 1,000? Well, you can either write them all in a list, or you can use the Python range function. This function has 3 variations. You can eithier call it with 1 integer, and the function will return the numbers from 0 to the number you requested in increments of 1. You can provide the function with a start number and end number (2 integers), and you will get back the numbers from the start to end in increments of 1. Finally you can give the range function 3 integers which will server as start, stop and increment. Here is an example to demonstrate:


# range with 1 argument, return a list with the numbers 1 to 10 in increments of 5
print range(10)

# range with 2 arguments, return a list with the numbers 5 to 10 in increments of 1
print range(5,10)

# range with 3 arguments, return a list with the numbers 5 to 50 in increments of 5
print range(5,50,5)

Output:

wpid-range_function_python-2013-10-24-15-30.png

Remember that the range function in not including the last number. So range(10) gave us the numbers 0 to 9 without 10. Lets combine the range function with indexing of the list to access and print the elements in a list.


list = [3,4,1,20,102,3,5]

for i in range(len(list)):
	print list[i]

This code will output:

wpid-python_list_example-2013-10-24-15-30.png

This is one way to do it. Note that we are using the Python len function to get the length of the list. Len is a built in function in Python and will return the length of any sequence.

Another way to accomplish the same task is to use Python and remove the indexing. Like this:


for element in list:
	print element

Both code output will be the same. There are some cases (as we are going to see) were we will need to use the first one and some where we are going to use the second. It all depends on your program. Now lets take a look and see how can we calculate the Average, Min, Max and Mode of a list. First what is the Average of a list? It is just the sum of the elements divided by the number of elements. Well, we can get the number of elements using the len function, and we can iterate through the elements and add them all up. Like this:


def avg(list):

	sum = 0
	for elm in list:
		sum += elm

	print “The average element of the list is: “ + str(sum/(len(list)*1.0))

That was very simple. Let me just clarify some things. You will notice that in the calculation we are multiplying everything by 1.0. We do this to make sure the length of a list, an integer is turned into a double. That way the result of the average element will not be rounded. We also need to convert the average from double to a string in order to concatenate it with a String.

Now let us move on to the Min/Max problem. Essentially both of these are two faces of the same coin. Here is our stragedy to solver this:

  1. Assume the fist element is our Minimum/Maximum value.
  2. For the rest of the elements in the array
  3. If you find a result smaller/larger than Minimum/Maximum, they are the new Minimum/Maximum
  4. return Minimum/Maximum

Hopefully that algorithm was easy enough to follow. Let us take a look how this looks like in Python:


def min(list):

	min = list[0]

	for elm in list[1:]:
		if elm < min:  			min = elm 			 	print "The minimum value in the list is: " + str(min) 	 def max(list): 	max = list[0] 	 	for elm in list[1:]: 		if elm > max:
			max = elm

	print "The maximum value in the list is: " + str(max)

And the output: (assume that: list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99])

wpid-min_max_output-2013-10-24-15-30.png

Now let us to get to the hard part, computing the mode. This will turn out to be not so hard. What is the mode of a list? It is the number (or numbers) that occur most often. Ok. Now we are going to use 2 powerful tools Python has in it’s dictionaries and try-catch try-except statements. Dictionaries in Python are essentially lists where you can define the key. You can think about them as lists, but instead of an index that starts at 0 and goes up, you can name the key anything you would like. I would love to spend some time on them, but this might have to be another post by itself. Try-Catch Try-Except blocks are another post all by themselves, but think about them as a way to avoid TraceBacks. In other words if Python were to execute a statement that will result in a TraceBack, you can specify what to execute and the program will continue instead of terminate. I would love to talk mode about these 2, but for the time being you will have to read more about them on the Python Documentation or Google it.

So what i our strategy to find the Mode of a list? Well, first we can count the number of occurrences of each element in the list. We can use a dictionary to store the count and use the element themselves as the key. Let us see what that we give us:


list = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]

d = {}
for i in t:
	try:
		d[i] += 1
	except(KeyError):
		d[i] = 1

print d

This will output the following:

wpid-dic_mode_python-2013-10-24-15-30.png

When we print out a dictionary we get all the keys and the values separated by a colon (:). We can also get all the keys in the list by typing d.keys(). That will give us a list of keys. Now the rest of the code involves finding the max of all values in the dictionary and then printing the keys that fit these values. Here is how that part looks:


for key in keys[1:]:
		if d[key] > max:
			max = d[key]

	print "The mode of the list is: ",
	for key in keys:
		if d[key] == max:
			print key,
	print " with the mode of: " + str(max)

wpid-mode_of_list_python-2013-10-24-15-30.png

Here is a link to the full code to Compute a Mode of a list in Python.

That’s it. We figured out everything we set to do in the beginning. But wait, there is more!

BOUNS Time: Find the range of the numbers in the list. That is super easy, especially now. The range of a list of numbers is simply the Maximum of your list minus the Minimum of your list. Since we alredy have function for that, this is super easy. Let’s take a look: (note a slight modification of the min/max functions is required to return values instead of print statements).


print "The range of the list is: " + str(max(list) - min(list))

By now you should have a better understanding of how lists work in Python. You will find out that all the tools we looked at are extremely useful and you will find them in every Python application. I am including here a full copy of the .py file I used to Compute the Mean, Min, Max, Mode and Range of a list in Python. I hope you have had some fun and learned something along the way. Here is the output of the complete program for:


list = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]

wpid-python_list_data-2013-10-24-15-30.png

Any questions?

Problems, Programming Languages

The Basics Of Classes in Java

October 17, 2013

It has been a little while since I had a chance to write an article, so I figured I am way past due for one. Let us get started.

What are Classes? Classes are essentially blueprints. Much like a blue print for a coffee mug, house or a car. Classes contain a framework on which we can build an Object. Classes are the technical generic framework of an Object. So what are Objects? Well, the text book definition I tend to like is that Objects are instantiation of Classes. They are the “bringing to life” (if I may) of a Class. Let me try to put this into an example. A table in the most generic form would be a flat service supported by legs. This will be the Class. An Object of the table might be a kitchen table of hight h, width w, length l and has 4 rounded edges with round legs. The particulars of the Object are called attributes. We will get back to that in a little bit.

So what can Objects do for us? Well, the must be somehow useful, after all Java is an Object Oriented Programming Language and is by far the most in demand. Objects are useful because we can interact with them. We can use what we call behaviors, to make use of them. Going back to our example, what can we do with a table? We can put something on it and remove something form it. Maybe we can change it’s height by putting it on 4 bricks? I will admit when you think about it a table is a pretty simple Object, but when we see more examples we will see many more attributes and behaviors.

wpid-java-logo-2013-10-18-00-49.jpg

Before we get in to gory detail let us see more ways objects are useful. This following paragraph is mostly to convince you that Objects are indeed useful in any language. First, Objects allow us to create a hierarchy of an Objects that inherit information from their parents. What does that mean? It means that if for example we create a parent Object, call it Shape, we can create a child Object named Rectangle. The Object Shape might only have 1 attribute Name, but the Object Rectangle will have it’s parents attribute Name, and maybe some more information such as it’s sides lengths. Second, Objects allow us to encapsulate data. This means we can keep the internal of the Object hidden and keep the implementation as well as attributes hidden from another user. So in a nut shell I can write a program that uses an Object that I have no direct way to interact with it, aside from public methods. Third, because of encapsulation I can ensure the integrity of the attributes of an Object. For example, I can prevent anyone from leaving the Name of Shape empty. I know this is a little out there for someone that is just starting off, but like I said it is something you are going to have to learn and we will have to visit that later.

All this theory makes me want to code something up. How about that Rectangle class? Here is a problem formal definition:

Create a class Rectangle. The class has attributes length and width, each of which defaults to 1.0. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 1.0 and less than 10.0. Write a program to test class Rectangle.

This is a classic beginner problem and a good review/quiz problem. It shouldn’t take you longer than 10-15 min to figure something like this out. Lets try to work this out together. Like every other Computer Science problem, start by reading the problem at least twice and then start to figure out what is requested from you. Here is my list of requirements:

  1. Create a Rectangle class
  2. Rectangle has 2 attributes (or variables) length and width that are floating point numbers
  3. The attributes of Rectangle are initially set to 1.0.
  4. We need a getter and setter for each attribute
  5. The setter must validate that the number assigned to length or width is no less than 1.0 and no more than 10.0.
  6. Rectangle has to have a method to calculate perimeter and area.
  7. Write a main method that utilize Rectangle class and tests it’s functions.

Great. Now let us start with Java.

Number 1 is ease, create a Rectangle class. To do this we need the following code stored in a .java file with the same name as the class. In this case Rectangle.java.


public class Rectangle{

}

Well that was super easy. Now let us add the 2 attributes:


public class Rectangle{

	private double length;
	private double width;

}

Ok. That is still easy, but why is there the word “private” there? That is a variable modifier that tells Java what is the working scope of a variable or a method. There are 3 modifiers, private protected and public. Usually attributes of classes are private, at least in the beginning of programming. This is a whole other discussion by itself.

The next thing we need is called a constructor. A constructor is a method that is invoked when to Object is created. This is normally where the attributes are setup. The constructor has to have the same name as the class and does not have a return type like a normal function would have. Here is what our default constructor will look like for Rectangle.


public Rectangle(){
	this.length = 1.0;
	this.width = 1.0;
}

Notice that we used the modifier this to denote the class attribute and not a local variable length. This is not a must, but it will make you life easier and in some cases save you a lot of time figuring out why things are not working like you except. The constructor we have is the empty constructor. It is not a must, like I said. If you do not write a constructor, Java will inherit one from the generic Class definition. That means that nothing will happen beside Java giving your variable an address.

Moving forward (or downward) in our list we need a getter and setter for each attribute. Remember a few paragraphs ago I mentioned something about data integrity? This is where the getter and setters com in to play. They act as a buffer between the user and the values of the attributes. In the case of getters they just return the value (normally). In the case of setters we can modify the actual attribute only if it is an acceptable value. In our case we can write our setters such that if the values are less than 1.0 or more than 10.0 the value of the Object is not set. Let’s take a look:

Here are our getters:


public double getLength(){
	return this.length;
}

public double getWidth(){
	return this.width;
}

And here are the setters:


public void setLength(double length){
	if((length >= 1.0) && (length <= 10.0))           	this.length = length; } public void setWidth(double width){ 	if((width >= 1.0) && (width <= 10.0))
          	this.width = width;
}

That was not so bad, was it? Before we move on to testing we have to complete 1 more task, writing a method for computing perimeter and area. That should be really straight forward.


public double perimeter(){
	return 2 * (this.length + this.width);
}

public double area(){
	return this.getLength() * this.getWidth();
}

You will notice that in the perimeter method we used this to access the variables, while in the area method we used the getters. Both styles are ok and will yield the same results. This was done for educational purposes only.

So now we are done with our class and can move on to testing. Wrong! I highly recommend you take the time to write a debug toString() method. Why? you will thank me later. Here is my toString() for Rectangle:


public String toString(){
	return "Length: " + this.length +"\tWidth: " + this.width;
}

It may seem simple, but later when you are dealing with multiple classes, it is nice to just be able to print them. Let us try to actually use our class. We are going to use a Scanner for user input and standard user output (terminal screen). Here is a simple Main I put together. If you find it useful here is a link to Java Rectangle Class.


public static void main (String[] args)
{

	Scanner userInput = new Scanner(System.in);
	Rectangle r = new Rectangle();

	System.out.print("Enter a length >>> ");
	r.setLength(userInput.nextDouble());

	System.out.print("Enter a width >>> ");
	r.setWidth(userInput.nextDouble());

	System.out.println("The Rectangle with the following attributes: \n" + r);
	System.out.println("Has perimeter is:  " + r.perimeter() + " and area is:  " + r.area());

}

And the output:

wpid-java_rectangle_output-2013-10-18-00-49.png

That is all. Easy isn’t it?