Table of Contents

C/C++ Programming Journal

August 28th, 2013

This is the first day of class.

Class Websites

An important thing introduced to the class today was the class website.

This page is important because it contains all the tasks for the semester, and it serves as a central hub for all notes in the class.

lab46

The actual place where the magic happens. Lab46 is the server that we must ssh into in order to do class work.
In order for me to get into the server I have to use a program called putty.

Once Installed its very simple to get to the server.

login as :
password : 
 __         _     _ _   __   . . . . . . . . . . . . . . . . . . . . . . . . .
|  |   __ _| |__ / | |_/ /   . Basic System Usage:  Type 'usage' at prompt   .
|  |__/ _` | '_ \\_  _/ _ \  . Events and News:     Type 'news' at prompt    .
|_____\__,_|_.__/  |_|\___/  . Broken E-mail?       Type 'fixmail' at prompt .
---------------------------  . Check Lab46 Mail:    Type 'alpine' at prompt  .
c o r n i n g - c c . e d u  . . . . . . . . . . . . . . . . . . . . . . . . .

 Lab46 is the Computer & Information Science Department's Student Development
 Server for Computer-related coursework, projects, and exploration.  For more
 information, please check out:
  .. .  .    .        .                .                .        .    .  . ..
 .  Lab46 Web Page:       http://lab46.corning-cc.edu/                       .
 .  Lab46 Help Form:      http://lab46.corning-cc.edu/help_request           .
 .  Help E-mail:          haas@corning-cc.edu or wedge@lab46.corning-cc.edu  .
  .. .  .    .        .                .                .        .    .  . ..
No mail.
Challenging Concepts

August 29th, 2013 - Lab

GNU

  1. c - higher level
  2. translate ~ compile ~ gcc
  3. processor

Hello World

int main (int a, char **){
printf ("Hello World!!!");
}

UNIX Commands

GCC

GCC manual gcc.gnu.org

gcc uses file name extensions to help figure out what it should be doing and what kind of file it is dealing with

Bash

Challenging Concepts

Things to look into

GCC manual gcc.gnu.org section 3 look at ~ see it goes through phases 1: preproccessing 2: compilling 3: assembling 4: linking

August 30th, 2013

Review

Class Repository

lab46:~$ hg help
Setup Step 1 - Cleaning src directory
lab46:~$ mv src src.bak
Setup Step 2 - Making new src directory
lab46:~$ mkdir src
Setup Step 3 - Local Cloning
lab46:~$ hg clone http://www/hg/user/(username) ~/src
Setup Step 3 - Alternative Remote Cloning
lab46:~$ hg clone http://lab46.corning-cc.edu/hg/user/(username) ~/src
Setup Step 4 - Restoring src content
lab46:~$ cd src
lab46:~$ lab46:~/src$ mv ~/src.bak/* ~/src/
lab46:~/src$ rmdir ~/src.bak
Setup Step 5 - Customizing Repo
lab46:~/src$ vi .hg/hgrc
[paths]
default = http://www/hg/user/(lab46username)
[web]
push_ssl = False
allow_push = *

[ui]
username = (your real first name followed by last name, space separated) <(lab46username)@lab46.corning-cc.edu>

[auth]
lab46.prefix = http://www/hg/user/(lab46username)
lab46.username = (lab46username)
lab46.schemes = http
Setup Step 6 - Ignoring File Types for sync
lab46~/src$ vi .hgignore
Sync Step 1 - Checking for changes in src folder
lab46:~/src$ hg status
Sync Step 2 - Adding files to the tracking
lab46:~/src$ hg add
lab46:~/src$ hg add
adding pokemon.c
lab46:~/src$
Sync Step 3 - Committing and pushing files
lab46:~/src$ hg commit -m "(something to note about the commit that can be easily referenced)"
lab46:~/src$ hg push
http authorization required
realm: Lab46/LAIR Mercurial Repository (Authorization Required)
user: <lab 46 user name>
password: <lab 46 password>
pushing to http://www/user/<lab 46 user name>
searching for changes
remote: adding changesets
remote: adding manifests
remote: adding file changes
remote: added <#> changesets with <#> change to <#> file
Alternative Sync Step 1
lab46:~/src$ hg pull
lab46:~/src$ hg update

Challenges

September 4th, 2013

There were lots of things covered today the primary thing was data-types

Data Types

Integer Types ~ length describes the size of the storage allocated ~ most likely to be used
  1. char ~ short for character has a dual purpose of being able to display character data
  2. short int ~ short integer ~ describes a small scale integer
  3. Int ~ integer ~ a thing that represents a whole number
  4. long int
  5. long long Int
Floating Point
  1. float
  2. double
  3. long double
Scaler
  1. Pointer Types ~ memory variables not really a thing that stands by themselves utilize the existing types ~ describing the region of memory that is pointing at something with specified property
Composite
  1. Arrays ~ all of the other types can be represented as an array homogenous in an array every element needs to be of the same data type
  2. Structures (struct) ~ heterogeneous can be of any types
Things to note
  1. Integer array is no different than having separate integer storage points
  2. Consider the performance requirements of your program and try to keep them reasonable even with the limits of memory being pushed daily to extreme ends. Proper coding is a must
  3. most programing books for c use argc argv as their examples
  4. main has the ability to communicate with the system
Variables defined by the command line
Example : int main (int argc, char ** argv)
  1. argc is an argument count
  2. when ever you see a * that is not there for multiplication it denotes use of pointers
  3. with the program knowing what it was called at run time, it can behave differently depending on how it was called

Common Escape Characters

OS Specific Notes

1) unix use line feeds to denote end of line
2) dos / windows use crlf carriage return line feed
3) mac used cr carriage return

Source Code

  1. source code portability ~ when you have the source code not only can you run it on other systems but you can fix it and enhance it for your own needs
  2. binary code portability ~ no system requirement but needs a specific program to help

1) jAVA ~ java vm needs to be available ~ need to be running a similar version
2) Interpreters
3) flash ~ with limits

1) c got its name to fame from source code portability
2) having the source code in a c compiler allows me to run the c code in any system

Storage Requirements and Usage

  1. How much storage does it use?
  2. What are the range of values we can store in them?
  1. declare the existence of the variable
  2. always a good thing to initialize your variable
Finding the size
Example for unsigned char
#include <stdio.h>
int main( )
{
    signed char sc;
    unsigned char uc;
    sc = 0;
    uc = 0;
    printf("an unsigned char is %hhu bytes \n", sizeof(uc));
    printf("lower bound is % hhu \n", uc);
    printf ("upper bound is % hhu \n", (uc - 1));
    return(0);
}

Challenges

Update

Unsigned
  1 #include <stdio.h>
  2 int main( )
  3 {
  4     unsigned char uc=0;
  5     unsigned short int us=0;
  6     unsigned int ui=0;
  7     unsigned long int ul=0;
  8     unsigned long long int um=0;
  9     //unsigned char
 10     printf("A unsigned char is %d byte\n",sizeof(uc));
 11     printf("Lower bounds is %hhu\n", (uc));
 12     printf("Upper bounds is %hhu\n\n", (uc-1));
 13     //unsigned short
 14     printf("A unsigned short is %d bytes\n",sizeof(us));
 15     printf("Lower bounds is %hu\n", (us));
 16     printf("Upper bounds is %hu\n\n", (us-1));
 17     //unsigned int
 18     printf("A unsigned int is %d bytes\n",sizeof(ui));
 19     printf("Lower bounds is %u\n", (ui));
 20     printf("Upper bounds is %u\n\n", (ui-1));
 21     //unsigned long
 22     printf("A unsigned long is %d bytes\n",sizeof(ul));
 23     printf("Lower bounds is %lu\n", (ul));
 24     printf("Upper bounds is %lu\n\n", (ul-1));
 25     //unsigned long long
 26     printf("A unsigned long long is %d bytes\n",sizeof(um));
 27     printf("Lower bounds is %llu\n", (um));
 28     printf("Upper bounds is %llu\n\n", (um-1));
 29     return(0);
 30 }
A unsigned char is 1 byte
Lower bounds is 0
Upper bounds is 255

A unsigned short is 2 bytes
Lower bounds is 0
Upper bounds is 65535

A unsigned int is 4 bytes
Lower bounds is 0
Upper bounds is 4294967295

A unsigned long is 8 bytes
Lower bounds is 0
Upper bounds is 18446744073709551615

A unsigned long long is 8 bytes
Lower bounds is 0
Upper bounds is 18446744073709551615
Signed
  1 #include <stdio.h>
  2 int main( )
  3 {
  4     signed char sc=0;
  5     signed short int ss=0;
  6     signed int si=0;
  7     signed long int sl=0;
  8     signed long long int sm=0;
  9     //signed char
 10     printf("A signed char is %d byte\n",sizeof(sc));
 11     printf("Lower bounds is %hhd\n", ((unsigned char)(sc-1)/2)+1);
 12     printf("Upper bounds is %hhd\n\n", ((unsigned char)(sc-1)/2));
 13     //signed short
 14     printf("A signed short is %d bytes\n",sizeof(ss));
 15     printf("Lower bounds is %hd\n", ((unsigned short)(ss-1)/2)+1);
 16     printf("Upper bounds is %hd\n\n", ((unsigned short)(ss-1)/2));
 17     //signed int
 18     printf("A signed int is %d bytes\n",sizeof(si));
 19     printf("Lower bounds is %d\n", ((unsigned int)(si-1)/2)+1);
 20     printf("Upper bounds is %d\n\n", ((unsigned int)(si-1)/2));
 21     //signed long
 22     printf("A signed long is %d bytes\n",sizeof(sl));
 23     printf("Lower bounds is %ld\n", ((unsigned long)(sl-1)/2)+1);
 24     printf("Upper bounds is %ld\n\n", ((unsigned long)(sl-1)/2));
 25     //signed long long
 26     printf("A signed long long is %d bytes\n",sizeof(sm));
 27     printf("Lower bounds is %lld\n", ((unsigned long long)(sm-1)/2)+1);
 28     printf("Upper bounds is %lld\n\n", ((unsigned long long)(sm-1)/2));
 29     return(0);
 30 }
A signed char is 1 byte
Lower bounds is -128
Upper bounds is 127

A signed short is 2 bytes
Lower bounds is -32768
Upper bounds is 32767

A signed int is 4 bytes
Lower bounds is -2147483648
Upper bounds is 2147483647

A signed long is 8 bytes
Lower bounds is -9223372036854775808
Upper bounds is 9223372036854775807

A signed long long is 8 bytes
Lower bounds is -9223372036854775808
Upper bounds is 9223372036854775807

September 5th, 2013 - Lab

Review

Differences

MinGW

Environment
CLI Interpenetrate

two major types of commands in a command line interpenetrate

  1. internal (Unix and Linux ~ built into the command line inter - knows where to go )
  2. external

C and C++

Joe Rant

Unix Output

Things To Work On

START COLAB ON
  1. UNIX / Microsoft Command Reference ~ a Cheat Sheet equivalence
  2. mingw bin folder file descriptions
  3. gcc options for 1) preprocess 2) compile 3) assemble 4) link
  4. figure out the other switches for these and how they would work
  5. file name extensions too ~ gcc documentation on bitbucket section 3 of manual
  6. 4 ~ 9899 section 5 pull out what we find most important
  7. freestanding hosted arguments reference for main( ) 5 9899 section 6
  8. language for 9899 section 7 library
  9. input output

Closing Thoughts and Challenges

September 6th, 2013

Signed Char

#include <stdio.h>
int main( )
{
    signed char sc;
    unsigned char uc;
    sc = 0;
    uc = 0;
    printf("a signed char is %hhu bytes\n", sizeof(sc));
    printf("lower bound is %hhd\n",((unsigned char)(uc-1)/2)+1);
//    printf("upper bound is %hhd\n",((unsigned char)(uc-1)/2));
    printf("upper bound is %hhd\n", 0xFFFF & 0x80);
    return(0);
}

Unix Specifics

Challenges and Closing Thoughts

September 11th, 2013

Sizes

PrintF Review

  1. short
  2. int
  3. char
  4. all the variable types
  5. * - / * ^ &

Function of STDIO.h

Good Programming

Example Program of the Day

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 int main( )
  4 {
  5     char *name,fi;
  6     name=NULL;
  7     fi=0;
  8     unsigned char age=0;
  9     printf("Please enter your name");
 10     name=(char*)malloc(sizeof(char)*20);
 11     scanf("%s", name);
 12     printf("%s, what is your age?",name);
 13     scanf("%hhu",&age);
 14     fi=*(name+0);
 15     printf("%s, your initial is %c (%hhu) and you are %hhu years old\n",name    ,fi,fi,age);
 16     return(0);
 17 }

September 12th, 2013 - Lab

September 13th, 2013

If Statements

If mods
  * "When writing IF statements it is good to remember"
  - "> greater than"
  - "< less then"
  - ">= greater than or equal to"
  - "<= less than or equal to"
  - "== Check equality ( is this equal to)"
  - "!= not equals"
  - "= sets equality"
  - "if statements do not need a semicolon"
  - "you can have if statements"
  - "else statements"
  - "with else if"
  - "have have exactly 1 if"
  - "can have only "
  - "exactly 1 else"
  - "0 or more else if"
  - "if(0) - true"
  - "if(1) - false"
If Types
  1. do while - run through the loop and then see if it should run again
  2. while
  3. for - need starting value - setting start value - second part is how long do we want to loop - third part
Misc stuff

We learned about things with I but they cant be posted in wiki syntax

Counting arguments

September 18th, 2013

GD

  1 # include <stdio.h>
  2 # include <gd.h>
  3 # define BLACK 0
  4 # define RED 1
  5 # define GREEN 2
  6 # define BLUE 3
  7 # define WHITE 4
  8 # define YELLOW 5
  9 int main()
 10 {
 11     FILE *out; // lets us interact with files in this case an output file
 12     char outfile[]="/home/jkosty6/public_html/snowmanhouseccc.png";
 13     gdImagePtr img;
 14     unsigned int color[5];
 15     unsigned short int high,wide,x;
 16     wide=800;
 17     high=600;
 18     img=gdImageCreate(wide,high);
 19     color[BLACK]=gdImageColorAllocate(img,0,0,0);
 20     color[RED]=gdImageColorAllocate(img,255,0,0);
 21     color[GREEN]=gdImageColorAllocate(img,0,255,0);
 22     color[BLUE]=gdImageColorAllocate(img,0,0,255);
 23     color[WHITE]=gdImageColorAllocate(img,255,255,255);
 24     color[YELLOW]=gdImageColorAllocate(img,255,255,0);
 25     gdImageFilledRectangle(img,0,0,wide-1,high-1,color[BLACK]);
 26     gdImageFilledRectangle(img,wide/3,high/1,wide/1,high/3, color[YELLOW]);
 27     gdImageFilledRectangle(img,wide/3,150,wide/1,200, color[BLUE]);
 28     gdImageFilledRectangle(img,300,400,400,500, color[BLACK]);
 29     gdImageFilledRectangle(img,650,400,750,500, color[BLACK]);
 30     gdImageFilledRectangle(img,450,400,600,high-1, color[BLACK]);
 31     gdImageFilledArc(img, 90, 90, 180, 180, -270, -90, color[RED], gdArc);
 32     gdImageFilledArc(img, 180, 90, 180, 180, -270, -90, color[RED], gdArc);
 33     gdImageFilledArc(img, 270, 90, 180, 180, -270, -90, color[RED], gdArc);
 34     gdImageFilledArc(img, 90, 300, 100, 100, 360, 0, color[WHITE], gdArc);
 35     gdImageFilledArc(img, 90, 400, 130, 130, 360, 0, color[WHITE], gdArc);
 36     gdImageFilledArc(img, 90, 500, 180, 180, 360, 0, color[WHITE], gdArc);
 37     out=fopen(outfile, "wb");
 38     gdImagePngEx(img,out,-1);
 39     fclose(out);
 40     gdImageDestroy(img);
 41     return(0);
 42 }

Thoughts

September 19th, 2013 - Lab

September 20th, 2013

Loops

int i;
for (i=0; i<10;i++)
{
    printf("%d\n",i);
}
Loops in GD

http://lab46.corning-cc.edu/~jkosty6/classgd.png

  1 # include <stdio.h>
  2 # include <gd.h>
  3 # define BLACK 0
  4 # define RED 1
  5 # define GREEN 2
  6 # define BLUE 3
  7 # define WHITE 4
  8 int main()
  9 {
 10     FILE *out;
 11     char outfile[]="/home/jkosty6/public_html/classgd.png";
 12     gdImagePtr img;
 13     unsigned int color[5];
 14     unsigned short int high,wide,x,y;
 15     wide=641;
 16     high=641;
 17     img=gdImageCreate(wide,high);
 18     color[BLACK]=gdImageColorAllocate(img,0,0,0);
 19     color[RED]=gdImageColorAllocate(img,255,0,0);
 20     color[GREEN]=gdImageColorAllocate(img,0,255,0);
 21     color[BLUE]=gdImageColorAllocate(img,0,0,255);
 22     color[WHITE]=gdImageColorAllocate(img,255,255,255);
 23     gdImageFilledRectangle(img,0,0,wide-1,high-1,color[BLACK]);
 24 //      {
 25 //      for(x=0;x<8;x++)
 26 //      for(y=0;y<8;y++)
 27 //          if ((x + y) % 2 == 0)
 28 //              {
 29 //              gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[BLUE]);
 30 //              }
 31 //          else
 32 //              {
 33 //              gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[RED]);
 34 //              }
 35 //          }
 36     gdImagePngEx(img,out,-1);
 37     fclose(out);
 38     gdImageDestroy(img);
 39     return(0);
 40 }

Thoughts

After playing with GD for a few days, I am finding it to be more difficult that its worth.

UPDATE

I have figured out what my problem was. I had deleted the line 36

  1 # include <stdio.h>
  2 # include <gd.h>
  3 # define BLACK 0
  4 # define RED 1
  5 # define GREEN 2
  6 # define BLUE 3
  7 # define WHITE 4
  8 int main()
  9 {
 10     FILE *out;
 11     char outfile[]="/home/jkosty6/public_html/classgd.png";
 12     gdImagePtr img;
 13     unsigned int color[5];
 14     unsigned short int high,wide,x,y;
 15     wide=641;
 16     high=641;
 17     img=gdImageCreate(wide,high);
 18     color[BLACK]=gdImageColorAllocate(img,0,0,0);
 19     color[RED]=gdImageColorAllocate(img,255,0,0);
 20     color[GREEN]=gdImageColorAllocate(img,0,255,0);
 21     color[BLUE]=gdImageColorAllocate(img,0,0,255);
 22     color[WHITE]=gdImageColorAllocate(img,255,255,255);
 23     gdImageFilledRectangle(img,0,0,wide-1,high-1,color[BLACK]);
 24         {
 25         for(x=0;x<8;x++)
 26         for(y=0;y<8;y++)
 27             if ((x + y) % 2 == 0)
 28                 {
 29                 gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[BLUE]);
 30                 }
 31             else
 32                 {
 33                 gdImageFilledRectangle(img,(80*x)+5,(80*y)+5,(80*x)+75,(80*y)+75,color[RED]);
 34                 }
 35             }
 36     out=fopen(outfile, "wb");
 37     gdImagePngEx(img,out,-1);
 38     fclose(out);
 39     gdImageDestroy(img);
 40     return(0);
 41 }

September 25th, 2013

Today we learned a lot about arrays

Arrays

Example

Scalers

===GD Arrays==-

gdPoint triangle[3]; ~ array of 3 gd points
triangle[0].x = wide/2;
triangle[0].y = 0;
triangle[1].x =0;
triangle[1].y =high-1;
triangle[2].x =wide -1;
triangle[2].y = high -1;

Challenges

Thoughts

Drawing with GD using exact x and y values with arrays is actually easier in my opinion than the alternative

September 27th, 2013

Today we just finished working on our GD pictures.

October 2nd, 2013

Shifts

  1. » logical right shift
  2. « logical left shift
  1 #include <stdio.h>                                                          
  2     int main ()
  3     {
  4     int a =5;
  5     printf("%d\n",a);
  6     a=a|6;
  7     printf("%d\n",a);
  8     a=a&9;
  9     printf("%d\n",a);
 10     a=!a;
 11     printf("%d\n",a);
 12     a=a^7;
 13     printf("%d\n",a);
 14     return(0);
 15     }
 16 
  1 #include <stdio.h>                                                                                                                      
  2 #include <stdlib.h>
  3 
  4 int getval(int,int); ~ prototyping
  5 int main()
  6 {
  7     int i,x,u,l;
  8         printf("Enter a number:");
  9         scanf("%d",&i);
 10         srand(i);
 11         printf("Give me the highest number.");
 12         scanf("%d",&u);
 13         printf("Give me the lowest number.");
 14         scanf("%d",&l);
 15 for (i=0;i<12;i++)
 16 {
 17     x=getval(u,l);
 18     printf("%d ",x);
 19 }
 20     printf("\n");
 21 return(0);
 22 }
 23 int getval (int top, int bottom)
 24 {
 25     int result;
 26     result = rand() %top + bottom;
 27 return(result);
 28 } 

October 4th, 2013

We created a program to tell you the ascii value of something, and changing a letters case

  1 #include <stdio.h>
  2 int main()
  3 {
  4     char x=0;
  5     char y=0;
  6         printf("Enter a number (0-255): ");                                 
  7         scanf("%hhu", &x);
  8         printf("Enter a character: ");
  9         scanf("%c", &y);
 10         printf("x is numerically %hhu and characterally %c \n",x,x);
 11         scanf("y is numerically %hhu and characterally %c \n",y,y);
 12         printf("x+48 characterally is %c \n", (x+48));
 13         scanf("y+32 character is %c \n", (y+32));
 14     return(0);
 15 }

enter in a data stream, stays behind in data stream

Function Stuff

October 9th, 2013

Compiling

WIKI DOESNT LIKE MY CODE

Limits
P.P.D.

Structs

Closing

It was interesting to see just how long a code is after adding in the headerfiles

October 11th, 2013

Today was the knowledge assessment. It was a little difficult at first, but when I really read the problems, I figured them out. Except the last one that blew my mind. A time based RNG

October 16th, 2013

Object oriented and C

Arrays vs structs

struct thing {
    int a;
    int b[20];
    float c;
    int d;
    short int e;
}; ~ one of the few times you need a semi colon after a closing bracket in C
struct thing stuff; ~ one thing from struct "thing" and we named it stuff
stuff.a =12;
stuff.b[ j ]='A'; ~ 
#include <stdio.h>
int main( )
{
    int i,j,k;
    struct person {

        char name [24];

    char age;

    float height;

};
typedef struct person ID;
ID db [4];
for (i=0; i<4; i++)
{
    printf("Entry [%d] name : ");
    scanf("%s",ID[i].name);
    printf("age");
    scanf("%hhu",&(ID[i]age));
    printf("height : ");
    scanf ("%f",&(ID[i]height));
}
    
    //print it all back out
    return(0);
}

Thoughts

Structs have me at a loss, but I am sure I will know them soon enough

October 18th, 2013

C plus plus

  1 #include <stdio.h>
  2 int main ( )
  3 {
  4     printf("Hello, world!\m");
  5     return (0);
  6 }

struct

October 23rd, 2013

Program with classes

today we wrote a program with classes and structs to it dealing with the sides of a shape and then outputting them

Class square {
      public
            square( );
            void setside(int);
            int getside( );
            int area( );
            int perimeter( );
      private
            int x;
};
 
square :: square( )
{
      x=0;
}
void square :: setside(int side)
{
      x=side;
}
int square :: getside( )
{
      return(x);
}
int square :: area( )
{
      return(X * X);
}
int square :: perimeter( )
{
      return( 4 * x );
}
 
int main ( )
{
      square s1;
      square s2;
      s1.setside(4);
      s2.setside(12);
      printf("s1's side is %d\n", s1.getside( ));
      printf("s1's area is %d\n", s1.area( ));
      printf("s1's perimeter is %d\n", s1.perimeter( ));
      return(0);
}

October 25th, 2013

bignum.h
#ifndef _BIGNUM_H
#define _BIGNUM_H
class BigNum {

    public:

    BigNum( );

    BigNum(unsigned int);

    unsigned char getbase( );

    unsigned char getlength( );

    unsigned char getsign( );

    void SetBase (unsigned char);

    void SetLength (unsigned char);

    void SetSign (unsigned char);

    void zero( );

    void print ( );

    private:

    unsigned char base;

    unsigned char Length;

    unsigned char sign;

    unsigned char *data;

October 30th and November 1st, 2013

This week we continued work on our program, but this week we added the ability to increment our numbers.

December 11th, 2013

Tape

I finally was able to get tape to work

Storage.h
#ifndef _STORAGE_H
#define _STORAGE_H

using namespace std;

class storage
{
    public:
        storage();
        int getCapacity();
        int getFree();
        int getUsed();

    protected:
        int load();
        void store(int);
        bool pos(int);

    private:
        int data[256];
        int used;
        int available;
        int loc;
};

#endif
Storage.cc
#include "storage.h"
#include <iostream>

storage :: storage()
{
    int i;
    used = 0;
    available = 255;
    for (i = 0; i < 256; i++)
        data[i] = 0;
    loc = 0;
}

int storage :: getCapacity()
{
    return used + available + 1;
}

int storage :: getFree()
{
    return available + 1;
}

int storage :: getUsed()
{
    return used;
}

int storage :: load()
{
    return data[loc];
}

void storage :: store(int value)
{
    if (used < 255)
    {
        data[loc] = value;
        used++;
        available--;
    }
    else
        cout << "Error! Out of space!" << endl;

    if (value == 0)
    {
        used--;
        available++;

        if(used > 255)
            used = 255;

        if(used < 0)
            used = 0;

        if(available > 255)
            available = 255;

        if(available < 0)
            available = 0;
    }
}
bool storage :: pos(int location)
{
    bool retval = true;

    if ((location >= 0) && (location <= 255))
        loc = location;
    else
        retval = false;

    return retval;
Tape.h
#ifndef _TAPE_H
#define _TAPE_H
#include <iostream>
#include "storage.h"
class tape : public storage
{
    public:
        tape();
        int read();
        void write(int);
        void forward();
        void backward();
        void rewind();
        void setlabel(string);
        string getlabel();
        int getpos();

    private:
        string label;
        int position;
};

#endif
Tape.cc
#include "storage.h"
#include "tape.h"
#include <cstdio>

tape::tape()
{
    position=0;
    pos(position);
    label="TapeYo";
}

int tape::read()
{
    return(load());
}

void tape::write(int num)
{
    store(num);
}

void tape::forward()
{
  if (position==255)
         {
            printf("You have reached the end of the tape!\n");
            position--;
            pos(position);
         }
else
    {
        position++;
        if (position==255)
            {
            printf("You have reached the end of the tape!\n");
            position--;
            pos(position);
            }
    }
}


void tape::backward()
{
  if (position==0)
         {
            printf("You have reached the end of the tape!!\n");
            position++;
            pos(position);
         }
else
    {
        position--;
        if (position==0)
            {
            printf("You have reached the end of the tape!\n");
            position++;
            pos(position);
            }
    }
}

void tape::rewind()
{
    while(position!=0)
    {
        position--;
    }

    pos(position);
}

void tape::setlabel(string labelstr)
{
   label=labelstr;
}

string tape::getlabel()
{
   return(label);
}

int tape::getpos()
{
    return(position);
}
Main.cc
#include <cstdio>
#include "tape.h"
#include <iostream>

using namespace std;

int main()
    {
    tape t;
    char choice;
    int tapeinputval;

while(choice!=113)
    {
    printf ("\n================================================\n");
    printf ("The Tape Is Currently At Position ");
    cout << t.getpos();
    printf ("\n\n");
    printf ("Please Choose A Command For The Tape To Take\n\n");
    printf ("f = move the tape forward\n");
    printf ("b = move the tape backward\n");
    printf ("r = rewind the tape\n");
    printf ("e = read what is stored at current position\n");
    printf ("w = write at current position\n\n");
    printf ("Use q to quit\n");
    printf ("================================================\n");
    cin >> choice;
    printf ("\n");
        switch(choice)
            {
            case 102:
                t.forward();
                printf ("The Tape Has Moved To Position ");
                cout << t.getpos();
                printf ("\n");
                break;
            case 98:
                t.backward();
                printf ("The Tape Has Moved To Position ");
                cout << t.getpos();
                printf ("\n");
                break;
            case 114:
                t.rewind();
                printf ("The Tape Has Moved To Position ");
                cout << t.getpos();
                printf ("\n");
                break;
            case 101:
                printf ("The Tape Is Currently At Position ");
                cout << t.getpos();
                printf (" and stored here is ");
                cout << t.read();
                printf ("\n");
                break;
            case 119:
                printf ("Please enter a value to store at current position \n");
                cin >> tapeinputval;
                t.write(tapeinputval);
                printf ("\nThis position now stores the value ");
                cout << t.read();
                break;
            case 113:
                return(0);
        }
    }
}

December 12th, 2013

Big Num

I managed to get increment and decrement to work. From these two things I can do almost anything

Base.cc
#include "bignum.h"

unsigned char BigNum::getBase()
{
        return(base);
}

void BigNum::setBase(unsigned char base)
{
        this -> base = base;
}
Bignum.h
#ifndef _BIGNUM_H
#define _BIGNUM_H

class BigNum
{

public:
        BigNum();
        BigNum(unsigned char);
        unsigned char getBase();
        unsigned char getLength();
        unsigned char getSign();
        void setBase(unsigned char);
        void setLength(unsigned char);
        void setSign(unsigned char);
        void zero();
        void print();
        void increment();
        void decrement();
private:
        unsigned char base;
        unsigned char length;
        unsigned char sign;
        unsigned char *data;

};

#endif
Length
#include "bignum.h"


unsigned char BigNum::getLength()
{
        return(length);
}

void BigNum::setLength(unsigned char length)
{
        this -> length = length;
}
Print.cc
#include "bignum.h"
#include <cstdio>
void BigNum::print()
{
        int i;


        for(i=0; i<length; i++)
        {
                printf("%d", *(data+i));
        }
        printf("\n");
}
Sign.cc
#include "bignum.h"

unsigned char BigNum::getSign()
{
        return(sign);
}

void BigNum::setSign(unsigned char sign)
{
        this -> sign = sign;
}
Zero
#include "bignum.h"

void BigNum::zero()
{
    for(int i=0;i<length;i++)
    {
        *(data+i)=0;
    }
}
create.cc
#include <cstdlib>
#include <cstdio>
#include "bignum.h"

BigNum::BigNum()
{
        length = 8;
        base = 10;
        sign = 0;
        data = (unsigned char*)malloc(sizeof(char)*length);
        this -> zero();
}


BigNum::BigNum(unsigned char length)
{
        this -> length = length;
        base = 10;
        sign = 0;
        data = (unsigned char*)malloc(sizeof(char)*this -> length);
        this -> zero();
}
increment.cc
void BigNum::increment()
{
    char carryvalue=1;
    {
        for(int i=0;i<length;i++)
        {
            char endresult = *(data+(length-1)-i);
            char addedvalue = endresult + carryvalue;
                if ((addedvalue > 9) && ((addedvalue%10)==0))
                    {
                    addedvalue = 0;
                    carryvalue = 1;
                    }
                else
                    {
                    carryvalue = 0;
                    }
                    *(data+(length-1)-i) = addedvalue;
        }
    }
}
decrement.cc
void BigNum::decrement()
{
        char carryvalue=1;
    {
        for(int i=0;i<(length-1);i++)
        {
            char endresult = *(data+(length-1)-i);
            char subtractedvalue = endresult - carryvalue;
                if ((endresult <= 0) && (carryvalue == 1))
                    {
                    subtractedvalue = 9;
                    carryvalue = 1;
                    }
                else
                    {
                    carryvalue = 0;
                    }
                    *(data+(length-1)-i) = subtractedvalue;
        }
    }
}
main.cc

Division is not done yet, but it is a work in progress.

#include "bignum.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstdio>

using namespace std;

int main()
{
	int choice;
	printf("\n\n================================================================\n");
	printf( "How would you like to increment or decrement a number?\n");
	printf( "\n0 - Subtraction");
	printf( "\n1 - Addition");
	printf( "\n2 - Multiplication");
	printf( "\n3 - Division !! NOT WORKING - WORK IN PROGRESS !!\n\n"); // work in progress
	printf( "Your Choice is :");
	cin >> choice;
	BigNum num;
	num.setBase(10);
	int i,x;
	int loop1,loop2;
	int loop3,loop4;
	int loop5,loop6;
	int loop7,loop8;
	int sub1,sub2;
	int div1,div2;
	int z,w;	
		{
		if (choice ==3)
			{
			printf ("================================================================\n");
			printf ("\nDivision Mode\n");
			printf ("\nEnter Your First Number: ");
			cin >> div1;
			printf ("Enter Your Second Number: ");
			cin >> div2;
			printf ("\n================================================================\n");
			{
                if (div1 > div2)
                    {
                    loop7=div1;
                    loop8=div2;
                        {
						for(i=0;i<=loop7;i+=loop8);
							{
							num.increment()
							}
						//other division stuff not done
						num.print();
						}
					}
				else
					{
					loop7=div2;
					loop8=div1;
						{
						for(i=0;i<=loop7;i+=loop8);
							{
							num.increment();
							}
						//other division stuff not done
						}
                                              num.print();
					}	
			}
		}
		else if (choice == 2)
			{
			printf ("================================================================\n");
			printf ("\nMultiplication Mode\n");
			printf ("\nEnter Your First Number: ");
			cin >> loop5;
			printf ("Enter Your Second Number: ");
			cin >> loop6;
			printf ("\n================================================================\n");
			{
			for(i=0;i<loop5;i++)
				{
				for(x=0;x<loop6;x++)
					{
					num.increment();
					}
				}
			}
				num.print();
		}
		else if (choice == 1)
			{	
			printf ("================================================================\n");
			printf ("\nAddition Mode\n");
			printf ("\nEnter Your First Number: ");
			cin >> loop1;
			printf ("Enter Your Second Number: ");
			cin >> loop2;
			printf ("\n================================================================\n");
			{
			for(i=0;i<loop1;i++)
				{
				num.increment();
				}
			for(i=0;i<loop2;i++)
				{
				num.increment();
				}
			}
				num.print();
		}
		else
			{
			printf ("================================================================\n");
			printf ("\nSubtraction Mode - Largest of The Two Numbers Sorted As Minuend\n");
			printf ("\nEnter Your First Number: ");
			cin >> sub1;
			printf ("Enter Your Second Number: ");
			cin >> sub2;
			printf ("\n================================================================\n");
				{
				if (sub1 > sub2)
					{
					loop3=sub1;
					loop4=sub2;
						{
						for(i=0;i<loop3;i++)
							{
							num.increment();
							}
						for(i=0;i<loop4;i++)
							{
							num.decrement();
							}
						}
							num.print();
				}
				else
				{
					loop3=sub2;
					loop4=sub1;
					{
					for(i=0;i<loop3;i++)
						{
						num.increment();
						}
					for(i=0;i<loop4;i++)
						{
						num.decrement();
						}
					}
						num.print();
				}
			}
		}
	}
	return(0);
}

December 13th, 2013

UNIX/Linux Fundamentals Lecture Journal

August 28th, 2013

First Day of Class

  1. Routers
  2. Cars
  3. Cellphones

Class Websites

An important thing introduced to the class today was the class website.

This page is important because it contains all the tasks for the semester, and it serves as a central hub for all notes in the class.

Joining IRC Server

  1. Log onto a terminal
  2. SSH Lab46 or lab46.corning-cc.edu if out of lab
  3. screen
  4. irssi
  5. /server irc
  6. /join csci
  7. /join unix

Challenges

August 30th, 2013

UNIX

UNIX is a Philosophy
  1. Small is beautiful ~ do more with less ~ hardware doesn't need to be that strong to run Linux or UNIX mostly UNIX cause of the old computers only running on a few kb of ram
  2. do one thing and do that one thing extremely well ~ example LS what does LS do it lists files extremely well ~ which is what it was designed to do. cant copy files or do anything other than what it was designed to d
  3. everything is a file in a UNIX system ( only about 90% true ) UNIX introduced the concept of io streams or data streams
IO STREAMS
  1. Standard input STDIN
  2. standard output STDOUT
  3. standard error STDER
IO redirection
  1. > redirect stdout and turn it into a write operation. write operation starts at the beginning of the file and writes on the next available lines
  2. » redirect stdout and append the file with a write operation.
  3. 2> redirect standard error Write
  4. 2» redirect standard error append
  5. < redirects standard input
File Control
lab46:~$ cat "myfilename" 
Shortcuts and Commands
lab46:~$ morse < "file name"

Thoughts and closure

September 4th, 2013

UNIX Shell Control

Commands

stuff=“things”
echo $stuff
you get “things” displayed

LS Coloration
  1. blue - directory files
  2. cyan - light blue - symbolic link
  3. red - broken symbolic link - or - compressed files
  4. magenta - bright purple - media files
  5. green - executable file
  6. yellow - special ( device ) file such as keyboard or mouse
  7. white foreground and red background - set uid set gid file
lab46:~$ pwd
lab46:~$ mkdir closet
lab46:~$ cd closet
lab46:~/closet$ 
  1. absolute path - contains the entire addresses
  2. relative path - contains a character or shorter name to represent the path to location of file or user
lab46:~/closet$ touch skeleton
lab46:~/closet$ echo "ingredients" > cake
lab46:~/closet$ echo "diamond pickaxe" >> cake

File Properties

Permissions
  1. Every file has permission settings
  2. After an ls -la, you can see what type of file a file is, and who controls it
  1. - ordinary file
  2. L - symbolic link
  3. Bc - block and character
  4. S - socket
  5. p - pipe
  1. followed by name of owner
  2. followed by group ownership
  1. r ~ read - 4
  2. w ~ write - 2
  3. x ~ execute except for a directory that means its searchable - 1
  4. - ~ no permission - 0
  5. t ~ sticky bit add on for file permissions you can write but cant delete
  6. s ~

Directory Structure

Default Directories
  1. / ~ directory known as root directory
  2. bin ~ directory means binary essential files for basic system usage
  3. dev ~ directory for devices or special files
  4. etc ~ system configuration files such as ldap ntp
  5. lib ~ libraries such as the c library at libc.so.6
  6. lib64 ~ links to lib directory
  7. lib32 ~ separate 32bit layer library considered foreign
  8. root ~ root users home directory
  9. lost+found ~ recovered files from a disk rarely used only when there is a serious hardware problem
  10. mnt ~ mount point for storage or media
  11. media ~ same as mnt
  12. opt ~ optional software or commercial vendors
  13. proc ~ information on running processes ~ has a directory for every running process
  14. sbin ~ essential tool for administrator
  15. selinux ~ security Linux extension
  16. sys ~ modern replacement of proc machine readable instead of user readable. easier for machine to reach
  17. tmp ~ TEMP FILES
  18. var ~ variety of things that fit nowhere else such as mail from lab 46
  19. usr ~ provides usr useful stuff not critical for operation, place for text editors ~ local/bin contains mods
file categories
  1. regular ordinary files ( text files mp3s movies)
  2. directory files / link files (is a file that contains other files or reference other files)
  3. special files
Thoughts on the day
  1. We learned a lot about how the subsystem in linux and unix works
  2. Knowing what the default directories were, really helped to draw a parallel to the windows environment
  3. With the lecture I was finally able to understand the meaning of chmod 777 that I use ever so much in my daily time. I know it is now read write and execute for all users. I feel silly for not knowing that.

September 6th, 2013

Shell

OS Specifics
  1. mac - finder
  2. unix - bash sh tosh csh zsh rc fish ksh ~ change shell with chsh
  3. windows - explorer
Nesting
-bash
       |_bash
                 |_bash
                           |_bash
Output Manipulation
  1. “ ~ half quite, allows variable expansion
  2. ' ~ full quote, literal quote offering no expansion - gives back exactly what you typed
  3. ` ~ back tick back-quote - allow command expansion
