Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit47a213b

Browse files
Corey SchaferCorey Schafer
Corey Schafer
authored and
Corey Schafer
committed
Added Python code snippets
1 parentdf2e19b commit47a213b

File tree

34 files changed

+880
-0
lines changed

34 files changed

+880
-0
lines changed

‎.gitignore

Lines changed: 5 additions & 0 deletions
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
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
classEmployee:
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+
defemail(self):
13+
return'{}.{}@email.com'.format(self.first,self.last)
14+
15+
@property
16+
deffullname(self):
17+
return'{} {}'.format(self.first,self.last)
18+
19+
20+
emp_1=Employee('John','Smith')

‎Automation/rename.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
importos
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+
forfinos.listdir():
12+
# If .DS_Store file is created, ignore it
13+
iff=='.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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
functionhtml_tag(tag){
3+
functionwrap_text(msg){
4+
console.log('<'+tag+'>'+msg+'</'+tag+'>')
5+
}
6+
returnwrap_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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
# Closures
3+
4+
importlogging
5+
logging.basicConfig(filename='example.log',level=logging.INFO)
6+
7+
8+
deflogger(func):
9+
deflog_func(*args):
10+
logging.info(
11+
'Running "{}" with arguments {}'.format(func.__name__,args))
12+
print(func(*args))
13+
returnlog_func
14+
15+
16+
defadd(x,y):
17+
returnx+y
18+
19+
20+
defsub(x,y):
21+
returnx-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

Lines changed: 4 additions & 0 deletions
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

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
importdatetime
2+
importpytz
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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Decorators
2+
fromfunctoolsimportwraps
3+
4+
5+
defmy_logger(orig_func):
6+
importlogging
7+
logging.basicConfig(filename='{}.log'.format(orig_func.__name__),level=logging.INFO)
8+
9+
@wraps(orig_func)
10+
defwrapper(*args,**kwargs):
11+
logging.info(
12+
'Ran with args: {}, and kwargs: {}'.format(args,kwargs))
13+
returnorig_func(*args,**kwargs)
14+
15+
returnwrapper
16+
17+
18+
defmy_timer(orig_func):
19+
importtime
20+
21+
@wraps(orig_func)
22+
defwrapper(*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+
returnresult
28+
29+
returnwrapper
30+
31+
importtime
32+
33+
34+
@my_logger
35+
@my_timer
36+
defdisplay_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

Lines changed: 41 additions & 0 deletions
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

Lines changed: 49 additions & 0 deletions
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+
classDuck:
5+
6+
defquack(self):
7+
print('Quack, quack')
8+
9+
deffly(self):
10+
print('Flap, Flap!')
11+
12+
13+
classPerson:
14+
15+
defquack(self):
16+
print("I'm Quacking Like a Duck!")
17+
18+
deffly(self):
19+
print("I'm Flapping my Arms!")
20+
21+
22+
defquack_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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#BlueBook code decryption
2+
importsys
3+
defsieve(n):
4+
x= [1]*n
5+
x[1]=0
6+
foriinrange(2,n/2):
7+
j=2*i
8+
whilej<n:
9+
x[j]=0
10+
j=j+i
11+
returnx
12+
13+
defprime(n,x):
14+
i=1
15+
j=1
16+
whilej<=n:
17+
ifx[i]==1:
18+
j=j+1
19+
i=i+1
20+
returni-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)foriin [73,83,66,78,32,61,32]))
26+
foriinrange (0,4):
27+
sys.stdout.write(str(prime(code[i],x)-key[i]))
28+
29+
print

‎Exceptions/currupt_file.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Currupt File!

‎Exceptions/exceptions.py

Lines changed: 16 additions & 0 deletions
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+
exceptIOErrorase:
7+
print('First!')
8+
exceptExceptionase:
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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Test File Contents!

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp