CISC 3110 Lecture 3 Notes: More on Terminal and Unix, Style, Grades and More
Today Professor Weiss continued his discussion of Unix and file operations. We started by copying the program from the Lecture02 directory to the Lecture03 directory. The command to copy a single file on Unix is:
$> cp source-path destination-path
The problem is that this won’t work on directories. To copy the contents of an entire in a directory, use
$> cp -r source-path destination-path
The r stands for “recursive”. Professor Weiss explained “recursive” as doing something until you can’t do it anymore. For example, when climbing a flight of stairs, you climb one stair. Now, you still have a flight of stairs to climb, but you’ve climbed the first stair already. To keep repeating this process is execute the process recursively. Climb one step. There are more, so keep climbing. Climb again. Still more… Climb again. Until you hit the top step. In other words, to “recurse” is keep repeating a process.
Now, talking about copying from one user’s directory to another, we want to copy with as little pain as possible. We can start with an absolute path
/home/student_weiss/
or a relative path
~/student_weiss/private/Lecture02/*
If the local directories are the same, you can use the current location to avoid long paths. (Professor Weiss didn’t specify them, he said we should look into it.) Professor Weiss points out the arrow keys as “history” to bring up the previous commands to make changes to typos.
Some Terminals act like vi, with insert and normal mode, and some act like Windows in that you can use the arrows and edit at the same time. CLI is “Command Line Interface”, useful acronym to know about.
Now, we’re finding the smallest value in an array. The wrong way to do it is to find a large number and start that as the maximum value. The correct way to find this value is to start with the first value in the array. It’s a “working” value, although not necessarily the smallest value. This is akin to running through a deck of cards and starting with the first card. If a card that we find is smaller, we throw away the first card and take the new smaller one. Here’s what this looks like in code:
int min(int arr[], int n){
int result = arr[0];
for(int i=1;i < n;i++){
if(arr[i] < result) result = arr[i];
}
}
There's a bug here, more on that soon.
Professor Weiss notes the way he indents the if statement. "Real Estate is expensive, especially if you live in NY". On the subject of style, Prof. Weiss just said that he won't take points off from his assignments because he doesn't give points on assignments! When code is handed in, he'll check the output. Freeze dates...
Professor Weiss is correcting a typo with vi.
:.1,29s/theMin/result/g
In English, the above expression is "begin, end, search, slash, search pattern, replacement pattern, global". We start on the current line.
As we mentioned, there's a bug in the above function. Professor Weiss is explaining arrays. "Imagine if I asked you to declare variables for 10 numbers. Now you declare int n1, n2, n3, n4 etc. Now go do it for 1,000 variables." In C++ an array of integers is essentially just a list of numbers. Contrast this with Java, where arrays know about themselves. (Particularly, their length.)
In C++, if you go outside the bounds of your array, it's like accidentally going into someone else's property. You may get your head blown off. If you put data out of bounds of an array, you're potentially destroying data that someone else put there. It's meaningless to you.
It could be that you're outside the bounds of your array, but still inside your program. You're just destroying your own variable. The other possibility is that this is "the end of my ranch and the neighbor put a minefield there". You could blow up. The system makes sure that you never go out of your program, but you can still easily overstep the bounds of your own array. If I say a[0] = 15; and `a` is part of Microsoft Word while it were running in memory, you can crash Word. If you're working on a term paper and a program at the same time, you'd possibly break your term paper. Therefore, the operating system takes care of this for you.
Is it worse when your array is "at the edge" of your program, or somewhere "inside" your program? The "middle" is worse, because you don't necessarily get immediate feedback when you try to overstep your bounds. You end up running in some broken state, liable to do more damage later. (In Prof. Weiss' CISC1110 class, he therefore teaches to terminate when weird errors occur.)
Moving back to our program, "garbage in, garbage out". We need a way to return no value when the array has no values in it. Unfortunately, we can't return -1 or 0, because those values are technically valid input. For now, we're leaving it at is. Now, we're covering there "conditional operator" (also called "ternary operator").
int years = ...;
int weeksVacation;
if(years < 5){
weeksVacation = 2;
}else{
weeksVacation = 3;
}
Here's to "talking boolean", which is thinking in terms of true and false at a much more interesting value. Here is how to change the above code to use a single conditional operator:
weeksVacation = years < ? 2 : 3
This has two symbols and three operands, hence the term "ternary", as opposed to a "binary" operator. Professor Weiss says that not knowing ternary operators is like not knowing fractions. Heh. Unlike and an if statement, you must have an else when using a ternary operator. Also, Professor Weiss says that he believes that the two sides of the colon must be of the same type. Makes sense, since we're often using it in the context of assignment.
We're editing some code, so back into vi. (Capital J is a vi-ism for "Join".) We're modifying our print function so, here's the old one:
void print(int arr[], int n) {
cout << "{";
for (int i = 0; i < n; i++) {
cout << arr[i];
if (i < n-1) cout << ", ";
}
cout << "}";
}
Here's what it becomes:
void print(int arr[], int n) {
cout << "{";
for (int i = 0; i < n; i++) {
cout << arr[i] << (i < n-1 ? ", " : "");
}
cout << "}";
}
That's it for ternary. Now we're writing a function to clear out the contents of an array. Can we get a value that has no value? We discussed this earlier. Java has it. We're going to use a zero, but for future reference, we should declare a constant.
Fun fact: Heinz has 57 flavors of ketchup.
Now Professor Weiss is writing a reverse function. Let's see if I did this correctly. Okay, I did it wrong, but there's going to be a problem here...
We want to swap a[n-i-1];.
// TODO: Put array reverse here, //waiting for Prof Weiss to change the permissions
Professor Weiss now shows how to move entire blocks of lines. (:start,end,"t or m", destination line). Now here's the gotcha. The reverse function reverses, but it reverses too much. So the array will look exactly the same when you're done as when before you started. The fix is fairly simple. Here's the change:
Bash stands for "born again shell" (I wonder if this has to do with Bjarne Stroustrup, creator of the C++ language.) When your shell starts running, it runs an initialization file. It's either .profile or .bashprofile. In there, you can set the default permissions. Apparently the default or Professor Weiss' .profile has permissions set to restrict us from reading new directories.
Professor Weiss was going to show us to change permissions, but we ran out of time.
Homework: Take the array functions and make it work for an array of strings. No deadlines yet. Use the cheatsheet.
Hints: You can't average strings. You can take minimums. What about a class called "employees"? How do we compare custom data types?
Two New Apps
Over winter break, I wrote about my attempt at writing an outrageously large number of apps in an unbelievably short period of time. Naturally, I didn’t succeed in accomplishing the supernatural, but I did write a few good apps. I finished Davka’s Torah Notebook for iOS, but even cooler, I met with, planned, and developed an app for the KOF-K. The entire process took three weeks from start to finish. From their website:
KOF-K Kosher Supervision is one of the premier kosher certifying agencies in the world, certifying thousands of products each year in the areas of food production; ingredients, flavors, fragrances, chemicals, pharmaceuticals, as well as vendors, restaurants, and other suppliers of kosher products and services.
I got a phone call on Chanuka, while I was at Yeshiva Zichron Aryeh in Bayswater, for a chanuka party. It was a certain Rabbi Lebovits from the KOF-K. He said that they wanted a simple app, that would allow people to easily ask questions about kosher from their iPhone. I told him that such an app might be too limited in functionality to be approved by Apple, and that we should develop the idea a little more. That was Wednesday.
On Friday morning, Rabbi Lebovits was in Manhattan to do a routine kosher inspection of a local matzah factory. After his inspection run, he swung by the Bialystoker synagogue and picked me up. About twenty or so minutes later, I was in his car gazing out over the Hudson River. We chatted about various things, including some possibilities for the app.
We arrived at KOF-K headquarters a short while later, and I had the privilege of meeting with Rabbis Danny and Ari Senter. We spoke for about an hour. I explained some of the technical bits behind how an app is made and what the collaboration process would look like. The Senters explained their vision to me. I made some mental notes of the details, then, I went upstairs with Rabbi Lebovits to his desk and put together a quick demo of what the app could potentially do. (Zbar is awesome!) We reconvened the meeting for a few minutes to finish up. I also got to demo another project of mine. (More details soon!) Rabbi Lebovits gave me a ride back to the city, since he was going to another inspection anyway.
The next three weeks were a whirlwind, if you will. I pushed the limits on this project, doing some pretty cool things. I added some tools and techniques to my repertoire, just for this project. (ARC anyone?) The incredible folks at Balsamiq sent me a license for Mockups. Thanks a lot for that, it made my job a lot easier.
The awesome part of the project was the clear manner in which it was coordinate and conducted. I have to really give it the folks at the KOF-K for that. Three weeks of time well spent. We set out to accomplish a goal, and we did. It was a pleasure to work with them on this project, and I hope to be able to work with them again in the future. Baruch hashem and thank you.
You can download the KOF-K app for free from iTunes for your iPhone, iPad and iPod touch.
Using VIM
Following up on my previous post about Changing your SSH Password on Unix, I’m going to get into some detail on using VIM and some resources for more information. To start, open Terminal and type in “vi” or “vim”.
On Mac OS X systems, it doesn’t matter what you type, although other machines might complain.
Background
As you might notice, the startup screen explains that VIM stands for Vi IMproved. There was once an editor called Vi, and VIM is an improved version of that. (Wikipedia explains that the name Vi originated from a command in another text editor called “ex”. For those trivia fans out there, Wikipedia also taught me that vi was written in 1976 by someone named Bill Joy.)
My professor mentioned in class yesterday that one of the things that VIM added was more undoes. In vi there was only one undo. Hooray for second, third, fourth, fifth, ad infinitum chances!
Enough of that, let’s get into using this thing.
Using VIM
vi had two “modes”, VIM has those in addition to several others. The three modes we will be focusing on here are NORMAL mode, INSERT mode, and COMMAND mode.
As one of my classmates put it, NORMAL mode is normal relative to VIM. A programmer on SuperUser suggested that NORMAL mode is essentially where you use your keyboard as a mouse.
You can use the arrows to move the cursor, or the [h], [j], [k], and [l] keys to do the same. My professor went through a bunch of keyboard shortcuts, which he has listed on his website, but I took notes into my text editor yesterday in class so I’m going to list them here. (Also, it seems that his website may be broken. I’m having trouble rendering it correctly.) In any event, here’s the keyboard shortcuts we covered in class:
[/] is forward search [?] is backward search. After typing one of those keys, type in what you’re searching for and hit enter. VIM will jump to the first occurrence of the search term. (I’m guessing that VIM has regex support, but I haven’t tried it, nor learned enough to know yet.)
The lowercase [f] moves the cursor forwarding a line. Uppercase [F] goes backward in a line. On a related note, lowercase [t] goes before the character, lowercase [f] moves the cursor on top of it. This makes a difference when cutting or yanking (which is VIMenese for what Word or Pages users would call “copy”).
How do you cut? Use lowercase [x] for that of course. Unlike Word or Pages, we don’t use v for pasting. Use the logical lowercase [p] for that. (I’ve been asked “Why does v paste in Word instead of p? The answer is, of course, that printing occupies the p key.) Use lowercase y for yanking, by the way.
By now you should be a VIM pro, typing a zillion words per minute. If that happens, you might do what Professor Weiss called “character twiddling”. Instead of typing, you might accidentally be “tpying”. The “keyboard shortcut” nature of VIM make it pretty simple to fix. Just move your cursor onto the first letter that’s out of order, and hit lowercase [x] followed by lowercase [p]. That’s it. It’s a cut followed by a paste.
Sometimes you want to move to the beginning of the text on a line, like when you’re coding and your code is indented, for example. Use the “carat”, [^] for that.
A lowercase [g] will take you to the first line in your file.
Uppercase [G] jumps to the last. For some reason this didn’t work for me, while using SSH from my MacBook. It seems that VIM 7.3 on Mac uses uppercase [L] for this.
Before we wrap it up, there’s a few things I want to bring up that were mentioned in class.
The lowercase [d] is delete.
The tilde key [~] changes case and jumps ahead by one character
Some people map [Caps-Lock] to Esc for faster touch typing, so they can hit Caps-Lock to change modes.
It seems that terminal has vi mode, but I’ve found it to be confusing on my MacBook. It could be that my professor is used to it, or perhaps the Unix implantation is different than the FreeBSD based version on Mac OS X Lion.
Also, if you repeat a keystroke twice, it applies to the entire line. For example [y] will yank a single character. However, [y][y] will yank the entire line.
Resources
Professor Weiss has a VIM section on his website. If you’re interested in more VIM stuff, you can look at the VIM Tips Wiki.
Also, there’s a really important command which you can type in to the terminal, before you even get into VIM, called “vimtutor”.
Try it:
vimtutor
Good. That should get you started.
The Emoticon
Now that you know a bit more of how to use VIM. Go open your terminal and start practicing. I leave you with the emoticon that may represent many beginner VIM users’ face after seeing it for the very first time:
:wq
Oh, and vimtutor.
A Train Ride in the City
I wrote this two nights ago, just hours before I started the spring semester. It was a spontaneous attempt at documenting my subway ride. I wrote it on my iPhone, do please excuse any blatant logical, semantic, syntactic, or other errors.
Ah… New York city. I’m sitting on the train. There was a fellow screaming. Then he stopped shouting in English and started screaming in some other incomprehensible language. I’m sitting on the F train.
I count no less than 3 guitars in the car. One is actually being played. One of the guitar owners is playing a game on her iPhone. Swiping sporadically. What game is that? Oh, traffic rush, by Donut Games.
At West 4th street, a fellow gets on and says the he suffers from post-traumatic distress disorder, and had an honorable discharge from the army. I don’t have any cash or food on me.
The train is now running on the A line instead of the F. Spring street. Oh great, now we’re on the C line, Canal street is next. So many pairs of headphones. It seems like the accepted thing to do is to play or listen to music. I need to get myself a pair of headphones. Held by the train dispatcher at – Nevermind the doors just closed. (Canal Street).
A lady is holding a vase of flowers. A young man in a gray suit and darker grey jacket sits with a black messenger bag around his neck. He taps to the beat of his headphones as we pull into chambers St. The guy with the guitar lets his friend play now. Low melody, not bad, but not as confident or as audible as the other guitarist.
Just noticed a skateboard and green sneakers. Nice. Guy next to him is staring into a smartphone. I can’t tell but it looks like an Android.
It’s 9:15PM. The train pulls into Fulton Street. I realize that I’m squishing my new shirt. I feel around in the bag, but there’s no hanger to be found. A tall black man walks on from the left side. He is wearing a black jacket and a backpack on which the shoulder straps have red fabric.
The train is moving faster. The flowers are limp, yet they dance with the train’s rustling as it speeds down the tracks. I look further down the car. Another smartphone. Might be an iPhone 4 or 4S. The form-factor fits but it looks like it might have a case.
The guitarists and the man in the fray suit get off at high street. I notice that the old lady next to me is reading something called “signals in Paris”. The young Hispanic couple across from we’re the gutarists were sitting (now occupied by the tall black man) are cuddling gently.
The next stop is Jay Street Metro Tech, at which point I’ll have to switch directions. The “possible iPhone 4S” is too big to be an iPhone, I notice. It’s an Android and it now has headphones plugged into it. It’s owner is wearing jeans, sneakers, a white jacket, and a green ski cap.
Transfer to the F is upstairs “across against the wall” according to the conductor. I just make it. The lady with the flowers did too. She is talking to a guy siting across from her. He’s in his 50s or 60s. She tells him what kind of flowers they are. “Baby something’s” I can’t hear. The guy is staring into space now, she at her flowerpot.
Only one other smartphone in the car but a bunch of books. Someone is reading Islamophobia. An Indian couple is looking at an Ikea catalog as we pull into York Street. At least two red baseball caps in the car. A few green ski caps. An Indian headband (not the couple – sitting next to the flowers).
Next to her is a big guy listening to Apple earbuds. Across from him, next to me, is a young Indian or middle eastern guy. Brown shoes. Dark blue jeans. Green jacket. Hair combed up in the front.
“This is east broadway”. I disembark and walk past the escalator. School starts tomorrow an I need to get back in shape. I put my phone away and head up the stairs.
How To Change Your SSH Password On Unix
In my last post, I explained how Mac OS X users can get logged in to SSH. In this tutorial, I’m going to walk you through changing your SSH login password, so you don’t have to use that auto generated gibberish provided by the professor. It’s fairly simple, but there are a few gotchas.
Professor Weiss’ email explains how to do this pretty clearly. After logging into the SSH server with your current password, use the Unix command “passwd” to change the password.
vc13:berman_moshe> passwd
Type in the command, and hit enter. You’ll be prompted for your current password. If you enter it correctly, you’ll be prompted to enter, and then confirm, a new password. In case you missed it above, when we logged in, passwords are not displayed on the screen at all. Those little black dots you’re used to seeing on your Mac? ничего. Nada. Nothing. You can still delete characters and use the Shift (or Caps Lock, if you prefer) to capitalize letters, but you will not see the results of your typing on your screen. It’s a security feature. Like I said, Unix is more responsible than a second semester freshman. Assuming everything went well, you’ll see the following:
passwd: all authentication tokens updated successfully.
If you don’t like autogenerated passwords, here’s to sanity and the ability to change your password to something you can actually remember. Don’t make it too simple though. Unix might complain about your password if it’s too simple or short. Here’s what that looks like:
Once you have successfully changed your password. Type “exit” to log off. Try out your shiny new password by logging in (or SSHing in) again. (Hopefully it works. I’m not sure what procedure is in place if you don’t know what you set your new password to.)
Up next: A VIM Tutorial
How To Use SSH on Mac OS X
Today, I started my second semester of college. One of my classes was Advanced Programming with C++. Professor Weiss is instructing the class, and he seems like a great professor. What makes him unique, is the fact that he wants us to use SSH and VIM to edit code throughout the semester. To be honest, I was surprised by this. (The pre-class email said that we would be using Unix, but I thought that we’d be using Unix machines in the classroom.)
My professor has instructions posted on his website for Windows users to set up SSH and VIM. The SSH programs listed on his website are for Windows only. Those one or two (or maybe three) students in the classroom who use Mac OS X, are seemingly left in the dark. Luckily your Mac ships with SSH installed. Here’s how to use it.
To start, let’s open up Terminal. To open Terminal, click on the Finder icon and type in the word “Terminal”. Click on the result Terminal (or hit Enter). Once you have opened the Terminal, you’ll be ready to log in to your SSH account.
The SSH included with your Mac is a little different from the one which you would have installed on a Windows machine. On a Windows computer, you can either enter your username into a GUI, or use commands in the Command Prompt (which is the Windows version of the Mac Terminal) to log in. On Mac, we don’t have that GUI, so we’re going to log in using a single command. This is actually a little quicker than using a GUI. Let’s get to it:
In the terminal, type:
ssh username@server.com
I’m using the username and the server that my professor assigned to me, so here’s what my login looks like:
I’m pretty sure that I shouldn’t be posting server addresses or usernames online, but in the name of being as verbose as possible, that’s what my login looks like. If you’re in my class, you’re going to use lastname_firstname@vc13.vc.panix.com as your server. (Of course, you your first and last name, along with the underscore in the middle, just like it’s printed on those paper that the Professor handed out.)
Hit enter and you’ll be prompted for a password. The password is case sensitive, naturally. Notice that the characters that you type don’t appear onscreen. SSH is more responsible about web security than I am. Once you have entered your password, hit enter again. If you’ve logged in successfully, you’ll see something like this:
Once again, notice the password isn’t shown at all. (In case you’re wondering, the blurred out bit has some info about your internet service provider which I’d rather not leave floating around the net, so that’s blurred out.) Assuming that everything went well, you should be all logged in and ready to go. Yay! Since we’re done for now, type “exit” to log off. I hope you enjoyed your first trip onto the class server (or wherever else you logged into).
In my next post, I explain how to change your SSH password. Until you read that, you’ll have to hang on to that piece of paper that Professor Weiss gave out.