my example will not work in wiki syntax and crashes my opus upon saving
  1. \ “whack” - toggle special meaning of the following character ex \n newline \t tab
  2. “date” gives back date
  1. * means 0 or more of anything
  2. ? means 1 of any character
  3. [ ] character class put sequence of characters in it ~ matches all enclosed
  4. [^ ] inverted character class ~ matches none enclosed
lab46:~$ ls ????

Thoughts

September 11th, 2013

Today we learned about VI

Vi

VI Commands

these will even show up in the normal CLI with CTRL + value sometimes case of character changes command

Thoughts

Its nice to have learned a few new VI commands I didnt know before

September 13th, 2013

Bash

Today almost everything learned was pure bash la -a shows all hidden files

We made two scripts

  1 #!/bin/bash
  2 #
  3 # script1.sh - my first script
  4 #
  5 echo -n "What is your name?"
  6 read name
  7 echo "Hi, ${name} how are you?"
  8 exit 0

This asks for your name and asks how you are and

  1 #!/bin/bash
  2 #
  3 # scipt2.sh - my second script
  4 #
  5 pick=$((RANDOM%91+1))
  6     echo -n " Pick a number :"
  7 read number
  8 if [ "$pick" -eq "$number" ]; then
  9     echo "you win"
 10 elif [ "$pick" -gt "$number" ]; then
 11     echo "$pick > $number you lose"
 12 else
 13     echo "$pick < $number you lose"
 14 fi
 15 exit 0

