0% found this document useful (0 votes)
19 views61 pages

EE250Unit1_Technologies

Uploaded by

花海
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views61 pages

EE250Unit1_Technologies

Uploaded by

花海
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

1.

EE 250 Unit 1

Technologies
(Python, Git, Raspberry Pi, Linux)
1.2

PYTHON
1.3

Credits
• Many of the examples below are taken from the
online Python tutorial at:
– http://docs.python.org/tutorial/introduction.html
• Other tutorials:
– https://www.learnpython.org/
– Many others online
1.4

Python in Context
• Two major versions with some language differences
– Python 2.x
– Python 3.x (we will focus on this version)
• Interpreted, not compiled like C++
– Can type in single commands at a time and have them
execute in "real time"
– Somewhat slower
– Better protection (no memory faults)
1.5

Interactive vs. Scripts


• Can invoke python and work interactively
– % python #python 2.x
– % python3 #python 3.x
>>> print("Hello World")
Ctrl-D (Linux/Mac) [Ctrl-Z Windows] at the prompt will exit.
• Can write code into a text file and execute that file as
a script
– % python3 myscript.py
# python2.x
>>>print "Hello world"

# python3.x
>>> print("Hello world")

myscript.py
1.6

Types
# python 2.x
>>> 3 / 2
1 # python2.x
• Types 1.5 # python3.x
– Bool: True/False (not true/false) # python 3.x
– Integers >>> 3 // 2
1
• Integer division => see examples
>>> 1.25 / 0.5
– Floats 2.5
– Complex
>>> 2+4j + 3-2j
– Strings (5+2j)

• Dynamically typed >>> "Hello world"


'Hello world'
– No need to "type" a variable
>>> 5 == 6
– Python figures it out based on what it is False
assigned
– Can change when re-assigned >>> x = 3
>>> x = "Hi"
>>> x = 5.0 + 2.5
1.7

Strings
• Enclosed in either double >>> 'spam eggs'
'spam eggs'
or single quotes
>>> 'doesn\'t'
– The unused quote type "doesn't"
can be used within the >>> "doesn't"
string "doesn't"

• Can concatenate using >>>'"Yes," he said.'


'"Yes," he said.'
the ‘+’ operator >>> "Con" + "cat" + "enate"
'Concatenate'
• Can convert other types
>>> i = 5
to string via the str(x) >>> j = 2.75
>>> "i is " + str(i) + " & j is" + str(j)
method 'i is 5 & j is 2.75'
1.8

Simple Console I/O – Python 3.x


>>> print("A new line will")
• Python3.x >>> print('be printed')
A new line will
– Output using print() be printed

• Must use parentheses # Python 3.x


• Use end='' argument for ending options >>> print('A new line will', end='')
>>> print(' not be printed')
– Input using input(prompt)
• Always returns a string # Python 3.x
>>> response = input("Enter text: ")
• Conversion to numeric types: Enter text: I am here

– int(string_var) convert to an integer >>> response = input("Enter a num: ")


Enter a num: 6
– float(string_var) convert to a float
>>> x = int(response)
>>> x = float(response)
1.9

Simple Console I/O – Python 2.x


>>> print "A new line will"
• Python2.x >>> print 'be printed'
A new line will
– Output using print be printed

• If ended with comma, no newline will be # Python 2.x


output >>> print('A new line will',
• Otherwise, will always end with newline >>> print(' not be printed'
A new line will not be printed
– Input using raw_input(prompt)
• Can provide a prompt # Python 2.x
>>> response = raw_input("Enter text: ")
• Will always return a string Enter text: I am here
• Conversion to numeric types: >>> response = raw_input("Enter a num: ")
– int(string_var) convert to an integer Enter a num: 6

– float(string_var) convert to a float >>> x = int(response)


>>> x = float(response)
1.10

Selection Structures
• if…elif…else #! /usr/bin/python3

• Ends with a : on that line myin = input("Enter a number: ")

• Blocks of code delineated by x = int(myin)

indentation (via tabs/spaces) if x > 10:


print("Number is greater than 10")
elif x < 10:
print("Number is less than 10")
else:
print("Number is equal to 10")
1.11

Iterative Structures
• while <cond>: #!/usr/bin/python3

• Again code is delineated secret = 18


by indentation attempts = 0
while attempts < 10:
myin = input("Enter a number: ")
if int(myin) == secret:
print("Correct!")
break
attempts += 1
1.12

Lists
>>> x = ['Hi', 5, 6.5]
• Lists are like arrays from C++ >>> print(x[1])
5
but can have different
>>> y = x[2] + 1.25
(heterogenous) types in a single 7.75
list object >>> x[2] = 9.5
• Comma separated values >>> x
['Hi', 5, 9.5]
between square brackets >>> x.append(11)
• Basic operations/functions: ['Hi', 5, 9.5, 11]

– append(value) >>> y = x.pop()


>>> x
– pop(loc) ['Hi', 5, 9.5]
– len(list) >>> y = x.pop(1)
>>> x
['Hi', 9.5]

>>> len(x)
2
1.13

Iterative Structures
• for <item> in <collection>: #! /usr/bin/env python3
• collection can be list or some other # Prints 0 through 5 on separate lines
collection we will see later (tuple, x = [0,1,2,3,4,5] # equiv to x = range(6)
dictionary, etc.) for i in x:
• For a specific range of integers just print(i)
use range() function to generate a list # Prints 0 through 4 on separate lines
– Start is inclusive, stop is exclusive x = 5
– range(stop) for i in range(x):
• 0 through stop-1 print(i)
– range(start, stop) # Prints 2 through 5 on separate lines
• start through stop-1 for i in range(2,6):
– range(start, stop, step) print(i)
• start through stop in increments of # Prints 0,2,4,6,8 on separate lines
stepsize
for i in range(0,10,2):
print(i)
1.14

Exercise 1a
• Continue to get input from Some text
the user until they type in Other input
quit
"quit" (exactly). Count 2

how many times you have


to get input before they
type "quit" and output
that value once they do
enter "quit"
1.15

Handy List Methods


• Can be sliced using : (range operator) >>> x = [4, 2, 7, 9]
>>> x[3]
– Eg. list[start:end] 9
– Start is inclusive, end is exclusive >>> x[0:2]
[4,2]
• len() function >>> x[2:]
[7, 9]
• item in list
– Return true if item occurs in list >>> 2 in x
True
• sort() >>> min(x)
– Sorts the list in ascending order 2
– Works in place >>> x.sort()
• reverse() [2, 4, 7, 9]

• min(), max(), sum() functions >>> x.append(4)


[9, 7, 4, 2, 4]
• count(item) >>> x.count(4)
– Counts how many times item occurs in 2
the list
1.16

Handy String Methods


• Can be subscripted >>> word = 'HelpA'
>>> word [4]
– No character type…everything is a 'A'
>>> word[0:2]
string 'He'
• Can be sliced using : (range operator) >>> word[2:4]
'lp'
– [start:end]
>>> word[:2]
– Start is inclusive, end is exclusive 'He'

• len() function >>> word[3:]


'pA'
• Immutable type
>>> len(word)
– To change, just create a new string 5

>>> word[0] = 'y'

Traceback (most recent call last):


File “<stdin>”, line 1, in ?
TypeError: object does not support item
assignment
>>> word = 'y' + word[1:]
1.17

Handy String Methods 2


• find(), rfind() >>> "HelpA".find('elp')
1
– Finds occurrence of substring and
return index of first character or -1 if >>> "yoyo".rfind("yo")
2
not found
>>> "yoyo".find("ooo")
• in -1
– Returns boolean if substring occurs >>> "yo" in "yoyo"
in string True

• replace() >>> "yoyo".replace("yo","tu")


'tutu'
• isalpha(), isnum(),
>>> "!$%".isalphnum()
isalnum(), islower(), False
isupper(), isspace() >>> "A 123"[2:].isnum()
– return boolean results True

• split(delim) >>> x = "The cow jumped over the moon"


>>> x.split()
– returns a list of the string split into >>> x
multiple strings at occurrences of ['The','cow','jumped','over','the','moon']
delim >>> x[2]
'jumped'
– delim defaults to space
1.18

Import Modules
myscript.py
• To use Python libraries/modules use #!/usr/bin/python3
import sys
the import keyword
print("Num args is " + str(len(sys.argv)))
• sys module contains system access
print("Command line args are:")
methods including access to for arg in sys.argv:
command line arguments print(arg)

– sys.argv is a list where each item is a


string representing the i-th command
line argument Command line

• Common modules $ python3 myscript.py hello 5 2.5

– math: defines functions like log, exp, Output


sin, cos, etc.
Num args is 4
– random: defines functions for random Command line args are:
number generation myscript.py
– os: File I/O and other OS functions hello
5
– socket, http, json, and many others 2.5
1.19

More Modules
• To call function and create instances >>> import math
>>> log10(100)
of classes (i.e. objects) defined in a
Traceback (most recent call last):
module, you must use hierarchy File "<stdin>", line 1, in <module>
indicating module.function( ) or NameError: name 'log10' is not defined
module.classname >>> math.log10(100)

• You can bring functions and classes 2.0

into the top level namespace with >>> from math import log10
the from statement >>> log10(1000)
• Examples: 3.0

– from math import log10


>>> cos(0)
– from math import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cos' is not defined
>>> from math import *
>>> cos(0)
1.0
1.20

Functions and Modules


• def func(…): #! /usr/bin/python3

– code def count_odds(inlist):


num = 0
– return statement for i in inlist:
if i % 2 == 1:
• No static typing of num += 1
return num
arguments
def count_evens(inlist):
• Return type can be anything return len(inlist) – count_odds(inlist)

• To use in another python


odd_even.py
script or from interactive
shell, use import Command line
$ python3

>>> import odd_even


>>> odd_even.count_odds([3,4,8,9,5])
3
1.21

Python Scripts & Main


def stuff():
print("In stuff()")
• There is no main()
print("I print first")
– Python will execute the code that is stuff()
print("I print last")
not in a function from top-down
• We can specify a starting function I print first
In stuff()
I print last
by checking if the module was
started from the top-level (i.e. from
the terminal, etc.) via its __name__ def stuff():
print("In stuff()")
property def func1():
print("In func1")
– If the __name__ is "__main__" then it
if __name__ == '__main__':
is the top and we can call any function print("Starting")
func1()
we like or execute any code we like
Starting
In func1
1.22

Exercise 1b
myscript.py

• Convert your code to get input and def countInput():


...
count how many times you receive
input before they type quit into a
function
• Modify your code to get input from
the user until they enter some text
that has "quit" anywhere in the larger >>> # import and
# call countInput
string (e.g. 'Okquit now').
• Start an interactive python session,
import your module/script and call
your function
1.23

Exercise 2
• Write a script that takes 1 command line
argument (call it quitVal)
– $ python3 ex2.py 5 # 5 is quitVal
• The script should read in integers one at a
time (one per line) and sum all the positive
integers, ignoring negative numbers, until the
user types the quitVal.
1.24

Variables & Memory Allocation


Object/Memory
Namespace
Space
• Variable names do not >>> x = [4,5,9]
x [4,5,9]
refer to fixed locations in >>> y = x

memory y
Object/Memory
• Instead a variable name Namespace
Space
references an object >>> x[1] = 7
x [4,7,9]
• When we assign a >>> print(y[1])
7
variable we are changing y
the association between
the variable name and Namespace
Object/Memory
which object it Space
>>> x = [4,5,9]
references x [4,5,9]
>>> y = list(x)
• Copies are not made >>> a = 5 y [4,5,9]
unless explicitly >>> b = a
performed via a "copy >>> b = 7 a 5
constructor" >>> print(a)
5
b 7
1.25

Variable/Reference Gotcha
Object/Memory
Namespace
Space
• Be sure to understand >>> x = [4,5,9]
x [4,5,9]
what assignment does >>> y = x

y
Object/Memory
Namespace
Space
>>> x = []
>>> print(len(y))
x []

y
You MAY think this is what you have…

Object/Memory
Namespace
Space
>>> xx == []
>>> []
>>> print(len(y))
print(len(y))
x []
>>>
3
y [4,5,9]

…when, in fact, you have this


1.26

Argument Passing
1 def f1(a, b):
• Not pass-by-value, not pass-by-reference! 2
a = 5
b.append(3)

• Object references are copied to new arg. names 3 b = []

x = 7
– Arguments are new names that reference the original y = [1,2]
argument references f1(x,y)
print(x)
– Reassigning associates a new object with the name print(y)

1 2 3
Object/Memory Object/Memory Object/Memory
__main__ __main__ __main__
Space Space Space
Namespace Namespace Namespace

x 7 x 7 x 7

y [1,2] y [1,2,3] y [1,2,3]

f1 f1 f1
Namespace Namespace Namespace

a a 5 a 5

b b b []
1.27

Tuples
• Like an array but can >>> x = ('Hi', 5, 6.5)

store heterogeneous >>> print(x[1])


5
types of objects >>> y = x[2] + 1.25

• Comma separated values 7.75


>>> x[2] = 9.5
between parentheses Traceback (most recent call last):

• Immutable File “<stdin>”, line 1, in <module>


TypeError: ‘tuple’ object does not support item
– After initial creation, assigned
cannot be changed
• Often used as the return
def square_a_and_p(s):
value of a function area = s*s
– Thus, in Python, you can perim = 4*s
return more than 1 value return (area,perim)
1.28

Dictionaries (C++ Maps)


>>> grades = {}
>>> grades['Bill'] = 85
• Associates key, value pairs Key : Value
>>> grades["Jan"] = 100
• Primary operations: >>> grades['Tom'] = 74
Bill : 85
– Insert(key, value)
– Erase(key) >>> grades['Jan'] + grades['Bill'] Jan : 100
– Lookup(key) => returns value 185 Tom : 74
– Is some key present in the dictionary >>> grades['Tom'] = 75

• Main idea is that we know or will be


>>> "Tom" in grades
given the key and use it to lookup,
True
access, or change the associated value
>>> "Mark" in grades
• Key needs to be something unique False
and "hashable" (string, int, etc. but >>> grades.keys()
not a list or other composite object) ['Bill','Jan','Tom']
– Hashing refers to converting some
data value (string, etc.) to an integer in >>> for k in grades: # same as for k in grades.keys()
some given range (32-bits, 128-bits, print(k)
etc.) ### Prints each key: 'Bill','Jan','Tom'

• Value can be anything (int, list, dict) >>> for k,v in grades.items():
print(k + " got the score " + str(v))
• Keyword in checks membership
1.29

Exercise 3
• Write a script that reads in zip codes (e.g. 90007,
90089, etc.) one per line until the user enters 0 and
then outputs how many occurrences of each unique
zip code was entered
– Use a dictionary to track the occurrences of each zip code

$ python3 ex3.py
90007
User input
90089
90007
0
Occurrences:
Desired output
90007 : 2
90089 : 1
1.30

Installing Linux Packages/Programs


• Ubuntu maintains servers that have distributions of
programs/packages available for installation
• Many packages depend on other packages and so installing
one requires installing many others
• Thankful Ubuntu makes this easier with installation utilities
and package manager (apt-get)
• Common syntax:
– sudo apt-get install package-name
– Examples:
• sudo apt-get install build-essential
– Installs g++ compiler and other
• sudo apt-get install git
• sudo apt-get install vim
1.31

Installing Python Packages


• Just like apt-get helps with distribution and
installation of programs for Ubuntu, pip3
downloads, installs, and configures Python
packages/libraries for python3
– $ pip3 install package-name
1.32

More "Humor"

https://imgs.xkcd.com/comics/universal_install_script_2x.png
1.33

Stdin, stdout, stderr


• Programs pull input from a stream known as 'stdin' (standard input)
– It is usually the stream coming from the keyboard but can be "redirected" to pull data from a file
• Programs output stream known as 'stdout' (standard output)
– It is usually directed to the screen/terminal but can be "redirected" to a file
• Programs have a 2nd output stream known as 'stderr' (standard error)
– It too is usually directed to the screen/terminal but can be "redirected" to a file

Input File #include<iostream>


using namespace std;
int main(int argc, char *argv[])
6 1 7 5 y ... 61 75 y {
cout << “Hello” << endl;
cerr << "Bad Input" << endl;

or }

#include<iostream>
Output File
using namespace std;
int main(int argc, char *argv[]) Hello
{ Hello
int dummy, x; Bad input
cin >> dummy >> x; Error File

} Bad input
1.34

Redirection & Pipes


• '<' redirect contents of a file as input to program
– ./prog1 arg1 arg2 < input.txt
• '>' redirect program output to a file
– ./prog1 arg1 > output.txt
• '>&' redirect stderr to a file
– g++ -o test test.cpp >& compile.log
• '|' pipe output of first program to second
– grep "day" re.txt l wc -l
• 'l&' pipe stderr of first program to second
– g++ -o test test.cpp l& grep error
1.35

GIT AND GITHUB


1.36

Source/Version Control
• Have you ever made backups of backups of source files to
save your code at various states of development (so you can
recover to an earlier working version)?
• Have you ever worked on the same code with a partner and
tried to integrate changes they made?
• These tasks can be painful without help
• Source/version control tools make this task easy
– Allows one codebase (no separate folders or copies of files) that can
be "checkpointed" (committed) at various times and then return back
to a previous checkpoint/commit if desired
– Can help merge differences between two versions of the same code
• Common source/version control tools are:
– Git, Subversion, and a few older ones (cvs, rcs, clearcase, etc.)
1.37

Repositories
• We generally organize our code repo

and related files for a project in test


some folder
– We will use the term "repository" in1.dat out1.dat
for this top-level folder when it is
under "version-control" bin

• Your repository can have some


files that ARE version controlled… file1.o file2.o
– Source code, Makefiles, input files
src
• …and some that ARE NOT
– Object files, executables, output
file1.c file2.c
files
1.38

Git
• Git is a version control system github.com

– Stores "snapshots" of files (usually code)


in a repository (think folder) at explicit
points in time that you choose repo
• No more making backup copies
– Allows easy updates to a view of the code clone/pull
at some historical point in time
• Git is "distributed" (often via Github) push

– Allows the repository to exist on various


machines and each can be modified and
repo repo
checkpointed (aka "commits")
– Github holds the central repository
– Updates can be communicated to each Your laptop Your
Raspberry Pi
"clone" of the repository by "push"-ing
updates to and "pull" updates from the
central repository on Github
1.39

Cloning Repos
github.com

• Cloning a repo brings a copy of the


specified repository onto your local
machine repo

– git clone url-of-repository


• You can now perform additions,
modifications, and removals locally
(without being connected)
• Allows the two repositories to be
synchronized in both directions via repo

git push and git pull


Your laptop

git clone git@github.com:usc-ee250-fall2022/Grove-Pi


1.40

Adds and Commits


• Repositories are updated by performing commits
repo
• We first indicate all the files we want to commit by file1.cpp
file2.cpp
performing one or more adds via git add C1
– Like adding things to your cart
repo
• Then we perform a git commit of the added files file1.cpp'
C2 file2.cpp
– Like checking out
• Note: Don't add folders, just files…folder structure
will be added automatically
Sample Sequence:
1 2 3 4
git add file*.cpp git commit –m "Initial" git add file1.cpp git commit –m "Updated"

file1.cpp
file1.cpp'
file2.cpp

C1 C2
This Photo by Unknown Author is licensed under CC BY-SA
1.41

git commit
git add

Git "Locations"
https://git-scm.com/book/en/v2/Getting-Started-Git-Basics

git add

git commit
Git File Lifecycle
https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository
1.42

Push and Pull


repo
• Suppose we make changes to our file1.cpp
file2.cpp
local repository C1
– git add file1.cpp
– git commit -m "Added func2" git pull
git push
• We upload the updates to the (u/l C2) (d/l C2)

remote repository via a push


repo repo
operation file1.cpp' file1.cpp
file2.cpp file2.cpp
– git push C1
C2
• Another clone of the repository can Your laptop Your
Raspberry Pi
download any updates from the
remote repository via a pull
operation
– git pull
This Photo and This Photo by Unknown Author is licensed under CC BY-SA; This Photo by Unknown Author is licensed under CC BY-NC-ND
1.43

Branches Motivation
• Branches are useful when you are time
C1
adding some new feature/fix,
especially when other developers
may also be doing the same by giving C2
a separate sandbox to work in
• Branches allow you to
– Grab the code from a particular starting feature1 C3 main branch
point (i.e. commit) branch C4 (other
(your updates developers or
– Modify code, add, delete and commit for feature 1) C5 fixes to C2)
without affecting others viewpoint unless
they explicitly desire
– Merge the code back into the main C5
branch
1.44

Branches (1)
• Each commit has one parent
• Branches are just names that can be C1
associated with a commit
– 'main' is the default branch feat1 main
– Created using: C2
git checkout -b branch-name
• You can only be working on one particular feat1
branch at a time C3
• Any commits are applied to the current
feat1
branch
C5
• Example:
– git checkout -b feat1
– git commit -m "Added part1"
– git commit -m "Added part2"
1.45

Branches and Merging


• We can switch between branches using git
checkout branch-name C1
• Example:
– git checkout main feat1
– git commit -m "Fix bug 1" C2
• Two branches can then be merged together via:
git merge branch-to-merge-in
• A merge is a special commit with two "parents" feat1
and combines the code C3
• Example: C4
feat1
– git merge feat1 C5
• Note: You must be in the branch that will be
updated with the code from the specified feat1 main
branch C7 C6
– The specified branch remains independent (you'd have
to do another merge to sync both branches)
– git checkout feat1
– git commit -m "Separate change"
1.46

Conflicts
C1
• If the merge encounters updates that it is
not sure how to combine, it will leave the feat1 main
file in a conflicted state C2
• Can find conflicted files via:
– git status feat1
C3
• Contents of conflicted files must be main branch
C4 (other
manually combined feat1 developers or
– Conflicted areas are highlight with <<<<, C5 fixes to C2)
====, >>>> with the contents of each
branch
– Edit the file to your desired final contents C5
– Then add and commit
If you have questions, please
<<<<<<< HEAD
open an issue
Sample =======
Conflicted File ask your question in IRC.
>>>>>>> feat1
1.47

Remotes
upstream
• Remotes are just like their name
github.com:usc-ee250/repo
repo repo
file1.cpp file1.cpp
indicates: remote locations where we file2.cpp file2.cpp

can push and pull (or fetch) data from github.com:mredekopp/repo

• To list remotes origin


– git remote -v
• To add a remote
– git remote add name remote-url repo
– origin is the common name for the file1.cpp
file2.cpp
remote repo from which you cloned
– A remote is just an association of a name
to a repo URL
• To choose & push a particular branch
to a remote
– git push -u remote local-branch
1.48

Forks
• A fork is a "copy" of a repository
– Essentially a new repo whose starting point is the current
state of the original, "forked" repo
– Allows changes to be made (like a branch) or starting a new
project based on some current codebase
• If the original fork changes, there are means to pull those updates into
your fork
– It is possible to fork a fork ☺
• Example
– The sensors we use have Python library support available on Icons made by Dave Gandy
from Flaticon is licensed by
Github Creative Commons CC 3.0 BY
– We have forked that repo and made some changes for EE
250
– You will then fork our repo (i.e. a fork of a fork) and modify
it with your lab group
• If we make changes in our repo, you can easily bring them into your fork
1.49

Upstreams
• Common definitions
– upstream: The parent repository from which you forked
– downstream: The forked ("child") repository (i.e. your repo)
• Common usage
– The upstream fork can be thought of as just another remote
– While the remote named origin usually refers to your fork on github, the
remote named upstream usually refers to the parent of your fork
• Setting up access to the upstream fork
– See https://help.github.com/articles/fork-a-repo/
– git remote -v Icons made by Dave Gandy
from Flaticon is licensed by
– git remote add upstream parent-fork-url Creative Commons CC 3.0 BY

• Updating your code from the parent fork


– git fetch upstream
– git checkout main (can be skipped if you aren't using branches)
– git merge upstream/main
1.50

An Example
• Suppose we create a repo for you: p1-ttrojan
– It comes preloaded (because of actions we took) with some code that was from
our own repo: p1-skel
– git clone git@github.com:usc-ee250-fall2023/p1-ttrojan-fork
– cd p1-ttrojan
– # You make changes; add, commit, push
• Now we make changes to p1-skel, how can you get and merge those
changes in?
– git remote -v # list the remotes
– git remote add upstream git@github.com:usc-ee250-
fall2023/p1-skel
– git fetch upstream # d/l changes to a temp area
– git checkout main # make sure you're in your main branch
– git merge upstream/main # Update your code
1.51

Summary
• git add file(s)
– Stage a file to be committed
• git commit -m "Change summary"
– Makes a snapshot of the code you added
• git checkout -b branch-name
– Create a branch and switch to it
• git pull
– Download commits from your remote repository
• git push
– Upload your local commits to the remote repository
• git checkout branch-name
– Switch to a new branch
• git merge other-branch-name
– Merge the commits from other-branch-name into current branch
• HEAD is synonymous with the current branch's latest commit
• origin is usually the remote name for your repo on github
• upstream is usually the remote your repo was forked from (must be added)
1.52

Helpful Links
• https://help.github.com/
• http://rogerdudler.github.io/git-guide/files/git_cheat_sheet.pdf
• https://learngitbranching.js.org/
– Main: Level 1 - Intro to Git Commits
– Main: Level 2 - Ramping Up
– Remotes: Level 1: Push & Pull – Git Remotes
– Remotes: Level 2: To Origin and Beyond
• https://services.github.com/on-demand/downloads/github-git-cheat-
sheet/ (web version)
• https://services.github.com/on-demand/downloads/github-git-cheat-
sheet.pdf (print version)
1.53

Summary
• You should…
– Feel generally comfortable writing basic Python
scripts that manipulate strings, integers, etc. and
call library functions
– Understand the basic git add, commit, push, pull
process
– Understand branches/remotes
– Know to use sudo apt-get install or pip3 to install
Linux packages or python-specific packages
1.54

LINUX
1.55

The Linux OS
• Based on the Unix operating system
• Developed as an open-source ("free") alternative by
Linux Torvalds and several others starting in 1991
• Commonly used in industry and in embedded
devices
• Both your VM and your RPi will be running Linux so
we want you to feel comfortable using it
rpi-ttrojan
1.56

ssh Connections
• ssh stands for Secure Shell
– Encrypted protocol to run a terminal
(command line) on a remote server
• Usage This Photo by Unknown Author is
licensed under CC BY-NC-SA

– $ ssh username@server
– $ ssh ttrojan@aludra.usc.edu
• Use your USC password first, then try 10-
digit ID rpi-ttrojan

– $ ssh pi@rpi-ttrojan
1.57

Terminal/Command Line
• No more GUI!
– ssh connections provide only command line
interfaces to the remote machine
• Have to be comfortable navigating the file
system, using command line utilities and text-
based editors
– Paths (e.g. ../ee250/Grove-Pi/examples)
– Utilities (cd, mv, cp, rm, mkdir, cat, more, grep)
– Text-based editors (vi, emacs, nano)
1.58

How Will We Transfer Files


repo
• With git file1.cpp
file2.cpp
– add/commit/push on one machine
C1
– pull on the other
• Good to know but should not be used in
place of git: scp git push git pull
(u/l C2) (d/l C2)
– Same as 'cp' (secure cp) but copies to/from
current machine to another network machine
repo repo
over a secure connection
file1.cpp' file1.cpp
– scp current_file dest_loc file2.cpp file2.cpp

• Current_file or dest_location can be on a C2 C1


remote machine which requires user@machine Your
Your laptop
syntax before file location Raspberry Pi
– Examples:
– scp username@aludra.usc.edu:temp/hi.txt .
– scp *.cpp username@aludra.usc.edu:temp/
1.59

Access Control and sudo


/

• Linux enforces access control per user lib


– You have access to /home/username
libgraph.a
– You likely cannot copy from your home folder to
/include include
• $ cp ~/crypto/crypto.h /include
graph.h
– The system is represented by user root and
has superuser/supervisor access
• The magic of sudo jane

– Admins can configure a user account to have


supervisor privileges crypto
– If you have supervisor access, precede your
command with sudo and it will execute the libcrypto.a
command with elevated privileges
crypto.h
– $ sudo cp ~/crypto/crypto.h /include
prog1
• Some labs will require you to run commands
(for example to use a USB device) preceded prog1.c
with sudo
1.60

sudo Humor

https://imgs.xkcd.com/comics/sandwich.png

https://imgs.xkcd.com/comics/incident.png
1.61

Environment Variables
• Contain values that can be accessed by
other programs that provide system and
other info Makefile
– PATH OBJECTS = lcd.o adc.o proj.o
CC = gcc
• Where to look for executables
– LD_LIBRARY_PATH proj.elf: $(OBJECTS)
$(CC) –o proj.elf $(OBJECTS)
• Where to look for libraries lcd.o: lcd.h lcd.c

• Set a variable $(CC) –c –Wall lcd.c –o lcd.o

– In a terminal/shell with export command


• export VARIABLE=VALUE
– In a Makefile
• VARIABLE=VALUE

• Use with $VARIABLE in shell


• Use with $(VARIABLE) in Makefile

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy