Skip to content

Commit 47a213b

Browse files
Corey SchaferCorey Schafer
Corey Schafer
authored and
Corey Schafer
committed
Added Python code snippets
1 parent df2e19b commit 47a213b

File tree

34 files changed

+880
-0
lines changed

34 files changed

+880
-0
lines changed

.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.DS_Store
2+
3+
# Video Scripts
4+
s.txt
5+
script.txt
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
class Employee:
3+
"""A sample Employee class"""
4+
5+
def __init__(self, first, last):
6+
self.first = first
7+
self.last = last
8+
9+
print('Created Employee: {} - {}'.format(self.fullname, self.email))
10+
11+
@property
12+
def email(self):
13+
return '{}.{}@email.com'.format(self.first, self.last)
14+
15+
@property
16+
def fullname(self):
17+
return '{} {}'.format(self.first, self.last)
18+
19+
20+
emp_1 = Employee('John', 'Smith')

Automation/rename.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import os
2+
3+
os.chdir('/path/to/files/')
4+
5+
# Am I in the correct directory?
6+
# print(os.getcwd())
7+
8+
# print(dir(os))
9+
10+
# Print all the current file names
11+
for f in os.listdir():
12+
# If .DS_Store file is created, ignore it
13+
if f == '.DS_Store':
14+
continue
15+
16+
file_name, file_ext = os.path.splitext(f)
17+
# print(file_name)
18+
19+
# One way to do this
20+
f_title, f_course, f_number = file_name.split('-')
21+
22+
# print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext))
23+
24+
# Need to remove whitespace
25+
f_title = f_title.strip()
26+
f_course = f_course.strip()
27+
# f_number = f_number.strip()
28+
29+
# Want to remove the number sign?
30+
# f_number = f_number.strip()[1:]
31+
32+
# One thing I noticed about this output is that if it was sorted by filename
33+
# then the 1 and 10 would be next to each other. How do we fix this? One way we can fix this is to pad
34+
# the numbers. So instead of 1, we'll make it 01. If we had hundreds of files then this would maybe need to be 001.
35+
# We can do this in Python with zfill
36+
f_number = f_number.strip()[1:].zfill(2)
37+
38+
# print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext))
39+
40+
# You have the power to reformat in any way you see fit
41+
print('{}-{}{}'.format(f_number, f_title.strip(), file_ext.strip()))
42+
43+
new_name = '{}-{}{}'.format(file_num, file_title, file_ext)
44+
45+
os.rename(fn, new_name)
46+
47+
48+
# print(len(os.listdir()))

Closures/closure.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
function html_tag(tag){
3+
function wrap_text(msg){
4+
console.log('<' + tag +'>' + msg + '</' + tag + '>')
5+
}
6+
return wrap_text
7+
}
8+
9+
print_h1 = html_tag('h1')
10+
11+
print_h1('Test Headline!')
12+
print_h1('Another Headline!')
13+
14+
15+
print_p = html_tag('p')
16+
print_p('Test Paragraph!')

Closures/closure.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
# Closures
3+
4+
import logging
5+
logging.basicConfig(filename='example.log', level=logging.INFO)
6+
7+
8+
def logger(func):
9+
def log_func(*args):
10+
logging.info(
11+
'Running "{}" with arguments {}'.format(func.__name__, args))
12+
print(func(*args))
13+
return log_func
14+
15+
16+
def add(x, y):
17+
return x+y
18+
19+
20+
def sub(x, y):
21+
return x-y
22+
23+
add_logger = logger(add)
24+
sub_logger = logger(sub)
25+
26+
add_logger(3, 3)
27+
add_logger(4, 5)
28+
29+
sub_logger(10, 5)
30+
sub_logger(20, 10)

Closures/example.log

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
INFO:root:Running "add" with arguments (3, 3)
2+
INFO:root:Running "add" with arguments (4, 5)
3+
INFO:root:Running "sub" with arguments (10, 5)
4+
INFO:root:Running "sub" with arguments (20, 10)

Datetime/dates.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import datetime
2+
import pytz
3+
4+
# Naive
5+
# d = datetime.date(2001, 9, 11)
6+
7+
tday = datetime.date.today()
8+
9+
10+
# weekday() - Monday is 0 and Sunday is 6
11+
# print(tday)
12+
13+
# isoweekday() - Monday is 1 and Sunday is 7
14+
# print(tday)
15+
16+
17+
# datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
18+
19+
tdelta = datetime.timedelta(hours=12)
20+
21+
# print(tday + tdelta)
22+
23+
# date2 = date1 + timedelta
24+
# timedelta = date1 + date2
25+
26+
bday = datetime.date(2016, 9, 24)
27+
28+
till_bday = bday - tday
29+
30+
# print(till_bday.days)
31+
32+
t = datetime.time(9, 30, 45, 100000)
33+
34+
# dt = datetime.datetime.today()
35+
# dtnow = datetime.datetime.now()
36+
# print(dir(datetime.datetime))
37+
# print(dt)
38+
# print(dtnow)
39+
40+
dt = datetime.datetime(2016, 7, 24, 12, 30, 45, tzinfo=pytz.UTC)
41+
# print(dir(dt))
42+
43+
dt_utcnow = datetime.datetime.now(tz=pytz.UTC)
44+
# print(dt_utcnow)
45+
46+
dt_utcnow2 = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
47+
# print(dt_utcnow2)
48+
49+
# dt_mtn = dt_utcnow.astimezone(pytz.timezone('US/Mountain'))
50+
# print(dt_mtn)
51+
52+
dt_mtn = datetime.datetime.now()
53+
54+
mtn_tz = pytz.timezone('US/Mountain')
55+
dt_mtn = mtn_tz.localize(dt_mtn)
56+
57+
# print(dt_mtn)
58+
59+
dt_east = dt_mtn.astimezone(pytz.timezone('US/Eastern'))
60+
# print(dt_east)
61+
62+
print(dt_mtn.strftime('%B %d, %Y'))
63+
64+
dt_str = 'July 24, 2016'
65+
dt = datetime.datetime.strptime(dt_str, '%B %d, %Y')
66+
print(dt)
67+
68+
# strftime - Datetime to String
69+
# strptime - String to Datetime