this one is a number game that has you guess a number

September 18th, 2013

Today we learned about how processes work

Process Termination

Background and Foreground Processes

1) stopped - in the background not doing anything, not working towards finis hing its process 2) running - means the job is running in the background perfectly fine

(sleep 30;ls)& runs ls after 30

Thoughts

Its nice seeing how processes work. I have dealt with daemons before, so I understand them well enough.

September 20th, 2013

Today we learned mostly about the cat command but we also learned about a few other things

General Stuff

I am going to list it all out since it doesnt really group at all

Cat Commands

Thoughts

its fun looking at the dictionary and playing with cat

September 25th, 2013

Cli Scripting

for ((i=0;i<10;i++));do
>  echo"$i"
>  done

XTE

xte 'mousemove 0 0'
xte 'sleep 1'
xte 'mouseclick 1'
xte 'mousedown 1'
xte 'sleep 1'
xte 'mousemove 100 100'
xte 'sleep 1'
xte 'mouseup 1'
xte 'mousemove 300 250'
xte 'sleep 1'
xte 'mouseclick 1'
      1 xte 'mousemove 0 0'
      2 xte 'sleep 1'
      3 xte 'mouseclick 1'
      4 xte 'mousedown 1'
      5 xte 'sleep 1'
      6 xte 'mousemove 100 100'
      7 xte 'sleep 1'
      8 xte 'mouseup 1'
      9 xte 'mousemove 300 250'
     10 xte 'sleep 1'
     11 xte 'mouseclick 1'
     12 xte 'sleep 1'
     13 xte 'mousemove 40 110'
     14 xte 'sleep 1'
     15 xte 'mouseclick 1'
     16 xte 'sleep 1'
     17 xte 'mousemove 40 130'
     18 xte 'mouseclick 1'
     19 xte 'sleep 1'
     20 xte 'mousemove 600 110'
     21 xte 'mouseclick 1'
     22 xte 'mousemove 200 200'
     23 xte 'mouseclick 1'
     24 xte 'mousedown 1'
     25 for ((x=200;x<500;x+=50));do
     26 y=200;
     27 xte "mousemove $x $y"
     28 xte "usleep 200000"
     29 done
     30 
     31 for ((y=200;y<500;y+=50));do
     32 x=500;
     33 xte "mousemove $x $y"
     34 xte "usleep 200000"
     35 done
     36 
     37 for ((x=500;x>190;x-=50));do
     38 y=500;
     39 xte "mousemove $x $y"
     40 xte "usleep 200000"
     41 done
     42 
     43 for ((y=500;y>190;y-=50));do
     44 x=200;
     45 xte "mousemove $x $y"
     46 xte "usleep 200000"
     47 done
     48 xte "mouseup 1"

Thoughts

Xte is fun and I could see many good, and bad uses for it for torturing my clients

September 27th, 2013

      1 xte 'mousemove 200 200'
      2 xte 'mouseclick 1'
      3 xte 'mousedown 1'
      4 for ((x=200;x<360;x+=10));do
      5 y=200;
      6 xte "mousemove $x $y"
      7 xte "usleep 10000"
      8 done
      9 
     10 for ((y=200;y<344;y+=4));do
     11 x=360;
     12 xte "mousemove $x $y"
     13 xte "usleep 10000"
     14 done
     15 
     16 for ((x=360;x>200;x-=10));do
     17 y=344;
     18 xte "mousemove $x $y"
     19 xte "usleep 10000"
     20 done
     21 
     22 for ((y=344;y>196;y-=4));do
     23 x=200;
     24 xte "mousemove $x $y"
     25 xte "usleep 10000"
     26 done
     27 xte "mouseup 1"
     28 
     29 for ((x=350;x>209;x-=10));do
     30 y=340;
     31 xte "mousemove $x $y"
     32 xte "mousedown 1"
     33 xte "usleep 10000"
     34 done
     35 xte "mouseup 1"
     36 
     37 for ((x=350;x>209;x-=10));do
     38 y=339
     39 xte "mousemove $x $y"
     40 xte "mousedown 1"
     41 xte "usleep 10000"
     42 done
     43 xte "mouseup 1"
     44 
     45 for ((x=350;x>209;x-=10));do
     46 y=337
     47 xte "mousemove $x $y"
     48 xte "mousedown 1"
     49 xte "usleep 10000"

    50 done

     51 xte "mouseup 1"
     52 
     53 for ((y=335;y>302;y-=1));do
     54 x=211
     55 xte "mousemove $x $y"
     56 xte "mousedown 1"
     57 xte "usleep 10000"
     58 done
     59 xte "mouseup 1"
     60 
     61 for ((y=335;y>302;y-=1));do
     62 x=210
     63 xte "mousemove $x $y"
     64 xte "mousedown 1"
     65 xte "usleep 10000"
     66 done
     67 xte "mouseup 1"
     68 
     69 for ((y=335;y>302;y-=1));do
     70 x=208
     71 xte "mousemove $x $y"
     72 xte "mousedown 1"
     73 xte "usleep 10000"
     74 done
     75 xte "mouseup 1"
     76 
     77 for ((y=335;y>302;y-=1));do
     78 x=349
     79 xte "mousemove $x $y"
     80 xte "mousedown 1"
     81 xte "usleep 10000"
     82 done
     83 xte "mouseup 1"
     84 
     85 for ((y=335;y>302;y-=1));do
     86 x=350
     87 xte "mousemove $x $y"
     88 xte "mousedown 1"
     89 xte "usleep 10000"
     90 done
     91 xte "mouseup 1"
     92 
     93 for ((y=335;y>302;y-=1));do
     94 x=352
     95 xte "mousemove $x $y"
     96 xte "mousedown 1"
     97 xte "usleep 10000"
    98 done
     99 xte "mouseup 1"
    100 
    101 for ((x=350;x>209;x-=10));do
    102 y=300
    103 xte "mousemove $x $y"
    104 xte "mousedown 1"
    105 xte "usleep 10000"
    106 done
    107 
    108 for ((x=350;x>209;x-=10));do
    109 y=299
    110 xte "mousemove $x $y"
    111 xte "usleep 10000"
    112 done
    113 xte "mouseup 1"
    114 
    115 for ((x=342;x>268;x-=1));do
    116 y=290
    117 xte "mousemove $x $y"
    118 xte "mousedown 1"
    119 xte "usleep 10000"
    120 done
    121 xte "mouseup 1"
    122 
    123 for ((x=271;x<275;x+=1));do
    124 y=289
    125 xte "mousemove $x $y"
    126 xte "mousedown 1"
    127 xte "usleep 10000"
 128 done
    129 xte "mouseup 1"
    130 
    131 for ((x=273;x<275;x+=1));do
    132 y=288
    133 xte "mousemove $x $y"
    134 xte "mousedown 1"
    135 xte "usleep 10000"
    136 done
    137 xte "mouseup 1"
    138 
    139 for ((y=290;y>278;y-=1));do
    140 x=342
    141 xte "mousemove $x $y"
    142 xte "mousedown 1"
    143 xte "usleep 10000"
    144 done
    145 xte "mouseup 1"

