Saturday, December 26, 2015

Taking an Array From Both Ends.

Warning. This post about arrays has no filter()!

 I love to manipulate arrays into doing my bidding, break 'em down, twist them to my will. It gives me a dirty thrill to take an array back to my homepage and push() in to it, Pop() a couple datum off its ass, then bring my neighbor Cat over and concat() into inserting herself into the situation.

Then after a <br>

...when the array starts to relax, thinks I've finished, I unshift("gears"), shove my data in its face, and when the array has taken all the data I have to give, I grab my [] cutter and  splice(n, 2, "it my initials", "ever so gently"). When the array winces, I offer it something to numb the pain then I join() it and we both lay on the floor, panting, strung out.

...If that passage didn't get arrays out of you, then maybe you need some hard facts about dealing with arrays to get your blood pumping.

Push:
Pushing is like doin' it doggy style with an array. i.e. Push shoves a new item (or items) into the back of an array.

syntax: array.push(newItem1 [, newItem2, etc]);
* anything inside of [within my examples indicates optional arguments... you shouldn't actually put square brackets in a functions arguments ]

NOTE, when you push to an array, you are changing the original array, so once you push to an array, you will only be able to reference the new, manipulated array.   

Also note, pushing an entire array (or arrays) into an existing array will not insert the contents of the inserted array, but will rather, create a multidimensional array… and if you are viewing multidimensional arrays in Google dev Tools, the data is truncated, but details of the contents of the internal arrays can be viewed by clicking on the arrow beside them.

 


Pop:
Popin’ a cap off in someone’s ass works exactly like poppin’ an item off of an array (where the array is the chamber of yo’ “gun” and the data is the “bullet” you just fired) well kinda… pop removes the last item from an array.
syntax: array.pop();

note —like push, you are manipulating the original array. However, unlike push, the parenthesis are left empty because you can only pop off one item from an array at a time.


Unshift:
If you want to shove data into an arrays face, use unshift. Unshift does to the 0th end of an array everything that push does to the array.length end of an array.
syntax: array.unshift(newItem1 [, newItem2, etc]);

note: an array can contain any combination of any type of data (strings, numbers, objects, etc)

syntax: array.unshift(item1 [item2, etc])


Shift:
Shifting data out of an array is like when you have a line of lovers before you and you don’t like the look of the one in front, so you ask that one to shift to one side and let the next one move to the front… except with an array rather than just shifting aside, you remove the item entirely. i.e. shift is like pop, but the item from the front of the array is remove rather than the item from the back. 

syntax: array.shift();


Slice:
Going back to the line of lovers. If there are one or two particularly enticing prospects in the middle of your line and you want to yank them out and deal with them privately before putting them back in line, you’d want to slice them out. Slice is a method that takes 2 arguments, the first of which is the index of the first item you wish to remove and the second argument is the position that follows the last item you want to remove. Slicing from an array removes items, but does not mutate the original array. So if you wish to reference the removed items in the future you should set them equal to a variable. NOTE if you only give one argument, slice will begin from the 0 index and slice items up to (but not including) the index you have given .

syntax: var sliced = array.slice([indexOfItem1,] indexAfterLastItem);

Splice:
If you’ve got some fuglies in your line and you just want them gone and put somewhere else, you can splice them out — and if you wish, you can splice in one or more replacements into the line. The splice method takes at least 2 arguments. The first is the index of the first item you wish to remove and the second argument is the total number of items you want to remove. If you are splicing IN to the array, you can add an additional argument for each item you would like to splice into the array. If you wish TO ADD ONLY (but not remove from the array), your second argument should be 0. Splicing mutates the original array, and you can also set a variable equal to the splice method you are calling to create a separate array containing any items you spliced out. NOTE If you put only one argument, all items after the first given index will be removed.

syntax: [var spliced =] array.splice(indexToBeginSplicing, numberOfItemsToSpliceOut [AdditionalitemsToSpliceIn]); 



Concat:

Like the story at the beginning of this blog post if you want to get inside two arrays at once, you have to concat. Because when you concat two arrays, the contents of the second array are inserted into the back of the first array.

note concat does not mutate the original array, so if you wish to reference the concatenated array in the future you must set a variable equal to the concatenated array.

syntax: var concatedArray = array1.concat(array2)
 














Friday, December 25, 2015

Searching For a True Match

Sometimes I just can't be bothered to deal with bullshit. When something isn't meeting my needs, I don't have time to fuck around with it. If (!"My boyfriend knows how to hit my g-spot") || "does my ass look good in these jeans" != true), then my boyfriend better figure out how to bang that ! out of that equation and I need to iterate through some more jeans before I execute buyThesePants(). Fortunately for these type of conundrums, there are a few particularly handy JS methods to sort through your data.

Filter: 
Allows you to insert each item from an array into a function that returns a boolean. If shoving the item into the function elicits a return value of "true" , then that item , along with any other truth-returning items from the original array, are inserted into a new array which becomes the return value of the filter.

syntax:var filteredArray = [array of data].filter(PUT BOOLEAN FUNCTION BETWEEN THESE PARENTHESIS);

example:
Holly, a scarlet-haired astrophysicist with a schedule even tighter than her waist line,  decided that it was time to stop playing the field and find a man to with whom she could start a family. Keen to keep her gene-pool as gingery fresh as possible, she decided to throw together a quick API to scrape data from hot-n-both-red.com, redI.com and crimsonlovers.com that would return the profiles of only the men that she deems to be desirable mates (ie 6'3 or taller, dog lovers making 65k minimum salary in a science related field). Below is an excerpt of some of the data she scraped:

var scrappedProfiles = [
 {name: "Dr Sex Panther", heightInCm: 160 , age: 35, income: 150000, profession: "Doctor", hobbies: "searching for my soul mate", pets: "has cats / likes dogs and cats", motto: "Trust me, I'm a doctor" },

{name:  "DJ Swizzle Stick", heightInCm: 175,  age: 25, income: 35000, profession: "valet",  hobbies: "gangsta rap, football, hunnies",  pets: "has cats / likes dogs and cats", motto: "I got 99 problems, but I'd like one more"},  
{name: "big D", heightInCm: 26 , age: 69, income: "mypenis", profession: "gigolo", hobbies: "blow, blowin', gettin' blown", pets: "yes I do", motto: "fuck bitches get money" },
{name: "Zenith", heightInCm: 185,  age: 25, income: 55000, profession: "Astronomy research", hobbies: "fishing, camping, walking my dogs",  pets: "has dogs / likes dogs", motto: "stay away from the dark side"}
];


After looking at the shape of the data, Holly designed the following filter that employed regex to search for certain key words in her prospective suitors profession and pet info as well as an assessment of the numerical value of their height and income. 

function dateable(profileObject){
  if( profileObject.income >= 65000 &&  profileObject.heightInCm >= 190 && profileObject.pets.search("dog") != -1     && profileObject.profession.search(/astro|doctor|sci|engineer|research|bio|chem|dev/i) != -1 ){
      return true;
  }
  return false;
}

var results = scrappedProfiles.filter(dateable);


Some:Checks to see if any individual items in an array meets the criteria of a given boolean and then returns true only if at least one item returns true when plugged into the boolean function. Some will return false only if there are no items within the array that meet the condition defined in the boolean function.

syntax:var filteredArray = [array of data].filter(PUT BOOLEAN FUNCTION BETWEEN THESE PARENTHESIS);

example: Frustrated that she was not getting any results back from her dating profile scraper. Holly, decided to broaden her search to include more sites (even some with men with less-favorable hair pigmentation). Not wishing to buy a membership to a site unless it contained some men that met her criteria, Holly modified her original function and ran it on prospective web sites:

function dateable(profileObject){
  if( profileObject.income >= 65000 &&  profileObject.heightInCm >= 190 && profileObject.pets.search("dog") != -1     && profileObject.profession.search(/astro|doctor|sci|engineer|research|bio|chem|dev/i) != -1 ){
      return true;
  }
  return false;
}

var useableSite = scrappedProfiles.some(dateable);

Every: 
Checks to see if all individual items in an array meet the criteria of a given boolean and then returns true only if every single item in the array gets a true result from the boolean or returns false if any of the items return false when plugged into the boolean function.

syntax:
var filteredArray = [array of data].every(PUT BOOLEAN FUNCTION BETWEEN THESE PARENTHESIS);


example:Once Holly had a few sites that she knew contained good prospects, she decided to apply one last function before joining a site. She wrote the below to search through the contents of each field on a user's profile and identify any disparaging language towards women.

function respectful(profileObject){
   var foulLanguage = [];
  
 Object.keys(profileObject).forEach(function(item, index){

  var value = profileObject[item]

 if(value.toString().search(/bitch|sukeban|whore|skintern|cunt|bobby soxer/i) != -1){
      foulLanguage.push(profileObject[item])
  }
       
})
   if (foulLanguage.length === 0 ){
      return true;
    }
  
  return false; 
  }

var useableSite = scrappedProfiles.every(respectful);





Sunday, November 22, 2015

Angular, The Portal To Another World


You know that portal that opens up in 85% of modern SciFi TV shows... the one where you jump into it in one place and are spat out somewhere very far from there, well Angular JS is like that, but instead of connecting one geographic location to another, it connects a place on your HTML file to a place on your JS file.

SETTING UP ANGULAR: 
In order to use Angular, when you set up your HTML, you should script Angular into the head of the HTML doc, above your custom JS script tag.

NG-APP
You then need to insert an ng-app into your page. You can choose to use Angular in your entire page, or just a portion of it. If you would like to use it in the entire page, type ng-app= "NAMEoFaPP" inside the HTML tag.


If you would like Angular to apply later on in your page then enclose the ng-app... inside the div containing the region of your page where you would like to use angular.

On your main JS you need to define your module (app) by  passing a name as its first argument and a blank array -- or an array containing any additional dependencies you would like to make use of in your app eg other modules you want to have access to within this app).

EMBEDDED APPS/ CONTROLLERS:
The next step is to set up an embedded app and/or a controller to specify the content and functions that you want to use in a given region of your page. You can set up a run function and reference the "view" (ie rendered html) by referencing the $rootScope. Anything contained within the html (or whichever tag you put your ng-app), is contained within the rootScope.

To delegate control over specific regions of your page, you must set up controllers. Controllers can access the view region of the page where they are named as controller, by referencing $scope.VariableToBeUsedInThatRegion.

Within the controller you can define functions that you will be able to employ and reference in the HTML.

MODELS AND PORTALS
To plug data from the main JS directly into a region of the page that is controlled by a particular controller, you can set up an element as an ng-model and name a variable to correspond to that model (so that you can reference the element from inside the controller in your JS file which contains that model ) And you can also reference declared models within the HTML itself by using double curly braces to surround the name of the model you are referencing: {{person.name}} ***Note you can only plug in strings here.

The best demonstration of the Science-Fantasy-Awesomeness of Angular is setting up double-data-binding (you can also set up triple-data-binding if you are connecting your app to a real-time server (eg firebase)... but before we can think about tying up a third data source and bringing her into bed, lets get a two way hook up going.

To bind data two ways just have your main JS reference the variable for your model in the scope... and watch the magic happen:





You can change text on one part of your page, while typing in another part of your page... and at the same time you are also changing the value on your js page as well... just like that.

To learn more about the crazy awesome power of Angular... read the AngularJS Docs, or do a tutorial.

Saturday, November 14, 2015

Little Homepage on the Web Search Query


Ever since the first time my mom read me Little House on the Prairie, I've wanted to build my own home. A log cabin with a fire place and a vegetable garden... I wanted a simple life where I could plant carrots, milk my goat and churn some mother fuckin' butter.

But the older I get, the more I wonder if I'll ever get a chance to build my tounge-in-groove, secret-passage-between-the-walls-that-leads-down-to-the-sex-dungeon, chicken-coop-havin' dream home. Fuck-it though, Imma keep saving up for a plot of land and some live stock, but in the mean time , just on the off chance that the physical house doesn't happen, I'm going to build a website...a simple webiste... about building a house... and I'm going to make it from bare HTML up...

These are the materials I will be working with:
HTML -the frame that supports casa de website. Throughout the page there are elements enclosed in tags in which you can enclose text, images, video etc. CSS adds personal flare to your site. You can need to link your HTML file to a CSS file to control the way elements are styled. CSS can change everything from text color and size to alignment of objects and opacity. CSS is important to make a website presentable, but it is not required. You can still run a website without CSS. If you want to make your website dynamic and/or interactive, you need to link it to a javascript file. Javascript is like the running water, heater, and electricity. With Javascript you can animate, re-style and personalize your site for every user.

Step 0: Download a text editor and emmet.io It is not necessary, strictly speaking, to have a special text editor to build a web site. Any plain text editor (note pad, text edit etc) can assign a file a .html,  .css or .js file extension which is all that is necessary for a browser to identify that the file contains code. However, a text editor is like the power tools of web developing... you can get by with a hammer and nails, but you probably aren't going to get around to building a sex dungeon without at least a power drill.  Text editors  greatly help with formatting and alerting you of syntactical errors (such as open parenthesis, missed commas etc). I use sublime which is free (though occasionally you do get pop ups -- which you can ignore, imploring you to purchase the official version of Sublime... its the same in every way except you wont get pop ups any more). Emmet is that guy down the street that works construction and has his own bob cat that he'll bring over to help you trench out your foundation... ie takes the ease and error prevention of text editors one step further by allowing you to abbreviate tags, assignment of classes etc. I highly recommend you download and learn the basics of emmet.


Step 1: layout HTML:
   I want to have a site where I can drag slices of a picture of a cabin onto a mat that will grab them when I drag them over it. I sliced my picture into 4 pieces, but I will want to keep them all together when you first open the site, so I put all the slices of the image in to a div. I have another div that will be the drop target for the pictures and then I wrapped the entire page in a div so I can keep everything aligned the way I like.



Step 2:
set up some CSS
There are many templates, libraries and other resources to do the brunt work of CSS and make alignment etc much easier for your page. A couple popular ones are Bootstrap and foundation both of these require that you have jQuery scripted to your page, but my page is very simple so I am not using anything beyond basic CSS.


Step 3:
JavaScript

Drag and drop are features of the jQuery ui library. The only coding necessary to drag and drop elements is the jQuery to identify what is draggable and what is droppable and specify the behavior you would like upon dropping the element.


step 4: going live
1. create a git repository for your files.
2. make sure that all your files are saved.
3. create a new git branch called gh-pages (git checkout -b gh-pages)
4. push to your gh-page (git push origin gh-pages)
5. go to your git hub page -to the settings for your repository and find the url for your new website

checkout Github and read up on my blog about git hub.

Finished product

Below are some resources to learn more about HTML, CSS, JavaScript, jQuery: https://jquery.com/
Code School jQuery, Code Academy jQUery,  W3Schools HTML/CSS, Code Academy HTML/CSS, Code School HTML / CSS, Official MDN Javascript docs, W3Schools Javascript, Code School Javascript 

Monday, November 9, 2015

Teaching a New Browser Old Tricks

Up until today every time I pulled input from a user that input would only exist as long as the page was not refreshed.As soon I clicked the refresh button my code would swirl down into the sewer of code of unsaved data that exists in the DOM.

My mind was blown last week when i learned about the wizardry that is session storage and local storage. Your browser can remember data from refreshes and even browser accesses past.

WHAT IS SESSION STORAGE?
Each website has its own storage space where you can save information that you will need access for longer than just one refresh of the page. When you save data as session storage it persists (remains in storage) until you close the browser tab or window. (It will not be passed on to new tabs or windows). Once you close the tab it is deleted.

This might be useful for a simple game where you have a limited number of tries at a task and wanted to be able to refresh the page to set you back to the previous try or close the tab to entirely restart. It may also be helpful for a survey or other nonsensitive document, where you want to be able to keep the info you've already filled out and saved, but clear the rest with a refresh.

syntax for saving to session storage:
sessionStorage.variable = value;
(the value can be a number, string, array, or object that has been converted into a string).
to remove an item from session storage:
sessionStorage.removeItem("name of session Storage variable you want to remove");
to clear all out of local storage:
window.sessionStorage.clear();


to view session storage: 
in Chrome dev tools you can view what is stored in your session storage by going to the resources tab  at the top of the tools and then when you're in the resources tab, on the left side select Session Storage and you should be able to see the variables (keys) and their values that are being stored.



WHAT IS LOCAL STORAGE?
Local storage works much the same as session storage, except that data saved in localStorage persists until it is removed , either through dev tools console or through a script that is being run on the page. (ie closing tabs, refreshing browser, shutting down computer etc will not remove it, the browser must be told to remove the data.) Below the two variables test 1 were assigned. Once the browser was closed and reopened the local storage variable persisted, but the sessionStorage was cleared.




to view session storage: in Chrome dev tools you can view what is stored in your session storage by going to the resources tab  at the top of the tools and then when you're in the resources tab, on the left side select Session Storage and you should be able to see the variables (keys) and their values that are being stored.









JSON
*** Local storage and Session storage store all data as a string ***

So if you save a number to local storage it will be converted into a string, so if you were to try to add it to another number it would concatenate the string instead of actually preforming math...



the solution to this is to use JSON.stringify to convert the data into a string before you save it  and then use JSON.parse to convert it back to its original format so that you can work with it. (if you are only saving a single string, it is sufficient to just put the string in quotes without bringin JSON into it.

NOTE: you cannot stringify a function.

read more about JSON.

GET YOUR HANDS DIRTY:
-try this go to your browser and open the dev tools on an empty page and type localStorage.bgColor = "red."
-Then refresh the page and type localStorage.bgColor ... it will console log red... because it remembers.
-Now that variable bg.Color will be red until it is changed manually OR until code for that page is run that changes it.
- If you link a javascript file to your index page and just type:
document.body.style.backgroundColor = localStorage.bgColor;
then refresh your browser, BAM! Your page is now a sexy fire engine red. 

Sunday, November 8, 2015

Let Me Re Iterator That


Iterators are handy tools that make looping through an array of data quicker than traditional for or while loops. The javascript iterators, map, reduce and forEach all employ an anonymous function that has three arguments built in: item, index and all.

Item references the current item in the array being operated on.

Index is the index of the item in the array that is being iterated through. (eg the first item in the array would have an index of 0).

All is the array itself.

MAP.map will go through every item in an array, preform some code on it and return a new array of THE EXACT SAME SIZE.

syntax:

var mappedArray= array.map(function(item, index, all){

   preform some operation to every item in array and return a new array with every item as the item       has been transformed by your code.

  return item OR all OR a variable you create or whatever.
})

You must always write a return statement at the bottom of your array (or else it will just be an empty array).

Examples of when to use this:
if you have a string of text and you want to manipulate each word or each letter (eg change certain letters to caps or if you want to add a certain number to each existing number in an array of numbers.

example: 
Johnny is making a database to keep track of each of the gentleman callers that visit his mom late at night. He wants to be able to add information to their profiles as he gets to know them better. Recently he found out that his mom only dates guys that are 27 years old, so he writes the following program.

var momsHarem = [{Name: Bruce, VisitsOn: [Wed]}, {Name: Clark, VisitsOn: [Wed,Friday]}, {Name: Tony, VisitsOn: []}]

function addToHarem(array) {
var newArray = array.map(function(item, index, all){
   item.age = 27;
console.log(item);
       
      return item;
 
})
  return newArray
}
addToHarem(momsHarem)

FOR EACH.forEach will go through every element in an array and will allow you to present some condition or not that will affect which items in the array are manipulated. If you want an array of the exact same size it is probably better to just use map, but for each can also be used.

syntax: 

array.forEach(function(item, index, all){

if (item MEETS SOME CONDITION) {

preform some code on the item and or index or whatever
}
  manipulatedArray.push
 OR
 $("#id").text(manipulated item from array)
OR
whatever else you wanna do
 })

example: 
Abhi has an extensive library of  things that sparkle, so he keeps the information about the items in a database. He wants to be able to search for particular theme or title and have the results returned in an array, so he writes the following function:
thingsThatSparkle = [{item: "glitter", location: "lv69", subGenres: "crafts shimmer"}, {item: "new penny", location: "fm11", subGenres: "coin glint"} ]

function findShinys(array, value){
  var results =[]

  thingsThatSparkle.forEach(function(item, index, all){
  var keyValue = item.subGenres
console.log(keyValue)
   if ( keyValue.indexOf(value) > -1) {
       results.push(item)
    }
  })
  return results;
}
console.log(findShinys(thingsThatSparkle, "glint"))

findUserInfo("a", array)

forEach does not return a value so to get info out you will need to push to an array or print to document or something along those lines to have the results of the loop show up.

when to use it:
if you want to do something to eliminate the odd numbers from an array OR send just the first 3 items to an array and do nothing with or do something else with the rest of the items. OR add a class to only the items that contain the letter B or whatever it is that you want to sort out one thing from another or eliminate items from an array.

REDUCE
.reduce will go through each item in an array and return a single value. So if you want to take an array of letters and return a single item rather than an array. Reduce also has an additional argument in front of these three, accumulation, which is the accumulation, running total of numbers being operated on or the current version of the string. The initial value of the accumulation can be set as a second argument in the anonymous function.

syntax:

var reducedValue = array.reduce(function(accumulation,  item, index, all){
   acc = acc item OPERATION (+, -, *, / etc...)
}, STARTING VALUE FOR THE ACCUMULATION -- USUALLY 0 OR 1 DEPENDING ON THE OPERATION YOU ARE PREFORMING)

WHEN TO USE
if you want to take an array of numbers that have been input and preform the same operation on them (eg if you wanted to add all the elements in an array and then work with the total)

OR

If you have a multidimensional array of letters or numbers and you want to concatenate each array within the array into a single value and then do something with that single value.

example:
Sally is building an app that pushes the value for the number of shits she gave in each of her classes today. She wants to take that data and total it so she knows the total amount of shits she gave all day long.

var shitsGivenToday= [0,1,0.5,2.4,0 ]

var totalShits = shitsGivenToday.reduce(function(acc, item, index, all){
   varShitsGivenToday = acc + item;
  return acc;
},0)

more about iterators

My friend DOM

Way back... a few months ago, when I started interviewing for coding bootcamps, one of my interviewers asked me to tell him about the DOM... and I was like, "Sorry I don't know him. Is he like to Fonz of programming..." He's not. In fact he's not a he at all.

WHAT IS "THE DOM"?
DOM is an acronym that stands for Document Object Model and it's basically a copy of the HTML that your browser renders when you open it.

WHY DO YOU NEED A COPY OF WHAT YOU WROTE?
Because it is a copy multiple users can reach out to the page without having to have the source files on their computer and they can interface with the same page at once and have a user experience that is unique from that of others.

DOM MANIPULATION:You don't want to access the DOM much. The more you grab info or push info to the DOM the slower your program will run. (because you have to wait for the script running the program to reach out to the DOM. Manipulating things in your actual script first and then sending as much correspondence to the DOM at once as you can is the preferred way to do things.

JQUERY SELECTORS AND THE DOM
Jquery makes interacting with the DOM much easier than using vanilla (plain ol') java script. The selectors allow you to easily classify and reference page elements like buttons, input and divs, text etc. The best way to learn about jQuery is to read the  jQuery docs, but the TLDR is that it is a library that has converted the long hand and sometimes confusing process of referencing the DOM with javascript into simple procedural steps. Once you add a script tag for jQuery (eg <script src="https://code.jquery.com/jquery-2.1.4.min.js"></> ) your browser will know to reference that library every time you include an $ symbol before your text. For example, $("#name") is the jQuery way to refer to an element on your DOM that has an id of name.

There are tons of handy things that can be with jQuery, so I definitely recommend having a peruse through the jQuery site.





Friday, October 23, 2015

GITing it



It was not so long ago that I was at total noob to Git Hub and even after I’d gone through the motions of installing git hub and doing the exercises I still didn't quite understand what it was...


SO WHAT THE HUB IS GIT? 

GitHub is a site that stores files for free. That’s it. It doesn’t necessarily have to be files for computer programming. It can be image or text files or whatever you want.


WHY STORE FILES THERE?

  
The cool thing about Git Hub is that it has been designed in such a way that multiple people can work on files at once. This is done by storing a copy of the files on the computer of each person who is working on the file and then when their changes to the file are uploaded back to GitHub it will identify what is different in your version of the file than the original and any other versions other people have created and will allow everyone involved to look at the changes and compare them.

Even if you are the only one working on the file, it is still quite handy to save it to GitHub because you will be able to look back at every version of the file you have saved — and if you are working on a computer program and you get off track in such a way that your program no longer runs OR doesn’t do what you had expected, you can back track and go back to an earlier version of the file before you got onto the wrong track and you can branch off in a new direction.

This process of saving different versions of a file and branching off in new directions is called Version control. And there are a lot of programs and sites that do this (Google drive can be used in a similar way for example), but GitHub is one of the most popular free sites to do this. And also, GIT lends itself nicely to puns.

HOW DO YOU USE GIT HUB:


These sites can help you GIT started:


Code School's Free intro to git hub

http://gitimmersion.com/

Pro GIT book

Thursday, October 22, 2015

Using the command prompt/ terminal





A DOSile EXPERIENCE
(contains no useful information)


I faintly remember using DOS on a pre-windows computer. When I was in 7th grade, before my dad had bought our first family computer. I was required to take computer class for three months. I would love to tell you that class was life-changing and sparked an interest in technology that burned inside of me from that day on...

But to me, at the age of 11, the thing that was most exciting about computers was their capacity to print large shitty address labels that sported shamefully pixelated images of Garfield And Friends. I was one of those kids who loved to stickers. My dresser, my homework folders, the brown paper bag covers on my books were all covered in stickers. So I'm pretty sure the day we learned how to make our own sticky labels was raddest day of my life.

As soon as I got home from school, I hand-wrote a half a dozen letters to send out to friends and family. Then I marched out to the mailbox, tipped up the red flag and gave the almost indistinguishable pictures of Odie and Garfield one last loving glance as I sent them off to "wow my friends and family."

... so I guess that's why seeing the good ol' black and white > on my screen makes me feel cool...  or maybe its cool for the same reason overly-pixelated graphics of Garfield are cool. Terminal commands are the OGs of computer interfacing. But using the command prompt is more than just a kookie-retro thing, it can actually be quite handy.

**** useful stuff starts here****

WHAT IS THE COMMAND PROMPT/ TERMINAL? 


-The command prompt (>  on a windows computer or $ on a Mac) is a non-GUI (graphical user interface) way to can access files and programs without a mouse or touch screen).

WHY WOULD YOU USE THE COMMAND PROMPT/ TERMINAL? 

-If you are familiar with searching/ accessing files through the command prompt it can be an extremely efficient and precise way to search and access files. (ie instead of opening finder and scanning through to the folder you want and then selecting the file you are looking for in that folder, you can just type one line into the command prompt and BAM, you've opened the file you were looking for. )

-It is the fastest easiest way to use certain Interfaces eg (Git Hub)

HOW DO YOU LEARN TO USE IT? 

Here are a few sites that are helpful in getting started with using the terminal:

The Command Line Crash Course

LinuxCommand.org

Ryan's Linux Tutorial

WHAT ARE THE BASICS? 

ls: lists the files in a directory
(adding  -a  will show files with any extension (some of which are normally hidden like git repository info)

cp: Copy the contents of a file and move it to a different file
eg:
cp file1.txt newBlankfile.txt OR file1.txt file2.txt 

mv: rename a file or directory OR move a file or directory
eg:
mv file1.txt improvedFile1.txt ... will rename "file1.txt": "improvedFile1.txt"
or
mv file1.txt folder1 ... will move file1.txt into folder1
or
mv folder1 theAwesomeFolder ... will rename the directory "folder1": "theAwesomeFolder"

mkdir: make a new empty directory (folder).

cd: change directory. Change from one directory to another
eg 
cd ..   takes you one step backwards in your path
cd ~ takes you to your home directory
cd ../../.. takes you three back
cd ~/desktop/fileOnDesktop takes you from the home directory forward 2 steps from there

pwd: "print working directory" ie show the path to get to where you currently are

less: gives you a summary of what's in a file
syntax:  
less file-name
http://www.thegeekstuff.com/2010/02/unix-less-command-10-tips-for-effective-navigation/

cat: Displays text file, file concatenation, create new text file, modify file, read text file
syntax:  cat filename OR cat > filename OR cat [options] filename

man: displays a manual of linux commands
syntax: man [option(s)] keyword(s)
eg man ls OR man pstree | col -b pstree.txt

grep: seraches any given input file, selecting lines that match one or more pattern(s). By default, a pattern matches an input line if the regular expression (RE) in the pattern matches the input line. Each input line that matches at least one of hte patterns is written to the standard output.
syntax:  grep patternYoureLookingFor filename

find: finds stuff
syntax:  
find location comparison-criteria search-term
.    finds all the files in the current and subdirectories

The pipe: method to send data from one program to another. Output is fed from the program on the left side of the "|: to the program on the right

syntax: fileOne and/or LinuxCommand1 | file2 and/or LinuxCommand2 | etc etc

eg
ps auxwww | grep fred | more
ls -al |grep Aug| grep -v '200[456]'| more

echo: appends text to a file. 
syntax:  echo "some text" >> afile.fileType (.txt, .rb etc) 

touch: creates an empty file
syntax: touch newFileName.type