Skip to content

Commit 37522a1

Browse files
committed
Trials
1 parent 60b81fc commit 37522a1

File tree

8 files changed

+261
-1
lines changed

8 files changed

+261
-1
lines changed

Notebooks/MyCheatsheet.ipynb

+64-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,70 @@
3333
"outputs": [],
3434
"source": [
3535
"li = [1, 10 ,2 ,22 ,454 ,64 ,778 ,845 ,32]\n",
36-
"la = [\"Ab\", \"a1\" , \"1A\", \"b!\", \"B1\"]"
36+
"la = [\"Ab\", \"a1\" , \"1A\", \"b!\", \"B1\"]\n",
37+
"lx = {1, 3, 5 ,2 ,1 , 8, 4}"
38+
]
39+
},
40+
{
41+
"cell_type": "code",
42+
"execution_count": 5,
43+
"metadata": {},
44+
"outputs": [
45+
{
46+
"output_type": "execute_result",
47+
"data": {
48+
"text/plain": [
49+
"{1, 2, 3, 4, 5, 8}"
50+
]
51+
},
52+
"metadata": {},
53+
"execution_count": 5
54+
}
55+
],
56+
"source": [
57+
"lx"
58+
]
59+
},
60+
{
61+
"cell_type": "code",
62+
"execution_count": 2,
63+
"metadata": {},
64+
"outputs": [
65+
{
66+
"output_type": "stream",
67+
"name": "stdout",
68+
"text": [
69+
"[1, 845]\n"
70+
]
71+
}
72+
],
73+
"source": [
74+
"final_list = list(filter(lambda x: (x%2 != 0) , li)) \n",
75+
"print(final_list) "
76+
]
77+
},
78+
{
79+
"cell_type": "code",
80+
"execution_count": 9,
81+
"metadata": {},
82+
"outputs": [
83+
{
84+
"output_type": "execute_result",
85+
"data": {
86+
"text/plain": [
87+
"'187'"
88+
]
89+
},
90+
"metadata": {},
91+
"execution_count": 9
92+
}
93+
],
94+
"source": [
95+
"from collections import namedtuple\n",
96+
"Person = namedtuple('Person', 'name height')\n",
97+
"person = Person('Jean-Luc', 187)\n",
98+
"f'{person.height}'\n",
99+
"'{p.height}'.format(p=person)"
37100
]
38101
},
39102
{

local/DataModel.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#Better say python data models than dunder methords
2+
3+
class Polynomail:
4+
def __init__(self, *coeffs):
5+
self.coeffs = coeffs
6+
7+
def __repr__(self):
8+
return 'Polynomial(*{!r})'.format(self.coeffs)
9+
10+
def __add__(self, other):
11+
return Polynomail(*(x + y for x, y in zip (self.coeffs, other.coeffs)))
12+
13+
def __len__(self):
14+
return len(self.coeffs)
15+
16+
p1 =Polynomail(1,2,3)
17+
p2 =Polynomail(2,3,4)
18+
19+
print(p1)
20+
21+
k = p1 + p2
22+
print(k)

local/RH/pickling.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import pickle
2+
import tempfile
3+
4+
#pickling and unpickling should be done using binary file since they support bytestream
5+
#to store structured data in a file
6+
7+
# pickle.dump(object, file) <- converts object to binary file
8+
9+
def storePickle():
10+
sagar = {'key': 'Sagar', 'name': 'Sagar Paul', 'age': 24, 'iq' : 10}
11+
nandini = {'key': 'Nandini', 'name': 'Nandini Chaudhary', 'age': 24, 'iq' : 60}
12+
13+
dbase = {}
14+
dbase['Sagar'] = sagar
15+
dbase['Nandini'] = nandini
16+
17+
try:
18+
dbFile = open('tryPickle', 'ab')
19+
pickle.dump(dbase, dbFile)
20+
finally:
21+
dbFile.close()
22+
23+
def storePickleTemp():
24+
sagar = {'key': 'Sagar', 'name': 'Sagar Paul', 'age': 24, 'iq' : 10}
25+
nandini = {'key': 'Nandini', 'name': 'Nandini Chaudhary', 'age': 24, 'iq' : 60}
26+
27+
temp = tempfile.TemporaryFile()
28+
29+
dbase = {}
30+
dbase['Sagar'] = sagar
31+
dbase['Nandini'] = nandini
32+
33+
try:
34+
temp.write(pickle.dumps(dbase))
35+
temp.seek(0)
36+
print(temp.read())
37+
finally:
38+
temp.close()
39+
40+
41+
def loadPickle():
42+
dbfile = open('tryPickle', 'rb')
43+
44+
dbase = pickle.load(dbfile)
45+
for k in dbase:
46+
print(k, dbase.get(k))
47+
48+
dbfile.close()
49+
50+
if __name__ == "__main__":
51+
storePickle()
52+
loadPickle()
53+
54+
55+

local/RH/unixSocket/client.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# -*- coding: utf-8 -*-
2+
import socket
3+
import os
4+
5+
print("Connecting...")
6+
if os.path.exists("/tmp/python_unix_sockets_example"):
7+
client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
8+
client.connect("/tmp/python_unix_sockets_example")
9+
print("Ready.")
10+
print("Ctrl-C to quit.")
11+
print("Sending 'DONE' shuts down the server and quits.")
12+
while True:
13+
try:
14+
x = input("> ")
15+
if "" != x:
16+
print("SEND:", x)
17+
client.send(x.encode('utf-8'))
18+
if "DONE" == x:
19+
print("Shutting down.")
20+
break
21+
except KeyboardInterrupt as k:
22+
print("Shutting down.")
23+
client.close()
24+
break
25+
else:
26+
print("Couldn't Connect!")
27+
print("Done")
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import socket
2+
import os
3+
4+
parent, child = socket.socketpair()
5+
6+
pid = os.fork()
7+
8+
if pid:
9+
print ('in parent, sending message')
10+
child.close()
11+
parent.sendall('ping')
12+
response = parent.recv(1024)
13+
print ('response from child:', response)
14+
parent.close()
15+
16+
else:
17+
print ('in child, waiting for message')
18+
parent.close()
19+
message = child.recv(1024)
20+
print ('message from parent:', message)
21+
child.sendall('pong')
22+
child.close()

local/RH/unixSocket/server.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# -*- coding: utf-8 -*-
2+
import socket
3+
import os
4+
5+
print("Opening socket...")
6+
server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
7+
server.bind("/tmp/python_unix_sockets_example")
8+
9+
print("Listening...")
10+
while True:
11+
datagram = server.recv(1024)
12+
if not datagram:
13+
break
14+
else:
15+
print("-" * 20)
16+
print(datagram.decode('utf-8'))
17+
if "DONE" == datagram.decode('utf-8'):
18+
break
19+
print("-" * 20)
20+
print("Shutting down...")
21+
server.close()
22+
print("Done")

local/something.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import asyncio, collections, curses, enum, random
2+
3+
P = collections.namedtuple('P', 'x y') # Position
4+
D = enum.Enum('D', 'n e s w') # Direction
5+
6+
def main(screen):
7+
curses.curs_set(0) # Makes cursor invisible.
8+
screen.nodelay(True) # Makes getch() non-blocking.
9+
asyncio.run(main_coroutine(screen)) # Starts running asyncio code.
10+
11+
async def main_coroutine(screen):
12+
state = {'*': P(0, 0), **{id_: P(30, 10) for id_ in range(10)}}
13+
moves = asyncio.Queue()
14+
coros = (*(random_controller(id_, moves) for id_ in range(10)),
15+
human_controller(screen, moves),
16+
model(moves, state, *screen.getmaxyx()),
17+
view(state, screen))
18+
await asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED)
19+
20+
async def random_controller(id_, moves):
21+
while True:
22+
moves.put_nowait((id_, random.choice(list(D))))
23+
await asyncio.sleep(random.random() / 2)
24+
25+
async def human_controller(screen, moves):
26+
while True:
27+
ch = screen.getch()
28+
key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w}
29+
if ch in key_mappings:
30+
moves.put_nowait(('*', key_mappings[ch]))
31+
await asyncio.sleep(0.01)
32+
33+
async def model(moves, state, height, width):
34+
while state['*'] not in {p for id_, p in state.items() if id_ != '*'}:
35+
id_, d = await moves.get()
36+
p = state[id_]
37+
deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
38+
new_p = P(*[sum(a) for a in zip(p, deltas[d])])
39+
if 0 <= new_p.x < width-1 and 0 <= new_p.y < height:
40+
state[id_] = new_p
41+
42+
async def view(state, screen):
43+
while True:
44+
screen.clear()
45+
for id_, p in state.items():
46+
screen.addstr(p.y, p.x, str(id_))
47+
await asyncio.sleep(0.01)
48+
49+
curses.wrapper(main)

tryPickle

238 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)