October 2nd, 2013

Arrays

Loops

for((i=0; i<12; i++)); do

    echo -n "Enter scores:"

    read score

    battleexp[$i]=$score

done
total=0
for((i=0; i<12;i++)); do

    let total = $total + ${battleexp[$i]}

done

    "Your total score is $total"

October 4th, 2013

Scripts vs programs

Thoughts

This is all review from C programming

October 9th, 2013

Today was a review day

October 11th, 2013

Today was the knowledge assessment, it was fairly simple other than the last problem. The problem where we were asked to make the brute program work.

October 16th and 18th 2013

This week we worked on some bash scripts for checking if a directory exists

  1 #!/bin/bash
  2 #
  3 #
  4 #
  5 #
  6 #
  7 if [ -z "$1" ]; then
  8     echo -n "Enter a path: "
  9     read path
 10     chk=`ls $path 2>&1 | grep 'No such file'| wc -l`
 11     if [ "$chk" -eq 1 ]; then
 12     path=`pwd`
 13 fi
 14 else
 15     paths="$1"
 16 fi
 17 echo $path
 18 cd $path
 19     max=0
 20 for file in `ls -1d` * ; do
 21     c=`echo $file | wc -c`
 22     echo "c is $c"
 23     data[$c]=$((${data[$c]}+1))
 24     if [ "$max" -lt "$c" ]; then
 25         max=$c
 26     fi
 27 done
 28 for (( i=1; i<=$max; i++));do
 29         printf "%2d | " $i
 30     if [ -z "${data[$i]}" ]; then
 31         data[$i]=0
 32     fi
 33 for ((j=0;j<${data[$i]};j++)); do
 34     echo -n "*"
 35 done
 36 done

October 23rd, 2013

Today we created a script that would run a simple website using our UID as a port number

#/bin/bash
#
while true; do

    { echo -e 'HTTP/1.1 200 OK \r\n'; cat /etc/motd;} | nc -l 5836

done

We also learned about the different protocols on the internet and about error codes

October 25th, 2013

Today we learned how to cat a file, but to organize the output in a readable manner, or however we want it to be organized some examples

cat file | grep "<th class="ddtitle'
sed stream editor
cat winter2014-20131025.html | grep '^<th class="ddtitle' | sed 's/^<th class="ddtitle.*crn_in=.....">//g' | sed 's/<\/a><\/th>//g'
cat winter2014-20131025.html | grep '^<th class="ddtitle' | sed 's/^<th class="ddtitle.*crn_in=.....">//g' | sed 's/<\/a><\/th>//g' | sed 's/^\(.*\) - \(.....\) - \(.*\) - \(...\)$/\2:\3-\4:\1/g'

October 30th and November 1st, 2013

This week we continued to work on cating the course list file.

We were given a small script to mess around with

ifs=; for line in `cat consolodate`; do 
crn=`echo $line | sed 's/^.* - \(.....\) - .....*$/\1/g'
 touch $crn
 echo $line >> $crm
 done

we learned about ifs internal field separator

we were also given

cat catstuff | enhance | enhance | ENHANCE > coursedata

December 13th, 2013

UNIX/Linux Fundamentals Case Study Journal

Case Study 0x1: Archive Handling

1)

2)

Case Study 0x3: The Puzzle Box

1.

2.

Case Study 0x4: UNIX Messaging Tools

Case Study 0x5: Web Pages

1

2

Case Study 0x6: Device Files

1

2

3

4

5

6

7

Case Study 0x7: Scheduled Tasks

Case Study 0x8: Data Types in C

1

2

3

4

  1 #include <stdio.h>
  2
  3 int main()
  4 {
  5     unsigned int a, x;
   6     signed short int b, y;
  7
  8     a = 0; // zero not letter "O"
  9     b = 32767;
 10     x = a - 1;
 11     y = b + 1;
 12
 13     printf("signed short int before: %hd \t after: %hd\n", b, y);
 14
 15     return(0);
 16 }

Case Study 0x9: Fun with grep

B cat pelopwar.txt | grep coast | wc –l causes 9 matches

Case Study 0xA: Data Manipulation

Copying

Comparisons

We can compare files line by line using the diff command md5sum(1): computes an MD5 hash of a file's contents, creating a unique data fingerprint

Case Study 0xB: Groups and Security

UNIX/Linux Fundamentals Lab Journal

Lab 0x0: Introduction to UNIX/Linux and Lab46

UNIX Facts

History
General Function
  1. Word
  2. word
  3. wOrD
  4. wOrd
Connecting To The Server


login as :
password : 
MOTD
 __         _     _ _   __   . . . . . . . . . . . . . . . . . . . . . . . . .
|  |   __ _| |__ / | |_/ /   . Basic System Usage:  Type 'usage' at prompt   .
|  |__/ _` | '_ \\_  _/ _ \  . Events and News:     Type 'news' at prompt    .
|_____\__,_|_.__/  |_|\___/  . Broken E-mail?       Type 'fixmail' at prompt .
---------------------------  . Check Lab46 Mail:    Type 'alpine' at prompt  .
c o r n i n g - c c . e d u  . . . . . . . . . . . . . . . . . . . . . . . . .

 Lab46 is the Computer & Information Science Department's Student Development
 Server for Computer-related coursework, projects, and exploration.  For more
 information, please check out:
  .. .  .    .        .                .                .        .    .  . ..
 .  Lab46 Web Page:       http://lab46.corning-cc.edu/                       .
 .  Lab46 Help Form:      http://lab46.corning-cc.edu/help_request           .
 .  Help E-mail:          haas@corning-cc.edu or wedge@lab46.corning-cc.edu  .
  .. .  .    .        .                .                .        .    .  . ..
Unix Location
lab46:~$ pwd
/home/jkosty6
Unix Navigation
lab46:~$ cd src
lab46:~/src$
lab46:~/src$ pwd
/home/jkosty6/src
lab46:~/src$ cd ..
lab46:~$
lab46:~$ cd ..
lab46:/home$
Listing
lab46:~$ ls
Desktop    Downloads  Music     Public     Videos  bin     hw           src
Documents  Maildir    Pictures  Templates  a.out   closet  public_html
Creating
lab46:~$ mkdir temp
lab46:~$ mkdir bin
lab46:~$ rmdir temp
People On The System
lab46:~$ who
lab46:~$ mesg n
Mail
lab46:~$ alpine
  ALPINE 2.00   MAIN MENU               Folder: INBOX                1 Message +


          ?     HELP               -  Get help using Alpine

          C     COMPOSE MESSAGE    -  Compose and send a message

          I     MESSAGE INDEX      -  View messages in current folder

          L     FOLDER LIST        -  Select a folder to view

          A     ADDRESS BOOK       -  Update address book

          S     SETUP              -  Configure Alpine Options

          Q     QUIT               -  Leave the Alpine program




                  Copyright 2006-2008 University of Washington