Decorators/decorators.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Decorators
2+
from functools import wraps
3+
4+
5+
def my_logger(orig_func):
6+
import logging
7+
logging.basicConfig(filename='{}.log'.format(orig_func.__name__), level=logging.INFO)
8+
9+
@wraps(orig_func)
10+
def wrapper(*args, **kwargs):
11+
logging.info(
12+
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
13+
return orig_func(*args, **kwargs)
14+
15+
return wrapper
16+
17+
18+
def my_timer(orig_func):
19+
import time
20+
21+
@wraps(orig_func)
22+
def wrapper(*args, **kwargs):
23+
t1 = time.time()
24+
result = orig_func(*args, **kwargs)
25+
t2 = time.time() - t1
26+
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
27+
return result
28+
29+
return wrapper
30+
31+
import time
32+
33+
34+
@my_logger
35+
@my_timer
36+
def display_info(name, age):
37+
time.sleep(1)
38+
print('display_info ran with arguments ({}, {})'.format(name, age))
39+
40+
display_info('Tom', 22)

Decorators/snippets.txt

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
3+
4+
5+
class decorator_class(object):
6+
7+
def __init__(self, original_function):
8+
self.original_function = original_function
9+
10+
def __call__(self, *args, **kwargs):
11+
print('call method before {}'.format(self.original_function.__name__))
12+
self.original_function(*args, **kwargs)
13+
14+
15+
# Practical Examples
16+
17+
def my_logger(orig_func):
18+
import logging
19+
logging.basicConfig(filename='{}.log'.format(orig_func.__name__), level=logging.INFO)
20+
21+
def wrapper(*args, **kwargs):
22+
logging.info(
23+
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
24+
return orig_func(*args, **kwargs)
25+
26+
return wrapper
27+
28+
29+
def my_timer(orig_func):
30+
import time
31+
32+
def wrapper(*args, **kwargs):
33+
t1 = time.time()
34+
result = orig_func(*args, **kwargs)
35+
t2 = time.time() - t1
36+
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
37+
return result
38+
39+
return wrapper
40+
41+
import time

EAFP/eafp.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Duck Typing and Easier to ask forgiveness than permission (EAFP)
2+
3+
4+
class Duck:
5+
6+
def quack(self):
7+
print('Quack, quack')
8+
9+
def fly(self):
10+
print('Flap, Flap!')
11+
12+
13+
class Person:
14+
15+
def quack(self):
16+
print("I'm Quacking Like a Duck!")
17+
18+
def fly(self):
19+
print("I'm Flapping my Arms!")
20+
21+
22+
def quack_and_fly(thing):
23+
pass
24+
# Not Duck-Typed (Non-Pythonic)
25+
# if isinstance(thing, Duck):
26+
# thing.quack()
27+
# thing.fly()
28+
# else:
29+
# print('This has to be a Duck!')
30+
31+
# LBYL (Non-Pythonic)
32+
# if hasattr(thing, 'quack'):
33+
# if callable(thing.quack):
34+
# thing.quack()
35+
36+
# if hasattr(thing, 'fly'):
37+
# if callable(thing.fly):
38+
# thing.fly()
39+
40+
# try:
41+
# thing.quack()
42+
# thing.fly()
43+
# thing.bark()
44+
# except AttributeError as e:
45+
# print(e)
46+
47+
d = Duck()
48+
49+
print(type(dir(d)))

Ex-Machina/ex-machina.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#BlueBook code decryption
2+
import sys
3+
def sieve(n):
4+
x = [1] * n
5+
x[1] = 0
6+
for i in range(2,n/2):
7+
j = 2 * i
8+
while j < n:
9+
x[j]=0
10+
j = j+i
11+
return x
12+
13+
def prime(n,x):
14+
i = 1
15+
j = 1
16+
while j <= n:
17+
if x[i] == 1:
18+
j = j + 1
19+
i = i + 1
20+
return i - 1
21+
x=sieve(10000)
22+
code = [1206,301,384,5]
23+
key =[1,1,2,2,]
24+
25+
sys.stdout.write("".join(chr(i) for i in [73,83,66,78,32,61,32]))
26+
for i in range (0,4):
27+
sys.stdout.write(str(prime(code[i],x)-key[i]))
28+
29+
print

Exceptions/currupt_file.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Currupt File!

Exceptions/exceptions.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
try:
3+
f = open('curruptfile.txt')
4+
# if f.name == 'currupt_file.txt':
5+
# raise Exception
6+
except IOError as e:
7+
print('First!')
8+
except Exception as e:
9+
print('Second')
10+
else:
11+
print(f.read())
12+
f.close()
13+
finally:
14+
print("Executing Finally...")
15+
16+
print('End of program')

Exceptions/test_file.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Test File Contents!

0 commit comments

Comments
 (0)