? Help                     P PrevCmd                 R RelNotes
O OTHER CMDS > [Index]     N NextCmd                 K KBLock
Mailing list

Unix is a Philosophy
Terminology
  1. Strongest account on the system
  2. Typically used by the system admin
  3. has no restrictions imposed on it or protections
  1. The starting part in a subtree of a file system
  2. on lab 46 it is our folder
  1. Units of data on a filesystem
  2. Normally in 512 or 1024 byte blocks
  3. CDs use 2048 byte blocks
  4. Rare hardware sometimes uses its own blocks
  1. 1024 bytes
  2. Sometimes refereed to as a KiB
  3. Binary representation often shows it as being 1000bytes
  4. This is often the case with hard drive manufacturers who see their hard drives with 1000 multiples instead of 1024
  1. Means the system can handle multiple users at once
  2. These users can do their own commands
  3. Unix is this type of system
  1. Means a system can handle multiple tasks
  2. Means a system can handle multiple users running multiple different tasks at the same time
  1. acronym for “Mail User Agent
  2. Mail client
  3. Allows the user to send or receive email
  1. A gathering of email addresses used to create a discussion forum
  2. allows for centralized announcements relayed to people
  1. a message sent to a mailing list is called a post
  2. When you send a message yourself its called posting
  1. any string of characters that manipulate features after being typed in a prompt
Logging Off The Lab

Lab 0x1: Basic Utilities and their Manual Pages

Unix Commands

  1. list is ls
  2. copy is cp
  3. move is mv
  4. remove is rm
  5. link is ln
Listing things
lab46:~$ ls -l
-rw-r--r-- 1 jkosty6 lab46   440 Sep 13 10:15 2.00   MAIN MENU               Folder: INBOX                1 Message +
drwxr-xr-x 2 jkosty6 lab46     6 Aug 28 12:20 Desktop
drwxr-xr-x 2 jkosty6 lab46    20 Aug 29 15:28 Documents
drwxr-xr-x 2 jkosty6 lab46     6 Aug 28 12:20 Downloads
lrwxrwxrwx 1 jkosty6 lab46    17 Aug 25 11:56 Maildir -> /var/mail/jkosty6
drwxr-xr-x 2 jkosty6 lab46     6 Aug 28 12:20 Music
drwxr-xr-x 2 jkosty6 lab46     6 Aug 28 12:20 Pictures
drwxr-xr-x 2 jkosty6 lab46     6 Aug 28 12:20 Public
drwxr-xr-x 2 jkosty6 lab46     6 Aug 28 12:20 Templates
drwxr-xr-x 2 jkosty6 lab46     6 Aug 28 12:20 Videos
-rwxr-xr-x 1 jkosty6 lab46  6561 Aug 29 16:34 a.out
drwxr-xr-x 2 jkosty6 lab46     6 Sep  3 08:57 bin
drwxr-xr-x 3 jkosty6 lab46    46 Sep  4 15:37 closet
-rwxr-xr-x 1 jkosty6 lab46 16638 Aug 29 16:42 hw
drwx-----x 2 jkosty6 lab46     6 Aug 26  2009 public_html
drwx------ 6 jkosty6 lab46    83 Sep 13 16:35 src
lab46:~$
-rwxr-xr-x 1 root root  119288 Apr 21  2010 grep
-rwxr-xr-x 1 root root   52288 Apr 28  2010 cat
Copying Things
lab46:~$ cp (directory and file name of target)
lab46:~$ cp (original copy name SPACE duplicate name)
Moving Things
lab46:~$ mv (file name) (directory destination)
lab46:~$ mv (old file name) (new file name)
Removing things
lab46:~$ rm (filename)
lab46:~$ ln [-s] (target file) (shortcut file)

Manuals

Lab 0x2: Files and Directories

Unix File System

Master Directories
  1. / - Root, the lowest you can go on a system, it is the base or foundation for the entire OS
  2. bin - Essential basic tools for normal system usage
  3. etc - the systems configuration files
  4. home - directory location of the system user files
  5. lib, lib64, lib32 - system libraries very important and can be different depending on the architecture of your system
  6. mnt - place where file systems get mounted such as hard drives
  7. root - the administrator or super users folder
  8. sbin - necessary system admin utilities
  9. tmp - Temporary directory
  10. usr - Additional (secondary) system functionality & userspace tools
  11. var - Misc. items that have no place such as mail
lab46:~$ cd /
lab46:/$
lab46:/$ ls
bin   etc         lib    lost+found  opt   sbin     sys  var
boot  home        lib32  media       proc  selinux  tmp  vmlinuz
dev   initrd.img  lib64  mnt         root  srv      usr
lab46:/$
Home Directory
lab46:/home$ cd /
lab46:/$ cd home
lab46:/home$ cd jkosty6
lab46:~$
Working Directory
Path-names
  1. Absolute - The exact location in the file system - the pwd command returns this
  2. Relative - The exact location on the file system is unknown and only comparable to the specific location
Extra Navigation
Files
  1. Regular Files - Text and executable files
  2. Directories - A file that points to other files
  3. Special Files - Devices and network specific items
  1. user - the owner of the file
  2. group - the group that owns a file
  3. other - everyone else
  1. read
  2. write
  3. execute
  1. read 4 r view / read the file
  2. write 2 w save / create / modify / delete the file
  3. execute / search 1 x run / parse through contents of a file

Lab 0x3: Text Processing

Cat Command

lab46:~$ cd /etc
lab46:/etc$ cat motd
 __         _     _ _   __   . . . . . . . . . . . . . . . . . . . . . . . . .
|  |   __ _| |__ / | |_/ /   . Basic System Usage:  Type 'usage' at prompt   .
|  |__/ _` | '_ \\_  _/ _ \  . Events and News:     Type 'news' at prompt    .
|_____\__,_|_.__/  |_|\___/  . Broken E-mail?       Type 'fixmail' at prompt .
---------------------------  . Check Lab46 Mail:    Type 'alpine' at prompt  .
c o r n i n g - c c . e d u  . . . . . . . . . . . . . . . . . . . . . . . . .

 Lab46 is the Computer & Information Science Department's Student Development
 Server for Computer-related coursework, projects, and exploration.  For more
 information, please check out:
  .. .  .    .        .                .                .        .    .  . ..
 .  Lab46 Web Page:       http://lab46.corning-cc.edu/                       .
 .  Lab46 Help Form:      http://lab46.corning-cc.edu/help_request           .
 .  Help E-mail:          haas@corning-cc.edu or wedge@lab46.corning-cc.edu  .
  .. .  .    .        .                .                .        .    .  . ..

Other Commands

lab46:/etc$ wc passwd
  27   32 1135 passwd
lab46:/etc$ wc -l passwd
27 passwd

VI Commands

Lab 0x4: UNIX Shell Basics

Background

Operating Systems
  1. Kernel - the core of the OS. It handles everything- manages I/O, etc.
  2. Drivers - components that instruct the kernel how to function or deal with a piece of hardware.
  3. Userspace - non-kernel level. System applications, utilities, files. Users exist here, hence the name “user space”
Userspace
  1. interactive use
  2. customization
  3. programming
Control Characters
Control Code 	System Code 	Description
CTRL-C 	INTR 	interrupt
CTRL-D 	EOF 	issue end of file character
CTRL-G 		sound bell
CTRL-H 	BS 	send backspace
CTRL-J 	LF 	send linefeed
CTRL-L 		refresh screen
CTRL-M 	CR 	send carriage return
CTRL-Q 	XON 	start code*
CTRL-S 	XOFF 	stop code*
CTRL-V 		escape the following character
CTRL-Z 	SUSPEND 	suspend current job
CTRL-[ 	ESC 	send escape character 
Dot files

In unix there are hidden files called dotfiles, and used on login or for configuration purposes

dotfile 	description
.bash_profile 	The first personal initialization file bash searches
.bashrc 	Session personalization file called by .bash_profile
.cshrc   	A personal initialization file for the csh/tcsh shells
.exrc 	        A configuration file for vi/ex
.signature 	Text file containing a signature banner for e-mail
.plan 	        A personal banner file that is displayed on finger(1) lookups
.forward 	A file used in automatic e-mail forwarding
.pinerc 	A configuration file for pine
.vimrc  	A configuration file for vim 
  1 I see pokemon
  2 John Kosty
  3 C / C++ and UNIX
Environment Values
  1. $PATH
  2. $HOSTNAME
  3. $USER
  4. $TERM
  5. $SHELL
history
Tab completions
Conclusions

Its nice review on how to use the command line's more unique features

Lab 0x5: More UNIX Shell Explorations

Wild Cards

Symbol 	Description
* 	match 0 or more characters
? 	match exactly one character
[ ] 	character class - match any of the enclosed characters.
[^ ] 	inverted character class - do not match any of the enclosed characters.

IO Redirection

Symbol 	Description
> 	STDOUT redirection operator
>> 	STDOUT append redirection operator
< 	STDIN redirection operator
2> 	STDERR redirection operator
2>> 	STDERR append redirection operator
| 	pipe 

Pagers

Quotes

Symbol 	Name 	Description
` 	backquote 	                command expansion
' 	single (or full) quote 	        literal quote, no expansion
" 	double (or partial) quote 	variable expansion 

===Conclusions===
Nice review from C

Lab 0x6: Shell Scripting Concepts

Running a script

We were told to make a script with this inside of it

ls ~
df
who

if we try to run it using (dot slash) it will say we lack the permission.

  1. We can view the permissions on the file by doing ls -la script1.sh
  2. The owner has read and write. The user has read. Global has read
  3. We can use chmod to change the permissions on the file to what we would like
  4. chmod 777 script1.sh
  5. The script works

Philosophy

Anything that you can type on the command line can be added to the script

Simple I/O

There are two easy ways to do IO

echo "What is your birth year?"
read birth
currentday=$(date | awk ' {print $6}')
let output=$currentday-$birth
echo $output

Shabang

Selection

#!/bin/bash
 
echo -n "Pick a number: "
read num1
 
echo -n "Pick another number: "
read num2
if [ "$num1" -lt "$num2" ]; then
    echo "$num2 is greater than $num1"
fi
if [ "$num1" -lt "$num2" ]; then
    echo "$num2 is greater than $num1"
elif [ "$num2" -lt "$num1" ]; then
    echo "$num1 is greater than $num2"
fi
if [ "$num1" -lt "$num2" ]; then
    echo "$num2 is greater than $num1"
elif [ "$num2" -lt "$num1" ]; then
    echo "$num1 is greater than $num2"
else
    echo "$num1 and $num2 are equal in value"
fi

* we can make a program that asks for a number and generates a random number to guess against.

#!/bin/bash
pick=$(($RANDOM % 20))
echo "Pick a number between 1 and 20"
end=4
counter=0
while [ "$counter" -lt "4" ]; do
read picked
    if [ "$pick" -eq "$picked" ]; then
        echo "$picked is the number!"
        exit
    elif [ "$pick" -lt "$picked" ]; then
        echo "$picked is greater than the number!"
        let counter=counter+1
    elif [ "$pick" -gt "$picked" ]; then
        echo "$picked is less than the number!"
        let counter=counter+1
    fi
done

iteration

  1. Starting condition
  2. a loop until condition
  3. and a method to get there
#!/bin/bash

for((i=1; i<=10; i++)); do
    printf "$i "
done

prints the provided script without newline

#!/bin/bash

for((i=20; i>=2; i--)); do
    printf "$i "
done

steps backwards from 20 to 2

in the provided list based for loop

The loop goes 8 times The fifth time through the color is blue

echo -n "First color is: "
for color in red orange yellow green blue indigo violet; do
if [ "$color" == "indigo" ]; then
    echo "$color"
    echo -n "The last color is: "
elif [ "$color" == "violet" ]; then
    echo "$color"
    exit
else
    echo "$color"
    echo -n "Next color is: "
fi
done

is my modified code

echo "Give me a number"
read number
echo $number > file$number

the code to create file with number

#!/bin/bash
printf "Please enterdirector to process: "
read directory
printf "Processing ...\n\n"
echo "Directory: $directory"
cd "$directory"
filecount=$(ls -la | wc -l)
if [ "$filecount" -gt "60" ]; then
    filecount=60
fi
echo "Total Files: $filecount"

Lab 0x7: Job Control and Multitasking

Viewing Processes

* We learned about multitasking * we can see the running processes with PS command * this works with

lab46:~$ ps
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
jkosty6  11177  0.4  0.1  13644  2004 pts/24   SNs  23:20   0:00 -bash
jkosty6  11206  8.0  0.0   8588   988 pts/24   RN+  23:23   0:00 ps u

* we can see our processes in other shells using the same

ps -e lists all processes on the system

Running in the background

using & you can instruct a command to run in the background The count file is a C file You can determine this with the file command gcc -o count count.c ./count

output is

real 0m36.795s user 0m35.482s sys 0m0.608s

adding an & to it runs it in the background

The Command Separator

We can use the semicolon as a command seperator to so that once the first command is done the second one executes

Task 1

sleep 8 ; ls /var > multitask.lab.txt &

Task 2

you cant log out cause tasks are stopped this might be incase you dont want to terminate the jobs you can keep running them

the links job is number 2

bringing it to foreground caused error

moving it back to background worked

fg 1 foregrounded cat

cat is gone all jobs gone

Kill

We can kill processes using kill 8 kill -l a 1 b 34 c 9 d 2

jkosty6 + pts/55 2013-12-12 15:35 . 3574 (cpe-69-204-219-21.stny.res.rr.com) jkosty6 + pts/82 2013-12-12 11:25 . 24306 (cpe-69-204-219-21.stny.res.rr.com)

dev/pts/82 dev/pts/55

kill -9 24369

killed pts/82

no messages at all just closed putty

no longer logged in twice

Applying skills

ps -e | grep statd the PID of init is 1 root own cron 1190 is pid cron is a task scheduler

Lab 0x8: The UNIX Programming Environment

GNU C compiler

We can compile a file with gcc -o output input.c

GNU C++ Compiler

g++ -o output input.cc We can compile with this

GNU Assembler

to assemble an assembly file we can do as -o outpout.o input.s to run it on the system we need to do ld -o binary object.o

Prodedure

copied over the files compiled them with

as -o helloASM.o helloASM.S ld -o helloASM helloASM.o

gcc -o helloC helloC.c

g++ -o helloCPP helloCPP.cc

Executing it

If we run it without a ./ it will fail to run saying command not found with ./ it executes it from the current directory, so it works

Putting back together

helloC.c is a ASCII C Program Text file helloASM.S is a ASCII assembler program test file helloCPP.cc is a ASCII C++ Program text file

if we compile with gcc -S helloC.c it turns it into assembly and an assembly file when we cat or VI the file we can see that it is pure assembly

if we type as -o hello.o helloC.s it creates an ELF 64bit LSB relocatable x86-64 sysv not stripped it seems to have been turned into an object form of the S file

Make Files

You can run make files to deal with multiple source files that need compiling at once

Lab 0x9: Pattern Matching with Regular Expressions

Procedure

We can use the grep command to narrow down our results in files cat /etc/passwd | grep System would limit it to only lines with system

lab46:~$ cat /etc/passwd | grep '^[jpk]' proxy:x:13:13:proxy:/bin:/bin/sh

cat regex.html | sed 's/<centre>/<center>/g' | sed 's/<\/CENTRE>/<\/center>/g' | sed 's/<b>/<strong>/g' | sed 's/<\/b>/<\/strong>/g'

cd /etc/dictionaries-common/ found it using ls -la and looking at the link seems to be just a text file with all the words 98569 words and you get it with cat words | wc -l

  1. 5 character length cat words | grep “^…..$”
  2. all words starting with jpk cat words | grep “^[JPKjpk]”
  3. first begining middle middle last last cat words | grep “^[jJ].*[pP].*[kK]$”
  4. begin and end with vowel cat words | grep “^[aeiouy].*[aeiouy]$”
  5. begin initial vowel second est last cat words | grep “^[jJpPkK][aeiouy].*[est]$”
  6. dont start with initial cat words | grep “^[^jJpPkK]”
  7. all 3 letter words ending in e cat words | egrep '^..[e]$'
  8. contain bob not ending in b cat words | grep 'bob.*[^b]$'
  9. all words starting with blue cat words | grep '^blue'
  10. contains no vowels cat words | grep '^[^aeiouyAEIOUY]*$'
  11. dont begin vowel. second letter anything. third abcd ends in vowel cat words | grep '^[^aeiouyAEIOUY].[abcd]*[aeiouyAEIOUY]$'

Lab 0xA: Data Analysis with Regular Expressions and Scripting

Obtaining data

cp /var/public/unix/courselist/fall2011-20110417.html.gz .

72355

gzip compressed file

gunzip fall2011-20110417.html.gz

2427432

98%

Raw Data

you use the slash then search parameter

most of them have the same filler junk around them

Isolating

cat fall2011-20110417.html | grep crn

yes it does

yes

Filtering unessessary

cat fall2011-20110417.html | grep crn | sed 's/<th class="ddtitle" scope="colgroup"><a href="https:\/\/.*crn_in=.....">//g'

cat fall2011-20110417.html | grep crn | sed 's/<th class="ddtitle" scope="colgroup"><a href="https:\/\/.*crn_in=.....">//g' | sed 's/<\/a>.*$//g' | awk '{print $1}' | uniq | wc -l 348

Lab 0xB: Filters

Today the lab was about filters. * We can get the Standard output of a file by catting it * We can pipe the file with wc -l to count the lines in the file

Keyword Filtering

* We can filter out all lines in a file by piping it with grep “keyword” * we can filter out all lines in a file by piping it twice to see if both lines contain something cat “filename” | grep “keyword” | grep “keyword”

To find students that are freshmen

Filter Manipulation

lab46:~$ echo "hello there:this:is:a:bunch of:text." | cut -d":" -f1,6
hello there:text.

Sed

lab46:~$ echo "hello there:this:is:a:bunch of:text." | cut -d":" -f1,6 | sed -e 's/:/ /g' | sed -e 's/t/T/g'
"hello there:this:is:a:bunch of:text." | cut -d":" -f1,6 | sed -e 's/:/ /g' | sed -e 's/\./\*/g'

Head and tail

Procedure